blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
3c55e208d740d938a13acd27fab92876a53c5ab4 | MadmanSilver/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/100-print_tebahpla.py | 148 | 3.53125 | 4 | #!/usr/bin/python3
i = 25
while i > -1:
if i % 2:
m = 97
else:
m = 65
print("{}".format(chr(i + m)), end="")
i -= 1
|
53abf3765bba1a488d830c47c04160059cc0b41b | neilwithdata/pythonmorsels | /add/add.py | 521 | 3.53125 | 4 | def add(*matrices):
rows, cols = len(matrices[0]), len(matrices[0][0])
# Check all matrices have the same number of rows
if not all(len(matrix) == rows for matrix in matrices):
raise ValueError("Given matrices are not the same size.")
# Check all rows have the same number of columns
if not... |
6f8f84b3ab5f996453a0b5a9dba6a6e858c91f72 | SamueldaCostaAraujoNunes/ColorWindowsLed | /color.py | 3,710 | 3.5625 | 4 | from typing import Tuple
class Color:
def __init__(self, color, standard):
self.standard = self.verify_standard(standard)
self.color = self.verify_color(color)
self.functions_color = {('RGB', 'HEX'): self.rgb_to_hex, ('HEX', 'RGB'): self.hex_to_rgb}
def verify_standard(self, standard)... |
bdcb3a4e53c7632cfa3fd3b3f8f63ed92b749d80 | fatecoder/Python-practices | /list_comp.py | 206 | 3.765625 | 4 | #!/bin/python
#even_squares = [x%2==0 for x in range(1, 11)]
even_squares = [x**2 for x in range(2, 11, 2)]
print even_squares
even_squares2 = [x**2 for x in range(1, 11) if x%2==0]
print even_squares2
|
f31a63242dae74dcb863f4ff1b4d3b923fe3d22f | fatecoder/Python-practices | /exe7.py | 855 | 4.0625 | 4 | #!/bin/python
import math
from random import randrange
numero = randrange(-100,100)
#print dir(math)
#print dir(randrange)
print "################################################"
print "Numero: %i" %numero
if numero < 0 :
numero = abs(numero)
print "La raiz es: %f" %math.sqrt(numero)
print "Potencia al cuadrad... |
3970e5e6d2fedd9f1eaa243d982d95d8a05322bb | fatecoder/Python-practices | /cadena.py | 635 | 3.84375 | 4 | #!/bin/python
str1 = raw_input("Ingresa el primer string: ")
str2 = raw_input("Ingresa el segundo string: ")
ini = 0
fin = len(str2)
acum = 0
def contar_veces (ini, fin, str1, str2, acum):
if len(str1) >= fin :
#print str1[ini:fin]
if str1[ini:fin] == str2 :
acum = acum + 1
ini... |
aef54f093c26995c87c9e5dadc69fb2a1f453495 | chetanbala-thunga/python | /calculator.py | 1,519 | 4.09375 | 4 | calc_on = 1
def addition():
print("Adding two values")
first = float(raw_input('What is your first number?'))
second = float(raw_input('What is your second number?'))
print(first + second)
def subtraction():
print("Substracting two values")
first = float(raw_input('What is your first number?')... |
1f44db5874020fcf3e221e01bce62b793379be06 | W0uterdeBoer/Exercises | /Divisorfinder.py | 2,130 | 3.640625 | 4 | from graphics import *
import math
max_i = 100
Graph_sides = int(math.sqrt(max_i))
print("Graphsides= ", Graph_sides)
win = GraphWin("My bar", Graph_sides * 10, Graph_sides * 10)
def main2():
all_divisors = finddivisors(max_i)[0]
primes = finddivisors(max_i)[1]
i = 0
while i < max_i:
... |
393c711aceaa405d0055b59891fb6e9c5a154b41 | TheCDC/cbu_csse_euler | /euler_024/Christopher D Chen/euler_024.py | 731 | 3.65625 | 4 | digits = set(range(10))
def generate_pandigitals(current=None, unused=None):
if not current:
current = []
if not unused:
unused = set(digits)
if len(unused) == 1:
# yield a single item list
# this allows for results to be concatenated
yield current + [next(i... |
f4bb7f1961f46b94961fd5649b09d001e19afed4 | TheCDC/cbu_csse_euler | /euler_018/Christopher D Chen/euler_018.py | 2,958 | 3.828125 | 4 | #!/usr/bin/env python3
"""
Problem 18: Maximum path sum I
By starting at the top of the triangle below and moving to adjacent
numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
... |
8e0f7f62bebfa5f4aa6c81d91e2b5bdaa09c9ba2 | TheCDC/cbu_csse_euler | /euler_027/Chris Nugent/PE27.py | 2,070 | 3.75 | 4 | import functools
import multiprocessing
import os
@functools.lru_cache(maxsize=None)
def is_prime(num):
if num == 2:
return True
if num % 2 == 0 or num < 0:
return False
check = 3
while check * check <= num:
if num % check == 0:
return False
check += 2
r... |
da373b579653e76fdfa78659109586dcbdb2ac6c | TheCDC/cbu_csse_euler | /euler_021/Chris Nugent/euler_021.py | 502 | 3.5625 | 4 | from functools import lru_cache
from math import ceil
def divisors(n):
divs = {1}
for i in range(2, ceil(n**(1 / 2))):
if n % i == 0:
divs.update([i, n // i])
return divs
@lru_cache(maxsize=None)
def d(n):
return sum(divisors(n))
def main(n):
known = set()
for a in rang... |
b3c406b38a2a87ec02607ae0c0ea27117bc83c0c | TheCDC/cbu_csse_euler | /euler_005/Christopher D Chen/euler_005.py | 1,268 | 3.84375 | 4 | #!/usr/bin/env python3
def isPrime(n):
for i in range(2, int(n**(1 / 2)) + 1):
if n % i == 0:
return False
return True
def pfactors(n):
res = []
if isPrime(n) or n == 4:
return [n]
while not isPrime(n):
for i in range(2, int(n**(1 / 2)) + 1):
if is... |
4f02459b200b9c61fdc96b717cc339ba9b4271c5 | Kimonili/data-structures-and-algorithms-python | /stack_reverse_string.py | 696 | 4.0625 | 4 | from collections import deque
class Stack:
def __init__(self):
self.container = deque()
def push(self,val):
self.container.append(val)
def pop(self):
return self.container.pop()
def peek(self):
return self.container[-1]
def is_empty(self):
return len(self.container)==0
def size(self):
ret... |
b53773fbc6ed0d4de74b35df96ee85bb6fc0ceb2 | Amagash/machine_learning_ud120 | /datasets_questions/explore_enron_data.py | 2,015 | 3.515625 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
ea104f260c04d3f7bbf7367f42aa08c55a958f1c | sanjeevs/AlgoByTimPart1 | /assignment3/test/test_qsort.py | 781 | 3.609375 | 4 | from qsort.qsort import *
import unittest
from random import randint
class MyTest(unittest.TestCase):
def test_qsort1(self):
a = [3, 8, 2, 5, 1, 4, 7, 6]
num_cmps = 0
qsort(a, 0, len(a) -1, num_cmps)
self.assertEqual([1,2,3,4,5,6,7,8], a)
def test_rand1(self):
randints = []
for _ in range... |
b141ddc29c11db608d165e4c1a9062f27671bee6 | sanjeevs/AlgoByTimPart1 | /assignment3/qsort/qsort.py | 2,243 | 4.1875 | 4 | from math import floor
def qsort(a, lhs, rhs, num_cmps):
""" Sort the array and record the number of comparisons.
>>> a = [2,1]
>>> num_cmps = 0
>>> qsort(a, 0, 1, num_cmps)
1
>>> print(a)
[1, 2]
"""
if((rhs - lhs) >= 1):
num_cmps += (rhs - lhs)
pivot = partition(a, lhs, rhs)
num_cmps =... |
2ed279c417d060bb07233d96fc30feeee8607419 | Donicia/Homework3 | /PyPoll/main.py | 2,051 | 3.765625 | 4 | import os
import csv
election_data = r'C:\Users\donic\Desktop\CLASS\RICEHOU201906DATA1\HW\03-Python\Instructions\PyPoll\Resources\election_data.csv'
votes = 0
Candidate =[]
Candidates = {"Khan":0,"Correy":0,"Li":0,"O'Tooley":0}
Candidates_Per = {"Khan":0,"Correy":0,"Li":0,"O'Tooley":0}
List = {"Khan", "Corr... |
d4576d365d88c995dea71cad2dbd05ebe63988e1 | abdulahi1000/python-project | /project4-1.py | 1,032 | 3.96875 | 4 | # try exception handling
# 1. FileNotFoundError
# raised when a file or directory is requested but doesn’t exist.
# Example
try:
file_name = 'myfile.txt'
with open(file_name) as f:
print(f)
except:
print("File Not Found")
# 2. Exception FileExistsError
# Raised when trying to create a file or direct... |
22e283d052f9b9931bf09c823dfb93dba87b33ed | Aijaz12550/python | /list/main.py | 953 | 4.375 | 4 |
#########################
##### remove method #####
#########################
list1 = [ 1, 2, True, "aijaz", "test"]
"""
list.remove(arg) it will take one item of list
as a argument to remove from list
"""
list1.remove(1) # it will remove 1 from list1
#list1.remove(99) # it will throw error because 99 is not exi... |
89cfbb12e1226acb21867932f6a1a76557b04214 | gainfoe/NguyenQuangAnh_c4t3_S3 | /dem_chu_theo_bang_chu_cai.py | 282 | 4.03125 | 4 | str_nhap = sorted(input("Nhap tu: ").lower())
alphabet = "qwertyuiopasdfghjklzxcvbnm"
letters = {}
for letter in str_nhap:
if letter in alphabet and letter not in letters:
letters[letter] = []
print("So chu cai la:")
for letter in letters:
print(letter + ":", str_nhap.count(letter))
|
88e4b65456f59fc1ef6ba41e469a9c6cddfe2ac7 | pdhummel/practice | /leetcode/first-missing-positive.py | 1,719 | 3.75 | 4 | #!/usr/bin/python
import sys
import time
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
found_num = set()
missing_num_set = set()
missing_num_set.add(1)
missing_num = 1
... |
956f4a8497ea4d1dcca292eb4d98009aff89af9d | pdhummel/practice | /reverse_string.py | 510 | 3.75 | 4 | #!/usr/bin/python
import sys
import ctypes
def main(args):
if len(args) > 1:
reverse_string(args[1])
def reverse_string(str2rev):
mutable = ctypes.create_string_buffer(str2rev)
for i in range(len(str2rev)):
j = len(str2rev) - i - 1
if i >= j:
break
... |
4923f19a1086cd3a12203af926840edba8193d3c | RajashriN/CreaTe-Python | /Chapter3_Challenges_HeleenKok.py | 6,158 | 4.5625 | 5 | __author__ = 'heleenkok'
#Student Number: S1183435
#Python_Programming Chapter 3
#The end assignment from chapter 3
# Challenges:
# 1. Write a program that simulates a fortune cookie. The program should display one of five unique fortunes, at random, each time it’s run.
# 2. Write a program that flips a coin 100 times... |
bfdcdd33e0984845295981c206272ca9f11355b8 | DragonKoc/ITEA | /0402/04_function_hard.py | 643 | 3.90625 | 4 | def f(x):
return 2*x
double = f
print(double(2))
##################
print('######')
def execute (f,x):
return f(x)
print(execute(double,5))
##################
print('######')
def f():
def g(x):
return 3*x
return g
print(double(2))
print(f()(2))
##################
print('######map')
map... |
ddf3fbd69841bd21c7108c93b99a9f413b2b589c | DragonKoc/ITEA | /2801/task3_while.py | 373 | 3.71875 | 4 |
i = 0
# while i<5:
# print(i)
# i +=1
# while True:
# pass
try:
while i <= 10:
print(1+i)
i +=1
if i == 5:
print('continue')
continue
print('after contiue')
elif i == 7:
print('breack')
break
except:
pri... |
4618b3ed36dabcafed233d3e85a1e2c1251b271b | DragonKoc/ITEA | /2002/20_3.py | 1,142 | 3.75 | 4 | class ReprMixin:
# только методы без состояний
def __repr__(self):
return "{}({})".format(
self.__class__.__name__,
','.join(f"{name}={value}" for name , value in vars(self).items())
)
class EqMixin:
def __eq__(self, other):
#vars - все поля и все значения
... |
8e535eee69266f51080a2577c504dbb33bd463d3 | DragonKoc/ITEA | /2801/tes1.py | 1,134 | 3.5 | 4 | i = 1000
# while i>100:
# print(i, end=' ')
# i /=2
for j in 'hello world':
if j=='h':
continue
print(j * 2, end ='')
else:
print('end with break')
a=5
lis = [1,22,333]
print(lis)
lis.append(56)
print(lis)
lis.extend([45,34])
print(lis)
a = [a + b for a in 'kostya' if a!='s' for b in 'g... |
43224d710674f33eafd7a5d1b0feb25bfec35141 | FlyingEwok/Linear-BinarySearch | /binarysearch.py | 1,116 | 4.21875 | 4 | def binarySearch (list, l, listLength, value):
# Set up mid point variable
if listLength >= l:
midPoint = l + (listLength - l) // 2
if list[midPoint] == value: # return the midpoint if the value is midpoint
return midPoint
elif list[midPoint] > value: # Do a search to... |
499581bb47a86a0632b19edbb323ee8237da9dd6 | jmfuch02/advent2018 | /advent2-1.py | 754 | 3.8125 | 4 |
def compute_checksum(input: list):
two_times: int = 0
three_times: int = 0
for item in input:
counter = {}
for letter in item:
if letter not in counter:
counter[letter] = 1
else:
counter[letter] += 1
if 2 in counter.values():... |
a525a1d61778c525286ec01c6cff5ab887a9d90e | Wsky51/ML-DL_MyselfCodes | /各种权重初始化方法.py | 5,056 | 3.53125 | 4 | #对比几种初始化方法
import numpy as np
import matplotlib.pyplot as plt
#1,初始化为0
def initialize_parameters_zeros(layers_dims):
"""
Arguments:
layer_dims -- python array (list) containing the size of each layer.
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
W1 -- weigh... |
e840a4beac5dc3f15f45923bcfd33f3509df09f2 | archanrr/Python-Programs | /Convert_sentence_to_morse.py | 856 | 3.734375 | 4 |
import json
import sys
def main():
print("Welcome to Morse command prompt")
input_string = input("Enter the sentence: ") # Getting input from user
print("\nMorse code for {} is".format(input_string))
input_string = input_string.lower()
# open json file as object
with open('moorse-code', ... |
0c98cf632b5e8638d1eb2e1f576b0bf667c10fe1 | YunusEmreAlps/Python-Basics | /3. Advanced/Inheritence.py | 2,315 | 4.25 | 4 | # Inheritence (Kalıtım)
# Inheritance belirttiğimiz başka classlardaki method ve attribute'lara erişmemizi sağlar.
# Diyelim ki farklı tipte çalışanlar yaratmak istiyorum IT ve HR olsun.
class Employee:
raise_percent = 0.5
num_emp = 0
def __init__(self, name, last, age, pay):
self.name = name... |
62237ae4ae5033ecf30d2f578aae1a909e34d42b | YunusEmreAlps/Python-Basics | /2. Basic/Non-scalar Veri Tiplerinde For.py | 1,761 | 3.859375 | 4 | # Non-Scalar For
# --------- List ---------
grades = [90, 72, 81, 77]
for i in grades:
print(i)
# 90
# 72
# 81
# 77
total = 0
for i in grades:
total += i
average = (total / (len(grades)))
print("Average: "+str(average))
for i in range(len(grades)):
print("Iteration :"+str(i))
print(grades) # [90,... |
c0b54db814c2b03264b46d1ee6868d09aae6e11d | YunusEmreAlps/Python-Basics | /2. Basic/Patika.py | 1,022 | 4.03125 | 4 | # PROJECT
flat_list = []
# Q1: Bir listeyi düzleştiren (flatten) fonksiyon yazın.
# Elemanları birden çok katmanlı listelerden ([[3],2] gibi) oluşabileceği gibi, non-scalar verilerden de oluşabilir.
# input: [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
# output: [1,'a','cat',2,3,'dog',4,5]
def solution1(arr):
# it... |
15bf570be794b9919f43b5786f61a8a97eb81d31 | YunusEmreAlps/Python-Basics | /2. Basic/Output.py | 1,846 | 4.34375 | 4 | # --------------------
# Example 1 (Output)
# This is comment
"""
This
is
multi-line
comments
"""
# if you want to show something on console
# you need to use a "print" instruction
# syntax:
# print('Message') -> single quotes
# print("Message") -> double quotes
print(' - Hello World!')
print(" - I love Python pr... |
19be701b4dee8fff590fdb72f6ce6ced9c7eae2a | veeneel/GridSolver | /CppDemo/GridTest.py | 1,928 | 3.5 | 4 | import csv
import bisect
# grid size = 4 (min), 100 (max)
squares = [x*x for x in range(2,11)]
#print(squares)
# nextHighest = lambda seq,x: min([(i-x,i) for i in seq if x<=i] or [(0,None)])[1]
# nextLowest = lambda seq,x: min([(x-i,i) for i in seq if x>=i] or [(0,None)])[1]
def validate(fname):
print('Input Fil... |
f5f54b5db00added0abbf07df9fa2c38bb2e2fbc | compsciprep-acsl-2020/2019-2020-ACSL-Python-Akshay | /class10-05/calculator.py | 844 | 4.21875 | 4 | #get the first number
#get the second number
#make an individual function to add, subtract, multiply and divide
#return from each function
#template for add function
def add(num1, num2):
return (num1+num2)
def sub(num1, num2):
return (num1-num2)
def multiply(num1, num2):
return (num1*num2)
def division... |
d938608a76e72261a3fe71c38a6d75c434315800 | StevenSadler/AIND-Isolation | /stub_board.py | 6,570 | 4.25 | 4 | """
This file contains the `Board` class, which implements the rules for the
game Isolation as described in lecture, modified so that the players move
like knights in chess rather than queens.
You MAY use and modify this class, however ALL function signatures must
remain compatible with the defaults provided, and none... |
04f69fb9ea8ff0ad3cb052883d5d75632daeade7 | ivmtorres/OpenCV-1 | /31.Detect_Corners_using_Harris_Corner_Detector/Detect_Corners_using_Harris_Corner_Detector.py | 1,168 | 3.53125 | 4 | # Harris Corner Detector
# Corners are regions with large variation in the intensity in all the directions.
# It contains three main steps :
# 1. Determine which windows produce very large variations in intensity when moved in both X and Y directions.
# 2. With each such window found a score R is computed.
# 3. Af... |
f854478c9d2851fda210df04d7c8c36d6e1008e3 | ivmtorres/OpenCV-1 | /10.Bind_Trackbar/Change_color_using_trackbar_switch.py | 963 | 3.765625 | 4 | # change colors using trackbar using switch.
import numpy as np
import cv2 as cv
def nothing(x):
print(x)
img = np.zeros((300,512,3),np.uint8)
cv.namedWindow('image') # Create a window with name 'image'
cv.createTrackbar('B', 'image', 0, 255, nothing) # Trackbar_Name, Window_Name, initial_value, Final_... |
681ac7bfeac29a22b7689221ff55dd10ca7db676 | ChrisLR/BFLib | /bflib/characters/abilityscores/base.py | 754 | 3.5 | 4 | import abc
class AbilityScore(object):
__metaclass__ = abc.ABCMeta
__slots__ = ["value"]
_modifier_table = {
3: -3,
4: -2,
5: -2,
6: -1,
7: -1,
8: -1,
9: 0,
10: 0,
11: 0,
12: 0,
13: 1,
14: 1,
15: 1,
... |
211e5843e73e12ed17babd1a823a44bfadbffd17 | wangtao10494/api | /alien_invasion/matplotlib/random_die.py | 463 | 3.609375 | 4 | from random import choice
from random import randint
class Random_die():
def __init__(self,num_points=2,num_sides=6):
self.num_points = num_points
self.num_sides = num_sides
"""开始时没有坐标"""
self.x_values=[]
self.y_values=[]
def roll(self):
return randint(1,self.num_sides)
def fill_walk(self):
fo... |
67a35cec9980373961eba321fa878983130369e9 | vassmate/Learn_Python_THW | /mystuff/ex15.py | 212 | 3.984375 | 4 | # http://learnpythonthehardway.org/book/ex15.html
print "Please enter the file name here: "
filename = raw_input("> ")
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
txt.close() |
8d438c71959d3fd16bffc44490bdfea783fcf61d | vassmate/Learn_Python_THW | /mystuff/ex3.py | 1,312 | 4.8125 | 5 | # http://learnpythonthehardway.org/book/ex3.html
# This will print out: "I will count my chickens:".
print "I will count my chikens:"
# This will print out how much Hens we have.
print "Hens", 25.0 + 30.0 / 6.0
# This will print out how much roosters we have.
print "Roosters", 100.0 - 25.0 * 3.0 % 4.0
# This will pr... |
1bd1431550433e411757182599741bfc865f7e39 | GithubWangXiaoXi/Time_Series_Analysis | /src/model/GM.py | 1,406 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
class GM:
def paramSetter(self):
# 使用GM(1,1)模型,无参数设置
pass
def fit(self):
# GM模型无需训练
print("GM fit")
def predict(self, X, K):
print("GM predict")
"""
Return the predictions through GM(1, 1).
... |
741c4b7001847616f27cd35228d6369dab972d29 | IronManZheng/GraphicCaculate_cloud | /people_class.py | 921 | 3.703125 | 4 | class People(): #定义人员的类
def __init__(self,name,next,edge):
self.name = name
self.next = []
self.edge = ()
def put_next(self,people_class): #给下一跳next赋值
self.next.append(people_class)
def put_edge(self,edge_name,width): #给两跳之间的连线也就是边赋值
self.e... |
7e23563c827b797bcb11bf669533fff78fc759ff | ksnt/Euler | /problem42.py | 1,159 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ksnt
def main():
f = open("words.txt","r")
data = f.read()
data_split = data.split(',')
str_data = []
f.close()
for i in data_split:
str_data.append(i.strip("\"")) # '"'を取り除く
result = []
for i in str_data:
result.append(sum... |
05ea77a096dac9ea5c5f9b711d2a088ef70b1be1 | rpatillo/Python-Matrice | /Pokemon/04_poke_types/pokeball.py | 821 | 3.703125 | 4 | import sys
from pokemon import Pokemon
class Pokeball:
pokemon = None
def __init__(self, pokemon=None):
if pokemon != None:
self.store(pokemon)
def __str__(self):
if self.pokemon == None:
return("An empty pokeball")
else:
return(str(sel... |
52480fd2a516e8b889ea9f8f86c102f62c9f7383 | XiyunLiu/STLeetcode | /281. Zigzag Iterator.py | 1,621 | 3.78125 | 4 | __author__ = 'liuxiyun'
class ListNode(object):
def __init__(self,val):
self.val = val
self.next = None
class ZigzagIterator(object):
def __init__(self, v1, v2):
"""
Initialize your data structure here.
:type v1: List[int]
:type v2: List[int]
"""
... |
034373050d319b47889520057ac923efbd9cc2e2 | XiyunLiu/STLeetcode | /288. Unique Word Abbreviation.py | 974 | 3.609375 | 4 | __author__ = 'liuxiyun'
class ValidWordAbbr(object):
def __init__(self, dictionary):
"""
initialize your data structure here.
:type dictionary: List[str]
"""
self.word_dic = {}
for word in dictionary:
key = self.getKey(word)
if key in self.word... |
52c689ba66d7c8a442195e93a23474d89c5da6cf | aaron-xyz/CS50 | /pset6/vigenere.py | 1,854 | 3.828125 | 4 | """
Pset6: Vigenere
From pset1 - vigenere
imported from C to Python
$ python vigenere.py ABC
plaintext: HELLO
ciphertext: HFNLP
$ python vigenere.py bacon
plaintext: Meet me at the park at eleven am
ciphertext: Negh zf av huf pcfx bt gzrwep oz
"""
import sys
def main():
# check correct number or inputs
if l... |
a7accddf475b97f65173dd098bb0c703b5de5aca | codeAligned/CS156 | /hw4/problem7.py | 6,441 | 3.5625 | 4 | import random
import math
import numpy as np
import numpy.linalg as linalg
import matplotlib.pyplot as plt
def dot(list1, list2):
assert(len(list1) == len(list2))
result = 0
for i in range(len(list1)):
result += (list1[i] * list2[i])
return result
def generatePoint():
x = random.uniform(-1,1)
y = random.uni... |
fdacb2906e0822d1234549419b8695bd467ec4e4 | GlaucioSales/paradigmas-2019 | /perso/Personalizada2.py | 5,147 | 3.609375 | 4 | #Crie uma função isVowel :: Char -> Bool que verifique se um caracter é uma vogal ou não.
def isVowel(c):
if c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u':
return True
else:
return False
#Escreva uma função addComma, que adicione uma vírgula no final de cada string contida num... |
b087f330b72cfcde0342e2d835d9adb684a12123 | akashpakkan/Reinforcement-Learning-based-Tic-Tac-Toe | /Reinforcement Learning based Tic Tac Toe/ML task.py | 8,042 | 3.734375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # ML Task - 01 (The Robotics Forum)
# ### Mentor Shripad Kulkarni
# #### Preeti Oswal, Aryan Gupta, Avinash Vijayvargiya
#
# ## Importing all required lib
# In[1]:
import numpy as np
import pickle
# ### Developing board and funcation to game play
# In[2]:
class Game:
... |
bb69b0aa43fa4249d3a392f643e07d6c699d22de | celeste16/gwc-2017 | /triangle.py | 466 | 4.09375 | 4 | from turtle import *
import math
# Name your Turtle.
t = Turtle()
# Set Up your screen and starting position.
t.penup()
setup(500,300)
x_pos = -0
y_pos = -0
t.setposition(x_pos, y_pos)
### Write your code below:
t.pendown()
t.pencolor("black")
t.fillcolor("hot pink")
t.begin_fill()
t.forward(100)
... |
2fa79815188096b82806ce536187c9555c1d682b | Zuck84/Money-Convertor | /For Linux & Mac OS/ConvertingMoney.py | 11,050 | 4.0625 | 4 | from decimal import Decimal
import os
os.system("clear")
# EVENTS OF THE PROGRAM
def Dollar():
final_currency_dollar = input ("\n New Currency ---> ")
final_currency_dollar = float(final_currency_dollar)
if final_currency_dollar == 2:
initial = input("\n $")
initial = floa... |
2fd7d2546a5bc41e1e9daee2c1c17060afede28d | thenickforero/holbertonschool-machine_learning | /supervised_learning/0x00-binary_classification/6-neuron.py | 7,567 | 4.34375 | 4 | #!/usr/bin/env python3
"""Module that contains a basic implementation of a Neuron
that performs binary classification.
"""
import numpy as np
class Neuron():
"""Class that defines a single neuron performing binary classification.
"""
def __init__(self, nx):
"""Initialize a Neuron instance accordi... |
1abd8eea6ff68cbb119651fc9e978bef80dfa1a8 | thenickforero/holbertonschool-machine_learning | /math/0x00-linear_algebra/2-size_me_please.py | 577 | 4.4375 | 4 | #!/usr/bin/env python3
"""Module to compute the shape of a matrix"""
def matrix_shape(matrix):
"""Calculates the shape of a matrix.
Arguments:
matrix (list): the matrix that will be processed
Returns:
tuple: a tuple that contains the shape of every dimmension
in the matr... |
79969b00b7683284a24114fa72d3b613caf1d3d2 | thenickforero/holbertonschool-machine_learning | /math/0x00-linear_algebra/14-saddle_up.py | 598 | 4.15625 | 4 | #!/usr/bin/env python3
"""Module to compute matrix multiplications.
"""
import numpy as np
def np_matmul(mat1, mat2):
"""Calculate the multiplication of two NumPy Arrays.
Arguments:
mat1 (numpy.ndarray): a NumPy array that normally represents a square
matrix.
... |
78c1d41234eac73a6a458bc23d73b63ada9d9d84 | M-Mazzoleni96/Landmark-Based-Navigation---Tesi-laurea-2020 | /Progetto/Dijkstra.py | 1,871 | 3.78125 | 4 |
def dijsktra(graph, initial, end):
global total_weight
global pesi
# shortest paths is a dict of nodes
# whose value is a tuple of (previous node, weight)
shortest_paths = {initial: (None, 0)}
current_node = initial
visited = set()
total_weight = 0
pesiParz = []
pesi ... |
0e6bbe6bb462b23c7588eebb661a01880653de4a | tanvirarafin/l2race | /src/car_command.py | 1,226 | 3.703125 | 4 | # structure to hold driver control input
class car_command:
""" Car control commands from software agent or human driver
"""
def __init__(self):
self.steering=0 # value bounded by -1:1, this is the desired steering angle relative to maximum value and it is only the desired steering angle; actual s... |
8b86c897a10bb9910e27ec82354136fc9a3c1e38 | ErikPerez312/CS-3-Core-Data-Structures | /source/palindromes.py | 3,529 | 4.40625 | 4 | #!python
import string
import re
# Hint: Use these string constants to ignore capitalization and/or punctuation
# string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz'
# string.ascii_uppercase is 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# string.ascii_letters is ascii_lowercase + ascii_uppercase
LETTERS = string.ascii_letters
... |
9590f0ee2cd0330f7acddc3856923b5356db6698 | hirosige/python-guys | /008 module/teacher.py | 561 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 13 13:24:21 2017
@author: mysurface
"""
class Teacher:
def __init__(self, name):
self.students = []
self.average = 0
self.name = name
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
... |
a403e25b42db8d2b9033c06b5aac45074300d4b3 | dkrusch/python | /lists/planets.py | 1,109 | 4.40625 | 4 | planet_list = ["Mercury", "Mars"]
planet_list.append("Jupiter")
planet_list.append("Saturn")
planet_list.extend(["Uranus", "Neptune"])
planet_list.insert(1, "Earth")
planet_list.insert(1, "Venus")
planet_list.append("Pluto")
slice_rock = slice(0, 4)
rocky_planets = planet_list[slice_rock]
del[planet_list[8]]
# Use appe... |
5cb1287e6fa4f8bd84535bbda3ebe49acc265189 | dkrusch/python | /lightning/garrys-garage/garage.py | 2,479 | 3.75 | 4 | class Car:
def __init__(self, manufacturer="", model="", horsepower=0, wheel_count=0):
self.manufacturer = manufacturer
self.model = model
self.horsepower = horsepower
self.wheel_count = wheel_count
class GasPowered(Car):
def __init__(self, capacity):
super().init(manu... |
174008d5ff445a72a43b6f626b6186d1af637208 | heigre/Prime | /primechecker.py | 513 | 3.59375 | 4 | n = []
checker = []
x = 213
for y in range (2, x+1):
z = x/(float(y))
checker.append(z)
#print checker
print z
for k in range (0, x-1):
p = checker[k]
if p.is_integer() == True:
n.append(1)
else:
s=0
if sum(n) > 1:
print ""
print ""
print ""
... |
d5229e9967b6cd88ce6ecb2913a59248c6994e09 | ballipongala/sqlworkshops | /PythonForDataProfessionals/Python for Data Professionals/code/02_ProgrammingBasics.py | 1,798 | 4.0625 | 4 | # 02_ProgrammingBasics.py
# Purpose: General Programming exercises for Python
# Author: Buck Woody
# Credits and Sources: Inline
# Last Updated: 27 June 2018
# 2.1 Getting Help
help()
help(str)
# <TODO> - Write code to find help on help
# 2.2 Code Syntax and Structure
# <TODO> - Python uses spaces to indicate code... |
fdcd57fd81cc62bc189b9a23f762dc3991d3922f | andystjean1/nba-totals-analysis | /data_cleaner.py | 7,558 | 3.65625 | 4 |
#clean up and reshape the data from the excel file
import datetime
import pandas as pd
import sys
DATA_FILE = "nba_odds_2019-20.xlsx"
TEAM_ABV_DICT = {"GoldenState":"GSW",
"Boston":"BOS",
"NewOrleans":"NOP",
"Toronto":"TOR",
"LALakers":"LAL",
... |
94d4dae91040dd8a74cce61e0977cc3931760ac0 | mali44/PythonPracticing | /Palindrome1.py | 645 | 4.28125 | 4 |
#Ask the user for a string and print out whether this string is a palindrome or not.
#(A palindrome is a string that reads the same forwards and backwards.)
mystr1= input("Give a String")
fromLeft=0
fromRight=1
pointer=0
while True:
if fromLeft > int(len(mystr1)):
break
if fromRight > int(len(mys... |
8b20bc0ca433632db5d3e5f3e6a3284fb504c3e5 | MinChul-Son/study_Phython | /day1/day1.py | 8,744 | 3.640625 | 4 | from copy import copy # copy라이브러리 import
print("hello")
# 이건 주석이에요
a = "hobby"
# 원하는값 count함수
print(a.count("b"))
# 원하는 값 find 함수(첫번째로 찾은 값의 인덱스 return), 비슷함 함수로 index함수도 있는데 이건 찾는 값있으면 index리턴 없으면 에러
print(a.find("b"))
# 원하는 문자열 삽입
a = ","
print(a.join('abcd')) # ==>결과:a,b,c,d
# 공백지우기
a = " hi "
print(a.strip())
# ... |
118535cb3faadb606b2b4803ead697867a76ba1f | osatooh/CIDM6303code | /assignment-python-chapter-1/app.py | 593 | 3.5 | 4 | print("syntax error means there is a problem in the grammar of the expression")
print("." * 5)
print("An IDE is a code editor with features for autocompletion and debugging.")
print("." * 10)
print("File extensions for a python app is .py")
print("." * 15)
print("A linter is to check for syntax errors.")
print("." * 20... |
620709285099d86166721d8d860aeb940269982a | sourcedexter/IBM-NLU | /text_analyser.py | 9,734 | 3.640625 | 4 | """
Script to analyse text and gain insights into unstructured data such as Sentiment and Emotion.
The complete tutorial can be found at: https://sourcedexter.com/product-review-sentiment-analysis-with-ibm-nlu
Author: Akshay Pai
Twitter: @sourcedexter
Website: https://sourcedexter.com
Email: akshay@sourcedexter.com
""... |
71dad1096b5699d19ad30d431d025aa12b8165f4 | E-Cell-VSSUT/coders | /python/IBAN.py | 2,276 | 4.125 | 4 | # IBAN ( International Bank Account Number ) Validator
'''
An IBAN-compliant account number consists of:
-->a two-letter country code taken from the ISO 3166-1 standard (e.g., FR for France, GB for Great Britain, DE for Germany, and so on)
-->two check digits used to perform the validity checks - fast and simple, but n... |
68e650fa51502dcc2a1e15bb7b956cb0c8630c58 | E-Cell-VSSUT/coders | /python/Fibonacci.py | 750 | 4.3125 | 4 | # -- Case-1 -->> Using Function
# This is a program to find fibonacci series using simple function
def fib(n):
if n < 1: # Fibonacci is not defined for negative numbers
return None
if n < 3: # The first two elements of fibonacci are 1
return 1
elem1 = elem2 = 1
sum = 0
for i in ran... |
0a95d362e7e9afd2c4c95d3937dfd9c7914ea2d7 | Ispaniolochka/lab_python | /3_3_math_sin.py | 393 | 4.3125 | 4 | '''Написать программу, вычисляющую значение
функции (на вход подается вещественное число):'''
import math
def value(x):
if 0.2<= x <= 0.9:
print('результат:', math.sin(x))
else:
print('результат:',1)
element=input('Введите число:')
result=value(float(element))
|
0b9a4aa03fa604c841688a7847118df804b2c5ed | Ispaniolochka/lab_python | /homework3_2.py | 383 | 3.703125 | 4 | import random
num = random.randint(1,4)
user_num = int(input('Введите число от 1 до 4:'))
if user_num == num:
print('Победа')
elif user_num > num:
print('Не угадали. Ваше число больше!')
elif user_num < num:
print('Не угадали. Ваше число меньше!')
else:
print('Повторите еще раз!')
|
7469de4e15f499d391230cd8f11527e36f9de942 | Ispaniolochka/lab_python | /homework1.py | 345 | 4.0625 | 4 | element=input("Введите номер элемента:")
if len(element)>0:
number=int(element)
if number==3:
print(number,'Li')
elif number==17:
print(number,'Cl')
elif number==25:
print(number,'Mn')
elif number==80:
print(number,'Hg')
else:
print('Вы не ввели число!')
|
e98d98a90049e360c7f398921cd5c545f0d865f8 | Ispaniolochka/lab_python | /homework3_3.py | 207 | 3.953125 | 4 | import math
def value(x):
if 0.2<= x <= 0.9:
return math.sin(x)
else:
1
element=input('Введите число:')
result=value(float(element))
print('результат:',result)
|
6448f6f3a3c44296e2bb0166000a6cb7d91898d9 | smitamitra2016/Python-test | /TestPython/com/Conditional.py | 357 | 3.734375 | 4 | '''
Created on 26 Jan 2017
@author: Nomad Digital
'''
a,b = 4,1
if (a+b)<2:
print('Summation {} is less than 2'.format((a+b)))
else:
print('Summation {} is greater than 2'.format((a+b)))
print("abc" if (a+b)<2 else "def")
choices = dict(
one = 1,
two = 2,
three = 3
)
#print(choices['... |
5eec04b7937ecc36999127b68edf991e68db7cf7 | Remor53/lesson2 | /strings.py | 1,256 | 4.375 | 4 | def str_check(str1, str2):
"""Проверяет объекты на пренадлежность типу string.
Если оба объекта строки, то проверяет одинаковые ли они,
если разные, то определяет какая длиннее и проверяет, является
ли вторая строка словом 'learn'
Ключевые аргументы:
str1 -- первый объект
str2 -- второй объ... |
8fbc68d5d56c5f11b8f827b60febdb9674c9f1d7 | sahay1996/Project1 | /Project1.py | 749 | 3.90625 | 4 | import random
def game(comp, b):
if comp==b:
return None
elif comp =='s':
if b=='w':
return False
elif b=='g':
return True
elif comp=='w':
if b=='w':
return False
elif b=='g':
return True
print(... |
b1e76d86c4ab0af7af6b5c86308e8797abb0479b | akashsrikanth2310/expertiza-topic-bidding | /app/matching_model.py | 9,694 | 3.59375 | 4 | import math
import random
import json
class Topic:
"""
Base class for Assignment Topics
ATTRIBUTES:
----------
model : MatchingModel
The parent matching model according to whose rules the matching will be
done.
id : String
The topic ID corresponding to the topic.... |
7cda694f8abc221af457b68cfc6de3169515931d | wu4f/cyberpdx-crypto | /www/users.py | 4,542 | 3.6875 | 4 | """
+------------+------------------+
| Username | PassHash |
+============+==================+
| John Doe | 1234 |
+------------+------------------+
This can be created with the following SQL (see bottom of this file):
create table users (username text, passhash text);
"""
import sqlite3... |
0eb2e3d2ba757ffdae11e4b78ec73ac6e035ce24 | OmarAnwar19/Voice-Prescription-Maker | /SET Hackathon/First Course - 1.py | 3,087 | 4.03125 | 4 | from random import randint
game_run = True
game_record = []
def calc_monster_attack(attack_min, attack_max):
return randint(attack_min, attack_max)
def game_over(victor_name):
print(F"{victor_name} Won!")
while game_run == True:
round_counter = 0
new_round = True
player = {"... |
df1f60c45a33ca268610f2428289efc27342e12f | fbscott/BYU-I | /CS241 (Survey Obj Ort Prog Data Struct)/_starter_files/assign04/main.py | 1,562 | 3.75 | 4 | """
File: main.py
Author: Br. Burton
This file tests the customer, order, and product classes for
assignment 04. You should not need to change this file.
"""
from customer import Customer
from order import Order
from product import Product
def main():
print("### Testing Products ###")
p1 = Product("1238223", ... |
79deed779d787d6b116860d08fedbff0a9e216db | fbscott/BYU-I | /CS241 (Survey Obj Ort Prog Data Struct)/checkpoints/check08b.py | 1,915 | 3.65625 | 4 | ###############################################################################
# Assignment:
# Checkpoint 08b
# curtis mellor, cs241
###############################################################################
class GPA:
def __init__(self, gpa = 0.0):
self.__gpa = float(gpa)
def __get_gpa(self... |
ac59fae1f1f0495af9a0ecbcb56aed8723da4391 | fbscott/BYU-I | /CS241 (Survey Obj Ort Prog Data Struct)/homework/hw_09_hash_table.py | 1,119 | 3.921875 | 4 | import csv
# dictionary to hold the education level and counts
education_counts = {}
def get_education_counts(file):
"""hash function"""
with open(file) as csv_file:
rows = csv.reader(csv_file)
for row in rows:
# get the education level from the 4th column (index 3) of each row
... |
faf830c550d3166f125c4b846f95de6b1047d5c7 | fbscott/BYU-I | /CS241 (Survey Obj Ort Prog Data Struct)/checkpoints/check02b.py | 682 | 4.21875 | 4 | user_provide_file = input("Enter file: ")
num_lines = 0
num_words = 0
# method for opening file and assigning its contents to a var
# resource: https://runestone.academy/runestone/books/published/thinkcspy/Files/Iteratingoverlinesinafile.html
# file = open(user_provide_file, "r")
# best practice is to use "with" to ... |
a4c93b8eb9a24d5e896c869ce1cc6fee77666e60 | fbscott/BYU-I | /CS241 (Survey Obj Ort Prog Data Struct)/skeet/flying_object.py | 1,213 | 3.671875 | 4 | import arcade
from point import Point
from velocity import Velocity
class FlyingObject:
"""
Base (parent) class for all objects (other than the rifle) that move on the
screen.
"""
def __init__(self):
"""constructor"""
self.center = Point()
self.velocity = Velocity()
... |
87f85202f1713c2ac5e6064593f525db40be111c | fbscott/BYU-I | /CS241 (Survey Obj Ort Prog Data Struct)/asteroids/main.py | 8,203 | 3.875 | 4 | """
File: asteroids.py
Original Author: Br. Burton
Designed to be completed by others
This program implements the asteroids game.
"""
import arcade
import os
from rock_large import Rock_large
from rock_medium import Rock_medium
# from rock_small import Rock_small
from ship import Ship
from bullet import Bullet
# Thes... |
2ce6dc58476374b5ef0f10ac94eee3b47b598800 | fbscott/BYU-I | /CS241 (Survey Obj Ort Prog Data Struct)/team_assignments/ta03.py | 668 | 3.875 | 4 | class RationalNumber():
def __init__(self):
self.numerator = 0
self.denominator = 1
def display(self):
print(f"{self.numerator}/{self.denominator}")
def prompt(self):
self.numerator = input("Enter the numerator: ")
self.denominator = input("Enter the denominator: ")... |
41b67a637f805c11cc6cc1fd1dc73b2e94f22cbe | fbscott/BYU-I | /CS241 (Survey Obj Ort Prog Data Struct)/skeet/bullet.py | 723 | 3.75 | 4 | import math
from flying_object import FlyingObject
class Bullet(FlyingObject):
"""Projectile. Fires from rifle. Destroys targets. Origin: (0,0)"""
def __init__(self, radius, speed, color):
"""constructor"""
super().__init__()
# bullets start at (0,0) so there's no need to override the "... |
8ac515605efd5ab84dedb6ec93a78120d04264a2 | alexnix/ngnt_matching | /notebooks/levSubstring.py | 782 | 3.578125 | 4 | import Levenshtein as lev
import re
def isLevSubstring(substring, string, precision):
substring = substring.lower().strip()
string = string.lower().strip()
i = 0
j = len(substring)
if j > len(string):
j = len(string)
while j <= len(string):
if lev.distance(string[i:j], substring... |
05f7c6a29397b5c5f3412c99d2648db8822e2862 | xinmingzh/CS1010X | /Mission 5/Mission 5/mission05-template-XINMING-PC.py | 2,419 | 3.546875 | 4 | #
# CS1010S --- Programming Methodology
#
# Mission 5
#
# Note that written answers are commented out to allow us to run your
# code easily while grading your problem set.
# Functions List:
# connect_rigidly(curve1, curve2)
# connect_ends(curve1, curve2)
# gosperize(curve)
# gosper_curve(level)
# show_connected_gosper... |
ecea0819ddc4eed242bf0705f35edacec7d5a90c | xinmingzh/CS1010X | /Mission 2/Side Quest 2.4/sidequest02.4-template.py | 998 | 3.671875 | 4 | #
# CS1010X --- Programming Methodology
#
# Mission 2 - Side Quest 2
#
# Note that written answers are commented out to allow us to run your
# code easily while grading your problem set.
import math
##########
# Task 1 #
##########
# Simplifed Order notations:
# 4^n * n^2
# Ans: 4^n
# n * 3^n
# Ans: 3^n
# 1000000... |
185bc6d17e0c61c6cb112816d318e9aba34b7fd1 | bkytchak/AutomateTheBoring | /Section 5/GuessTheNumber.py | 486 | 4.09375 | 4 | #This is a guess the number game.
import random
print("What is your name?")
name = input()
secretNum = random.randint(1, 5)
print("I am thinking of a number 1 through 5")
#Ask the player to guess 6 times
for guessesTaken in range (1,5):
print("Take a guess")
guess = int(input())
if guess < secretNum:
... |
4b29b5de3c75cc757f11cacad097747d02790a86 | ndraper2/data-structures | /binheap.py | 1,741 | 3.84375 | 4 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
class BinHeap(object):
def __init__(self, iterable=None):
"""Create a new binary min-heap.
Insert values from an optional iterable.
"""
self.list = []
if iterable:
for item in iterable:
... |
f2dcd6ec19dfb7de95df56c80e7189f02fbf5e4c | Leeheejin1/python-test | /n10.py | 189 | 3.578125 | 4 | b=input('단어를 입력하세요')
c=0
for i in range(0,len(b)):
if b[i] == 'f':
print(i,end=" ")
c= 1
else:
if i==len(b)-1 and c==0:
print(-1) |
7c1897412e54a953bde229a65a976e05e192923e | RichInCode/projectEulerProblems | /SpecialPythagoreanTriplet.py | 1,142 | 3.75 | 4 | import math
def SpecialPythagoreanTriplet():
x = [i**2 for i in xrange(1,1001)]
#print x
for i in xrange(0,len(x)-2):
a = x[i]
#print 'a = '+str(a)
for j in xrange(i+1,len(x)-1):
b = x[j]
# print 'b = '+str(b)
aAndb = a + b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.