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
0b3668269954b8a9252a578ba81fa1d315274e7e
joshbenner851/Cracking-Coding-Interview
/reverse.py
177
4.0625
4
a = input("please enter a string") b = input("please enter a string for comparison") if(a != b[::-1]): print("not a palidrome") else: print("This is a palidrome")
22a55abc1942ab670ebf43e66c4e478338db5945
waitlearn/py
/sfalg/matrixmul.py
209
3.6875
4
def matrixMul(A,B): result = [[0] * len(B[0]) for i in range(len(A))] for i in range(len(A)): for j in range(len(B[0])): for k in range(len(A[0])): result[i][j] += A[i][k] * B[k][j] return result
5347c6a3973be52d78ea1c4df9835c686b5b2ea7
minessi91/Python
/funcaoMult.py
306
3.765625
4
valor = input("Digite um valor ") #a # lista = [a * 1 for a in range(11)] # b lista = [1,2,3,4,5,6,7,8,9,10] # b def multiplicando(a, b): counter = 1 for var1 in [x * int(a) for x in b]: print('{} * {} = {}'.format(a, counter, var1)) counter += 1 multiplicando(valor, lista)
adfb2f9b19654efb88faa1ff1e3c643eb50cbbe7
leomarkcastro/Python-School-Codes
/how many.py
1,194
4.0625
4
''' Code #5 Goal: Perform two input. The first input is a number. This number will be the max length of the second input string. Count the alphabet, number and symbols on the second input string. ''' while True: try: count = int(raw_input("Enter the number of characters o...
2eb75d354089fa5da4b722bf19ee40583028cded
ManuBedoya/AirBnB_clone
/tests/test_models/test_amenity.py
401
3.609375
4
#!/usr/bin/python3 """Module to test the amenity class """ import unittest from models.amenity import Amenity class TestAmenity(unittest.TestCase): """TestAmenity Class """ def test_create_amenity(self): """Test when create a amenity """ my_model = Amenity() dict_copy ...
c2e6c90fb2a705b94ec183a32454e2e4551652bb
Priyankazoya/without-inputhandler
/stack operations.py
2,658
3.921875
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 15:38:26 2020 @author: Priyanka Zoya """ ''' stack data structure D C B A ''' class Stack(): def __init__(self): self.items = [] def push(self,item): self.items.append(item) def pop(self): ...
e8bac117e889770c1bae6fc994a73ea401096af0
Stephan-kashkarov/Number-classifier-NN
/neuron.py
1,393
4.28125
4
import numpy as np class Neuron: """ Neuron Initializer This method initalises an instance of a neuron Each neuron has the following internal varaibles Attributes: -> Shape | This keeps track of the size of the inputs and weights -> Activ | This is the function used to cap the ra...
2d2975969b0aedc9c58033ec14ca532a4c1b287f
Nimrod-Galor/selfpy
/hangman.py
5,390
3.546875
4
import re HANGMAN_ASCII_ART = """ _ _ | | | | | |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __ | __ |/ _` | '_ \ / _` | '_ ` _ \ / _` | '_ \ | | | | (_| | | | | (_| | | | | | | (_| | | | | |_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_| __/...
b57811fc464a9454134e3320e7c240c94e51c438
Nimrod-Galor/selfpy
/642.py
764
3.609375
4
import re old_letters = ['a', 'p', 'c', 'f'] def try_update_letter_guessed(letter_guessed, old_letters_guessed): if len(letter_guessed) == 1 and re.search('[^a-zA-Z]', letter_guessed.lower()) == None and letter_guessed.lower() not in old_letters_guessed: old_letters.append(letter_guessed.lower()) ...
e50c89fefc91ef78eea0295e91064a88ca366097
Nimrod-Galor/selfpy
/931.py
928
3.5625
4
def my_mp3_playlist(file_path): """ return a tuple where first item the name of longest song second item number of songs in the file and last the name of artist with most songs :param file_path path to file containing our list :type string :return "" :rtype tuple """ fo = open(file_pat...
8937df336ce66130635a95695082040116352953
Nimrod-Galor/selfpy
/343.py
156
3.9375
4
user_input = input("Please enter a string: ") new_str = user_input[:len(user_input) // 2].lower() + user_input[len(user_input) // 2:].upper() print(new_str)
2be6c1dff2a08f4b38119d1094ab5b8b589ad699
Nimrod-Galor/selfpy
/823.py
615
4.4375
4
def mult_tuple(tuple1, tuple2): """ return all possible pair combination from two tuples :tuple1 tuple of int :type tuple :tuple2 tuple of int :type tuple :return a tuple contain all possible pair combination from two tuples :rtype tuple """ comb = [] for ia in tuple1: ...
fc0b046d8086a54ea8c3ddaacf2ed72bd920cd54
Seyekt/Lowest-Common-Ancestor.py
/lowest_common_ancestor.py
2,149
3.71875
4
class Node: def __init__(self, key): self.key = key self.right = None self.left = None class DAGNode: def __init__(self, key): self.key = key self.parents = [] self.children = [] self.distance = None def findPath( root, path, k): if root is None: return False path.append(root.key) if root....
1146f1ba1a2922eeace3e229596e2b0ed89512a3
Thadishi/PythonPrac
/learnPythonTheHardWay/states39.py
618
3.96875
4
states = { "Lucy": "Cedric", "Ennie": "Joyce", "Maria": "Putini", "Mamorake": "Danny", "Mavis": "Foster", "Isahai": "Koketso", "Oupa": "keMolebetse", "Nathaniel": None, "Junior": "Lethabo", } cities = { 1: "Johannesburg", 2: "Cape Town", 3: "Durban", 4: "Germiston", 5: "Pretoria", 6: "Port Elizabeth", ...
a3c9d7ef2d2c6978f7b424185e3a4d458cafdc1a
ntaleronald/easy-video-maker
/audio_to_slideshow-master/app/image_edit.py
4,239
3.9375
4
from PIL import Image, ImageDraw, ImageFont import os from config import WIDTH, HEIGHT def resize(image_pil, width, height): """Resize image keeping the ratio and using white background Args: image_pil (Image): Image Object, width (int), height (int), Returns: [Image]: I...
9acf49178b2b1bff1ede067a2870e855449f7aaf
nuttawich/Python-Basic
/calculate grade.py
403
4.03125
4
# calculate grade """ input: student's score (int) process: match score with condition output: show grade (str) """ try: score = int(input("enter score: ")) if score >= 80: print('A') elif score >= 70: print('B') elif score >= 60: print('C') elif score >= 50: prin...
4d1cb0cbeab96c88c30e50a189bc722c0344de8b
lethal233/CS305-SUSTech
/narcissistic_number.py
339
3.640625
4
def find_narcissistic_number(start: int, end: int) -> list: list = [] for i in range(start, end): temp = 0 string = str(i) length = len(string) temp = 0 for j in range(length): temp = temp + int(string[j])**length if temp == i: list.append(...
8f33de431e632851839be19a00853eeae37c914f
gHuwk/University
/First course/1st semester/ptotect.py
756
3.859375
4
n = int(input('Количество элементов матрицы= ')) def my(matr): if len(matr) == 0 or len(matr) == 1 : print('Неверная длина матрицы' ,end=' ') else: def mtrx(matrix,ii,jj): res = [] k = 0 p = 0 for i in range(len(matrix)): ...
ac9d3783d4173f580f8c142ee67846f8e1762854
gHuwk/University
/First course/2nd semester/Основы программной инженерии/Rk__1.py
1,099
3.71875
4
from random import random import numpy def create_matrix(): file = 'matrix.txt' f = open(file, 'w') N = 3 M = 3 mtx = [] arr = [None] * N*M for i in range(N): a = [] for j in range(M): a.append(int(random()*9)) mtx.append(a) for i in ...
28a5d7832e0e49ea4c3a87044e1ed32d62a28b96
gHuwk/University
/Second course/4th semester/Computational Algorithms/Lab3 - Multivariate interpolation/interpolation_mnogomer.py
3,361
3.859375
4
from math import * from prettytable import PrettyTable def func(x, y): return x * x + y * y def main(): mas_x = []; mas_y = [] tmp_x = []; tmp_y = []; tmp_y2 = [] tmp_x3 = []; tmp_y3 = [] matrix = [] beg = 0; end = 10 N = abs(end - beg) - 1 eps = 1e-5 for ...
2c4a5aee5a41c3fb8f1c1a36d67c46fabc9292aa
gHuwk/University
/Third course/5th semester/Analysis of algorithms course/Lab3 - Sorting/sort.py
2,136
3.765625
4
def mysort_bubble(arr): n = len(arr) for i in range(n - 1): for j in range(n - i - 1): if arr[j] > arr[j + 1]: buf = arr[j] arr[j] = arr[j + 1] arr[j + 1] = buf return arr def mysort_insert(arr): n = len(arr) ...
f2bee00df8defbce2d2f21448543d6f2b65c82ae
gHuwk/University
/First course/1st semester/protect grapic.py
1,204
3.546875
4
a,b,h = map(float,input('Введите (Нач. коорд)w (Конеч. коорд)p (Шаг)k: ').split( )) def my_range(a,b,h): while a < b: yield a a += h L = [] print("----------------------------------") print("| T | A |") print("----------------------------------") for i in my_range...
0c4ee755fdd67b5232110e0aedca82ecb781afc8
gHuwk/University
/Third course/5th semester/Analysis of algorithms course/Lab3 - Sorting/main2.py
490
3.640625
4
from sort import * from main1 import get_calc_time arr = list(map(int,input().split(' '))) arr1 = arr.copy() arr2 = arr.copy() arr3 = arr.copy() print("\nСортировка пузырьком:") print(get_calc_time(mysort_bubble, arr1)) #print(arr1) print("\nСортировка вставками:") print(get_calc_time(mysort_insert, a...
a4f39b224b24b404622234b678e6e6d8d9307849
Jon10011/Python-study-notes
/20170927_界面编程.py
2,477
3.625
4
#coding=utf-8 from Tkinter import * root = Tk() V = IntVar() V.set(2)#设置位置 Radiobutton(root,text='range',variable=V,value=1).pack(anchor=W)#W放在中间 Radiobutton(root,text='if',variable=V,value=2).pack(anchor=W) Radiobutton(root,text='while',variable=V,value=3).pack(anchor=W) var = IntVar() c =Checkbutton(root,text='this i...
d4c73683b16bb6afde8865f441d76a9569e3e499
Jon10011/Python-study-notes
/20170925_Time.py
1,179
3.59375
4
# coding=utf-8 #Time模块 "" "1.time" import time t1 = time.time() for i in range(10000000): pass t2 = time.time() print t1,t2 "2,。ctime(...)将一个时间戳(默认为当前时间)转换成一个时间字符串" print '----------------------------' print time.ctime(t1) "3.asctime()将一个struct_time(默认当前时间,转换成字符串)" print '----------------------------' print time....
0d3683efd8fc9dd8578928cda52114cc18204895
Dev-352/prg105
/chapter 10/practiec 10.1.py
1,760
4.6875
5
# Design a class that holds the following personal data: name, address, age, and phone number. # Write appropriate accessor and mutator methods (get and set). Write a program that creates three # instances of the class. One instance should hold your information and the other two should hold your friends' # or family...
05814dcb33986ba46af95b6aac6feb69d0e372ca
Dev-352/prg105
/Financial_aid.py
1,657
4.03125
4
# You are writing a program to determine if a student is eligible for financial aid for the next semester. To qualify, # the student must either be a new student, or a current student with a GPA of 2.0 or higher. Additionally, # the student may not have a criminal record for drugs, must enroll in a minimum of six cr...
570f38c28c680b599d34897d1988f74196f61225
Dev-352/prg105
/chapter 9/practice 9.2.py
1,161
4.15625
4
# Create a dictionary based on the language of your choice with the numbers from 1-10 paired with the numbers # from 1-10 in English. Create a quiz based on this dictionary. Display the number in a foreign language and # ask for the number in English. Score the test and give the user a letter grade. def main(): ...
da5322901540169f5a33d233ab94b973430be4a7
Dev-352/prg105
/sales.py
787
4.5
4
# You need to create a program that will have the user enter in the total sales amount for the day at a coffee shop. # The program should ask the user for the total amount of sales and include the day in the request. # At the end of data entry, tell the user the total sales for the week, and the average sales per day...
5c8af2f203bd7d6dcab73272765f1254b1171426
kawashima-mozart/python_app
/while.py
484
3.796875
4
import random import time a = 0 b = 0 goal = 20 user = input("aとbのどちらのカメが勝つか?") print('競争開始') while a< goal and b < goal: print('---') a = a + random.randint(1,6) b = b + random.randint(1,6) print("a:" + ">" * a + "@") print("b:" + ">" * b + "@") time.sleep(1) if a == b: winner = '同時' ...
aac34c61da8a66e9539c44318db89fa1ddf1a5fd
fatima-cyber/madlibs
/madlibs.py
939
4.46875
4
# MadLibs - String Concatenation #suppose we want to create a string that says "subscribe to ____" youtuber = "Fatima" #some string variable # a few ways to do this # print("subscribe to " + youtuber) # print("subscribe to {}".format(youtuber)) # print(f"subscribe to {youtuber}") # using this adj = input("Adje...
97425c9225cbc8477c31c79ab9ee157bd68e53d5
lzacchi/INE5416
/python/multiparadigma/1069.py
373
3.609375
4
# Done cases = int(input()) for i in range(cases): inpt = str(input()) inpt = inpt.replace(".", "") # replaces all '.' with empty spaces print(inpt) diamonds = 0 while inpt.find("<>") != -1: inpt = inpt.replace("<>", "", 1) # replaces one occurence of '<>' with an empty space pr...
0ad25c80807fbee8778ca9e8f8e993db9daedeef
Irache/TFM
/venv/src/buscar_palabras.py
501
3.578125
4
import re import string frequency = {} import locale print(locale.getpreferredencoding(False)) file = "..\\file\\result_project.html" document_text = open(file, 'r') text_string = document_text.read() text_string = document_text.read().lower() match_pattern = re.search(r'b[a-z]{3,15}b', text_string) for word in mat...
da82f58f522359f13c1e69f2dd1efce52ba57189
Jia35/-Python-Tutorial
/file/code/hw21.py
179
3.5625
4
a = input("輸入:") offset = int(input("偏移量:")) out = [] for i in a: num = ord(i)+offset if num>122: num = num-122+96 out.append(chr(num)) print(out)
01fdeadc4878f83ade9514fb19bad4e884486200
fowku/python-course-test
/1.py
425
3.984375
4
def check_number(numbers_list: list, n: int): """ Check, if there is number in list. If not, add to the end of the list. :param numbers_list:list for ex. [1, 4, 23, 12, 32] :param n:int :return:list """ if n in numbers_list: print('There is n in numbers_list already!') ...
41209063cf57370a1a7b4ec5a4623bc2d8ac1ee8
kelly-sovacool/tiger_salamander_project
/legacy_scripts/nexus2fasta.py
2,037
3.75
4
#!/usr/local/bin/python3 """ Convert files in nexus format to fasta format Author: Kelly Sovacool Email: kellysovacool@uky.edu 06 Feb. 2018 Usage: ./nexus2fasta.py input_dir_or_file output_dir_or_file """ import os import sys def main(): input_path = sys.argv[1] output_path = sys.argv[2] if os.path....
ab54aea3aabc4120f10733fb063b18b5ede3101e
lchesn2/GreedyAlgorithm
/hashmap.py
2,352
3.8125
4
# Larah Chesnic Student ID: 001106662 class HashMap: def __init__(self): self.size = 10 self.map = [None] * self.size # adds the ASCII characters in the key and uses modulo function to determine hash # Big O is O(n) def __get__hash(self, key): hash = 0 for char...
c39bd54af1b2b184392b69d7712f7f06d77ed3df
Sampatankar/Udemy-Python
/280521.py
708
4.3125
4
# Odd or Even number checker: number = int(input("Which number do you want to check? ")) if number % 2 != 0: print("This is an odd number.") else: print("This is an even number.") # Enhanced BMI Calculator height = float(input("enter your height in m: ")) weight = float(input("enter your weight in...
bdc5204477c59c372caf53946b5db59d8ac7c151
Sampatankar/Udemy-Python
/100621_lovecalc.py
1,567
4.0625
4
# 🚨 Don't change the code below 👇 print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 # Concatenate the string: both_names = name1 + name2 # Lower case the string a...
7823d72d98e4fa7063b2b469420d826feb95fda8
Sampatankar/Udemy-Python
/050721_secretauctions.py
1,025
4
4
from replit import clear # This is a repl.it module...build your own 'os' module related clear screen func if needed! # Google it! #HINT: You can call clear() to clear the output in the console. """ Put in a clear screen function when in IDE """ # Import the art logo & print it: from art import logo print(logo...
5e5fbd1ab074f1fcbd35f42e5ff913b5edda7421
smunj/InterviewBit
/Arrays/mergeIntervals.py
1,728
3.75
4
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: # @param intervals, a list of Intervals # @param new_interval, a Interval # @return a list of Interval def insert(self, intervals, new_interval): a...
ef92df9298731e5e028dff08921e408aa871a75e
mle8109/repo1
/CS_Python/Coding/Fibonacci_DS.py
536
3.953125
4
def fibonacci(n): if n == 0: return 0 if n == 1: return 1 return fibonacci(n-1) + fibonacci(n-2) ret = [] def fibonacci2(n): if n == 0: ret.append(0) return ret if n == 1: ret.append(1) return ret tmp = fibonacci2(n-1) + fibonacci2(n-2) ret.append(tmp) return ret cache = [] def fibonacci_d...
bdabf313628ae5516fc596b20785332477a3bc77
zsaegesser/CS370
/final_project/StringTransmission.py
5,128
3.71875
4
# Name: String Transmission # Course: CS 370 # Professor: Borowski # Assignment: Final Project # @file StringTransmission.py # @author: Aimal Wajihuddin # Zach Saegesser # Ryan Edelstein # # I pledges my honor that I have abided by the Stevens Honor System # - Aimal Wajihuddin # - Zach Saegesser # ...
4f5bf4e2f4ad4f968b6ffe379a5377abf02ca613
jeffreyrosenbluth/sapphire
/sapphire.py
13,756
3.953125
4
#!/usr/bin/env python import random import time from itertools import * class Card(object): """ playing card location: p = pick pile, h = sapphire's hand, g = sapphire's unknown, u = opponents uknown hand, k = opponents known hand, d = discards """ def __init__(self, rank, suit, position): ...
a83c113675fd6072468b5f3dd71a7b86dd3f1857
ebragaparah/project_euler
/3_prime_factors_of_a_number/prime_factors_of_a_number.py
673
3.90625
4
from math import sqrt def is_prime(number): root = int(sqrt(abs(number))) if number == 0 or number == 1: return False else: counter = 0 for iterator in xrange(1, root + 1): if number % iterator == 0: counter += 1 return counter <= 1 def prime_factors_of(number): root = int(sqrt(abs...
887ae562fde3c76d4bacdc27ab16e2fd6f612848
AvisSHACk/pythonejer
/mclibre/minijuegos/ejercicio2.py
246
3.78125
4
import random print("TIRADA DE DADOS") n_jugadores = int(input("Numero de jugadores: ")); dado = 0 if(n_jugadores <= 0): print("Imposible") else: for i in range(n_jugadores): print(f"Jugador {i + 1}: ", random.randint(1, 6))
a1229068344de94d01d972219dc971981a1bfb51
AvisSHACk/pythonejer
/mclibre/minijuegos/ejercicio9.py
962
3.8125
4
import random print("EL DADO MAS ALTO") n_dados = int(input("Numero de dados: ")); jugador1, jugador2 = 0, 0 if(n_dados <= 0): print("Imposible") else: bajo, alto = 7, 0 print("Jugador 1: ", end="") for i in range(n_dados): valor_dado = random.randint(1, 6) if valor_dado < bajo: ...
5fbb78d357f990de369a4656b454e5ad02f767e1
AvisSHACk/pythonejer
/practicas/adivinaElNumero.py
883
3.96875
4
import random print("¿Podras adivinar el numero?, El programa te dara una ayudita sin embargo solo tendras 6 intentos") usuario = int(input("Ingresa un numero al azar entre 1 al 20: ")) ''' Al pedir el numero por primera vez ya se gasto un intento, por lo tanto la variable debe empezar en 5 pues el usuario solo tiene ...
6af631be6b68598c208aaac7fc014bc67b1261c3
AvisSHACk/pythonejer
/mclibre/minijuegos/ejercicio5.py
405
3.921875
4
import random print("EL DADO MAS ALTO") n_dados = int(input("Numero de dados: ")); dado = 0 if(n_dados <= 0): print("Imposible") else: print("Dados: ", end="") masAlto = 0 for i in range(n_dados): valor_dado = random.randint(1, 6) print(valor_dado, end=" ") if masAlto < valor...
a2b9b24447e9ce0889d050a00ffffd25b6189ec8
AvisSHACk/pythonejer
/mclibre/minijuegos/ejercicio8.py
464
3.765625
4
import random print("EL DADO MAS BAJO") n_jugadores = int(input("Numero de jugadores: ")); ganador = 0 dado_ganador = 7 if(n_jugadores <= 0): print("Imposible") else: for i in range(n_jugadores): valor_dado = random.randint(1, 6) if(valor_dado < dado_ganador): ganador = i + 1 ...
fdd2f29653309b7cc7fb7fb6f7c04050bfadc5ad
shellshock1953/python
/oop/3.py
194
3.71875
4
class Person(): def __init__(self,name,age): self.name = name self.age = age def info(self): print(self.name, self.age) person1 = Person('Bob',11) person1.info()
d5df4247029297677c33b8f8172b4e62d7369093
BillMaZengou/raytracing-in-python
/01_point_in_3d_space/mathTools.py
769
4.1875
4
def sqrt(x): """ Sqrt from the Babylonian method for finding square roots. 1. Guess any positive number x0. [Here I used S/2] 2. Apply the formula x1 = (x0 + S / x0) / 2. The number x1 is a better approximation to sqrt(S). 3. Apply the formula until the process converges. [Here I used 1x10^(-8)] ...
83311fe516c076db1b167650fb325315c08b87db
hm1365166/opencsw
/csw/mgar/gar/v2/lib/python/colors.py
628
3.78125
4
"""Color processing.""" def MakeColorTuple(hc): R, G, B = hc[1:3], hc[3:5], hc[5:7] R, G, B = int(R, 16), int(G, 16), int(B, 16) return R, G, B def IntermediateColor(startcol, targetcol, frac): """Return an intermediate color. Fraction can be any rational number, but only the 0-1 range produces gradien...
3052b2bcc23f527313f82fd3786d1dbf64039199
rokorio/mycrypto
/fieldelement.py
1,861
3.765625
4
'''In this class we are trying to have finite elment i.e an order number which is greater than zero and less than largest . The largest nummber in sequence of 19 should be 18 i.e F19 ={1,2,3,..18} ''' class FieldElement(): def __init__(self,num,prime): if num >= prime or num <0: error='num {} i...
5d8316b712711e888d290c125f3355fb3cc3a374
thimontenegro/Dataquest
/Machine Learning/Linear Regression/The Linear Regression Model-235.py
1,883
3.625
4
## 2. Introduction To The Data ## import pandas as pd data = pd.read_csv('AmesHousing.txt', delimiter = '\t') train = data.iloc[0:1460] test = data.iloc[1460:] target = 'SalePrice' ## 3. Simple Linear Regression ## import matplotlib.pyplot as plt # For prettier plots. import seaborn fig = plt.figure(figsize = ...
331908242ab5e802e7a46118bb9f754358307fce
thimontenegro/Dataquest
/Statistics/Intermediate/The Mean-305.py
2,956
3.90625
4
## 2. The Mean ## def mean_mode(l): total = 0 for i in range(len(l)): total += l[i] result = total / len(l) return result distribution = [0,2,3,3,3,4,13] mean = int(mean_mode(distribution)) center = False dist_list_below_mean = [] dist_list_above_mean = [] for i in range(len(distribution)): ...
4c36924a2d26144c29892ebac5c1d2b7a6885728
Ben-Baert/Exercism
/python/nth-prime/nth_prime.py
567
3.78125
4
from itertools import count from math import sqrt def prime_candidates(): yield 2 yield 3 for n in count(6, 6): yield n - 1 yield n + 1 def nth_prime(n): primes = [] candidates = prime_candidates() while len(primes) < n: candidate = next(candidates) for prime i...
864bb0c32e55606564eaa3324fe8db2af7177be3
Ben-Baert/Exercism
/python/sieve/sieve.py
351
3.96875
4
def sieve(x): numbers_to_consider = range(2, x + 1) composite = [] prime = [] for number in numbers_to_consider: if number not in composite: prime.append(number) current = number while current <= x: current += number composite.a...
c057b1a968bb6206e86bcf13c5b004ced2d1be71
Ben-Baert/Exercism
/python/largest-series-product/largest_series_product.py
598
3.828125
4
#from numpy import product def slices(string_of_digits, slice_length): if slice_length > len(string_of_digits): raise ValueError("Your slices are larger than the length of your string.") return [[int(x) for x in string_of_digits[i:slice_length + i]] for i in range(len(string_of_digits) - sl...
33eec58a3cf604f01975b53926cd1931beb9b928
MohammadAbufard/SocialNetworksProgram
/timer.py
4,521
4
4
def is_network_connected(person_to_friends: Dict[str, List[str]]) -> bool: ''' Return whether the social network based on the given person_to_friends dictionary is connected. A network is connected if and only if every key in the dictionary is linked, through a sequence of friends, to every ...
53cab2990d1922e4a3f7cca0b60cf5b093ae16c4
FabianSieper/polygonSimplification
/src/main/gpxParser.py
1,991
3.640625
4
import gpxpy import gpxpy.gpx class Point: def __init__(self, longitude, latitude, index = -1): """ Initialization of points :param longitude: the value of the longitude of a point :param latitude: the value of the latitude of a point :param index: an index wh...
b3e8e82bff5edf3c14fafb9eb9d357a46a52ebd4
FabianSieper/polygonSimplification
/src/test/test_helper.py
2,353
3.578125
4
from unittest import TestCase import sys sys.path.append("../main") from gpxParser import Point from helper import computeDistance, buildDirectedGraph from gpxParser import parse import random class Test(TestCase): def test_compute_distance(self): startPoint = Point(0, 1) endPoin...
3309ec514d0ae1ad9f84aab3f7f455836b91f5aa
ivaben/Intro-Python-I
/src/13_file_io.py
998
4.28125
4
""" Python makes performing file I/O simple. Take a look at how to read and write to files here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files """ # Open up the "foo.txt" file (which already exists) for reading # Print all the contents of the file, then close the file # Note: pay close...
89b4023654d1880a0e2c19a2ded84b5be517897a
ochronus/advent-of-code-2019
/day06/python/day06.py
1,345
3.71875
4
def part1(pairs): total = 0 # strategy: trace each node back to the common ancestor in the graph. # each step is a direct orbit, we just need to add them up. # each indirect orbit is a series of direct orbits, so we just need to add them up for space_object in pairs: while space_object != "C...
c8b118e43be7dfe1877c789f295c5e50103690eb
Anubhav410/cab-details-crawler-python
/searchEmployeeDetails.py
1,173
3.6875
4
import pickle import sys import re ### #This file, reads the data of all the employees , that booked the cab from the pickle object that was created by the crawler.py #It takes the name of the employee that we want to search for as an argument and displays the answer appropriately ### name_list = [] place_list = [] c...
7b0fa8c328fdc670a032557e188b34e47683d5b4
darshil01/ModernPython3Bootcamp
/rps.py
1,319
3.953125
4
import random play_dict = { "paper": "", "rock": "", "scissors": "", } print("...rock...") print("...paper...") print("...scissors...") p1_input = input("Player 1 enter your choice - ") c_list = ["rock", "paper", "scissors"] c_pick = random.choice(c_list) print("Computer picks {}".format(c_pick)) def ...
d674ae486827f095f48c7fba04aa738e0eb0a9ca
neversay4ever/synbio
/synbio/picklists/opentrons.py
1,048
3.765625
4
"""Script generation for the opentrons platform.""" from enum import Enum from ..instructions import Instruction class Robot(Enum): """Opentrons has an OT-2 and an older OT-One. https://opentrons.com/ """ OT1 = "OT-One" OT2 = "OT-2" def to_opentrons( instruction: Instruction, existin...
4517dbb81560a98d3122733a924136bc1f639705
iamchanu/leetcode
/solutions/group-anagrams.py
1,073
3.796875
4
from typing import List import unittest class Solution: def make_anagram_key(self, s: str) -> str: char_dict = {} for ch in s: if ch not in char_dict: char_dict[ch] = 0 char_dict[ch] += 1 return ",".join([f"{ch}:{cnt}" for ch, cnt in sorted(l...
b60801db814b9c80732e466832df29d2d8408204
iamchanu/leetcode
/solutions/trapping-rain-water.py
984
3.75
4
from typing import List import unittest class Solution: def trap(self, height: List[int]) -> int: n = len(height) left_walls = [0] * n water_levels = [0] * n maximum = 0 for i in range(n): maximum = max(maximum, height[i]) left_walls[i] = maximum ...
db9cc01a57ceab28f2e1a78cba282bc7bda7f08f
iamchanu/leetcode
/solutions/maximum-subarray.py
1,095
3.609375
4
from typing import List import unittest class Solution: def maxSubArray(self, nums: List[int]) -> int: sum_until_now = 0 max_subarray = None min_containing_first = 0 for num in nums: sum_until_now += num max_containing_now = sum_until_now - min_containing_fi...
5c87f25294c78d4746efa3161a0c58013e43fcb5
jaehobang/Eva
/logger.py
1,474
3.65625
4
""" This file implements the logging manager that is used to create / print logs throughout all the program """ import logging from enum import Enum class LoggingLevel(Enum): DEBUG = 10 INFO = 20 WARNING = 30 ERROR = 40 class Logger: _instance = None _LOG = None def __new__(cls): ...
e56de2745026c12ead00ae427c444b7ac1ebfe03
Bamgm14/Harvard-cs50x-2020-Intro
/Week-7/proj_houses/roster.py
765
3.625
4
# TODO import sqlite3 as sql import sys if len(sys.argv) != 2: print("Usage: python roster.py [house]") # Make sure for correct syntax exit(1) conn = sql.connect("students.db") # COnnects to SQL Server cur = conn.cursor() # Gets Cursor cur.execute("select first, middle, last, birth from students where house...
2057889db209ef93a237f61eb8d6f1b7a1bcf5ee
alvaromartinezsanchez/2020-hackathon-zero-python-retos-pool-3
/src/kata2/rpg.py
273
3.765625
4
#!/usr/bin/python import random import string def RandomPasswordGenerator(passLen): list_values=string.printable passwrd="" for i in range(passLen): passwrd+=random.choice(string.printable) return passwrd print(RandomPasswordGenerator(10))
74472c694eb8300b3cf19d6cd6ec97626d8fe324
siekiery/MITx-6.00.1x
/Week2/Problem3.py
3,824
3.765625
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 20 21:05:58 2018 @author: Jakub Pitera """ ''' Problem 3 You'll notice that in Problem 2, your monthly payment had to be a multiple of $10. Why did we make it that way? You can try running your code locally so that the payment can be any dollar and cent amount...
6961bd99ddb083325aafc522d563b65b632fc085
paolomartini25/ITIS_Sistemi_e_Reti
/Esercizi/pile-parentesi.py
1,181
4.09375
4
def push_(pila, elemento): pila.append(elemento) def pop_(pila): return pila.pop() def main(): parentesi = input("inserisci una stringa: ") pila = [] giusto = False for elemento in parentesi: if(elemento == "(" or elemento == "[" or elemento == "{"): p...
c86d40baae573f9f10497da16276261d896c85ec
paolomartini25/ITIS_Sistemi_e_Reti
/compiti delle vacanze/es4.py
1,652
3.796875
4
#Il ROT-15 è un semplice cifrario monoalfabetico, in cui ogni lettera del messaggio da cifrare viene sostituita con quella posta 15 posizioni più avanti nell'alfabeto. #Scrivi una semplice funzione in grado di criptare una stringa passata, o decriptarla se la stringa è già stata precedentemente codificata. alfabeto...
9ad82eaeffe98fe2b483e4527f677d94059e4ce7
paolomartini25/ITIS_Sistemi_e_Reti
/Esercizi/HelloWorld.py
191
3.84375
4
numero = 7 #Esempio di f-string print("hello world") print(f"il valore del numero è {numero}") #esempio di concatenazione di stringhe print("il valore del numero è " + str(numrto))
66a2bbf02db158cade18f49d719e96e425e20d53
ybamnolk/python-learn
/factorial.py
240
4.03125
4
def factorial(n): print("Entering factorial with n", n) if (n == 1): return(1) return(n * factorial(n-1)) n_str = input("please enter a postive number: ") n = int(n_str) print("Factorial of", n, "is", factorial(n))
5cd8bf7993bd2c5c4e297489e12ff22170f21297
WillLuong97/Back-Tracking
/countSortedVowelString.py
2,449
4.125
4
#Leetcode 1641. Count Sorted Vowel Strings ''' Problem statement: Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alp...
5af2bc25ed5f56ba1c822569d34d788ad308eb0c
WillLuong97/Back-Tracking
/numberWithSameConsecutiveDifferences.py
2,723
3.921875
4
#Problem 967. Numbers With Same Consecutive Differences ''' Return all non-negative integers of length n such that the absolute difference between every two consecutive digits is k. Note that every number in the answer must not have leading zeros. For example, 01 has one leading zero and is invalid. You may return th...
a971e160a9289b5235b45df9919b607b3ab011fe
AbhishekTiwari0812/A.I.
/l1/code/BestFirstSearch/controller1.py
4,708
3.890625
4
import Queue import math import copy #dimensions of the board dimension_x=0; dimension_y=0; #position of the diamond diamond_x=0; diamond_y=0; class node: def __init__(self,value,x,y): self.value=value self.x=x self.parent=None #initializing with Null value self.y=y; #adds all the immediate neighbours to...
bdeabc959cf39e6c03181c280b5a3c684177490c
WAMaker/leetcode
/Algorithms/125-Valid-Palindrome.py
429
3.53125
4
class Solution: def isPalindrome(self, s: str) -> bool: l, r = 0, len(s) - 1 s = s.lower() while l < r: while l < r and not (s[l].isalpha() or s[l].isdigit()): l += 1 while l < r and not (s[r].isalpha() or s[r].isdigit()): r -= 1 ...
366e8b5d215aaa2403178a2ceec4fbe9e6be126a
dag2104/DEEP_LEARNING_FOR_COMPUTER_VISION
/Navdeep/day1.py
1,050
3.578125
4
from PIL import Image import numpy as np class Pic: # Used to initialise the basic array and dimensions def __init__(self,img_w= 400, img_h=400): self.img_w = img_w self.img_h = img_h self.pic_array = np.zeros((img_h, img_w, 3), dtype=np.uint8) # Displays the image de...
911c4f8d06289dcbc836627b624afeba3ee01d59
nasimulhasan/3D-Tank-Implementation-with-Pygame
/frange.py
831
4.28125
4
def frange(x, y, jump=1.0): ''' Range for floats. Parameters: x: range starting value, will be included. y: range ending value, will be excluded jump: the step value. Only positive steps are supported. Return: a generator that yields floats Usage: >>> list(...
3263013409be5ef8164bf092724a9548fa3022e7
harmankumar/Snippets
/EULER/prob73/prob51.py
418
3.609375
4
import math prlist=[] def findprime(a,b): x=[0 for i in range(0,b+1)] x[0]=x[1]=1 i=2 while(i<math.sqrt(b)): count=2*i while(count<=b): x[count]=1 count=count+i i=i+1 while(x[i]!=0): i=i+1 # for i in range(0,b+1): # if(x[i]==0): # print i t=[] for i in range(a,b+1): if(x[i...
5a0f3695c15ef77934cff8bab97aab346c12f0cd
harmankumar/Snippets
/EULER/prob73/prob46.py
787
3.59375
4
import math sqlist=[] prlist=[] def findprime(a,b): x=[0 for i in range(0,b+1)] x[0]=x[1]=1 i=2 while(i<math.sqrt(b)): count=2*i while(count<=b): x[count]=1 count=count+i i=i+1 while(x[i]!=0): i=i+1 # for i in range(0,b+1): # if(x[i]==0): # print i t=[] for i in range(a,b+1):...
162a5bd826d68b8d15fa4bfb44469804ffad206c
cormacdoyle/ICS4U1c-2018-19
/Working/practice_rectangle.py
326
3.9375
4
class Rectangle(object): def __init__(self): self.width = 0 self.height = 0 def get_area(rec): return(rec.width *rec.height) def main(): rect1 = Rectangle() rect1.height = int(input("What is the height?")) rect1.width = int(input("What is the width?")) print(get_area(rect1)) ma...
177b53891c174ac2496638bbf3ecf97c398f23e9
illiaChaban/Algorithms
/algorithms3.py
5,072
4.3125
4
# Lunar Cycles # The moon goes through phases because it orbits # the earth and the sun hits it differently at # different places in its orbit. This means that, # depending on where it is in its orbit, you might # see a full moon, right quarter moon, or even "no" # moon (new moon) at all. It takes 27.3 days for th...
c9a573cf3ebda4d2dae039e58b9e3bcf95eb2957
microMomal/python
/Assignment 2/assignment 2.py
1,882
3.921875
4
# -*- coding: utf-8 -*- """ #Testasdfsdfds Created on Sat Nov 3 14:42:49 2018 @author: USER """ #Part 1 print("Part 1") def isPrime(n): # Corner case if (n <= 1): return False # Check from 2 to n-1 for i in range(2, n): if (n % i == 0): return False return True ...
6f8265a30cf93547df25d1cad41f178d3cc66257
nguyenhuuthinhvnpl/met-cs-521-python
/hw_3/jdfuller_hw_3_4_3.py
1,296
3.9375
4
""" JD Fuller Class: CS 521 - Fall 1 Date: 27SEPT2020 Homework Problem # 3 Description of Problem: Create program that interprets input string uppercase, lowercase, digits and punctuation - returns data """ import string # User prompt for input usr_input = input("Enter Phrase: ") # Function parses out uppercase, lo...
a0af3b492a446f65054ddb97f465bcb71a094cb2
nguyenhuuthinhvnpl/met-cs-521-python
/hw_3/jdfuller_hw_3_4_4.py
1,337
3.921875
4
""" JD Fuller Class: CS 521 - Fall 1 Date: 27SEPT2020 Homework Problem # 4 Description of Problem: Gather user input and ensure input is digits in ascending order without duplicates """ # While loop prompts input until valid 3-digit input meets validation criteria while True: usr_input = input("Please enter a 3-di...
990226dae732759d0323c72cd4b5f787d065ec8e
nguyenhuuthinhvnpl/met-cs-521-python
/hw_4/jdfuller_hw_4_7_1.py
707
3.796875
4
""" JD Fuller Class: CS 521 - Fall 1 Date: 04OCT2020 Homework Problem # 1 Description of Problem: Determine and print Odd & Even integers from list using list comprehension """ # Constant list of integers L = range(1, 11) # List comprehension determines evaluation_num == full list of integers in list evaluation_num ...
8fed5f5ab9f52328158a8274bba199ed03a36ef1
nguyenhuuthinhvnpl/met-cs-521-python
/hw_2/jdfuller_hw_2_1_1.py
1,138
3.796875
4
""" JD Fuller Class: CS 521 - Fall 1 Date: 20 SEPT 2020 Homework Problem # 1 Description of Problem : User input and number verification from formula """ # get user input # user input add 2, multiply by 3, subtract 6, divide by 3 # If input equals result, print "Success", else, does not match. # Function performs the...
ef113f468766d0b48cb18482b59871dbbba7f210
nguyenhuuthinhvnpl/met-cs-521-python
/instructor_code_hw_5/hw_5_5_1.py
670
4.125
4
def vc_cntr(sentence): """ Return count of vowels and consonants from input sentence :param sentence: :return: """ vowels = "AEIOU" sentence = sentence.upper() v_total = len([v for v in sentence if v in vowels]) c_total = len([c for c in sentence if c.isalpha() and c not in vowels...
622485e3c6548bb23f04e30e67861db9d90e7fd1
nguyenhuuthinhvnpl/met-cs-521-python
/hw_3/jdfuller_hw_3_2_1.py
2,221
4.03125
4
""" JD Fuller Class: CS 521 - Fall 1 Date: 27SEPT2020 Homework Problem # 1 Description of Problem: Count number of odd, even, squares, cubes of an integer range """ # Range of Numbers N_MIN = 2 N_MAX = 130 num_list = list(range(N_MIN, N_MAX + 1)) # Function takes in list of integers, calculates odd and even integers,...
d93fb13d91dd44009c3fceb5301b096ba64f0a98
kim-seoyoon/study-python
/convert_dollars_canvas_simplegui.py
1,166
3.984375
4
# interactive application to convert a float in dollars and cents import simplegui #define global value value = 3.12 #define funciions def convert_units(val,name): result=str(val)+" "+name if val >1: result=result+"s" return result def convert(val): # split into xx dollars and yy cents ...
02af8c762f5a9b7c7eea9d52066f6ae51f439f25
josedaniel973/programas_python
/HackerRank/Introduction/if-else.py
248
4.09375
4
n = int(input("Write a positive integer from 1 to 100: ")) if 1 <= n <= 100: if n%2 != 0 or 6 <= n <= 20: print("Weird") else: if 2 <= n <= 5 or n> 20: print("Not Weird") else: print("Invalid number")
8f4624abea7c03e36dfa2c0d28190bc3d11e3ad8
josedaniel973/programas_python
/4. Calculadora/tridimensional_mod.py
998
3.9375
4
def dro(geom): if geom.upper() == "C": lado = float(input("¿Cuánto mide un arista del cubo?")) return lado**3 elif geom.upper() == "N": x,y,z = input("Ingresa las medidas del largo y el ancho y la profundidad: ").split(",") x,y,z = float(x),float(y),float(z) return...
31878bc03d65a478d1a3c930b52fc074baa5653c
filza-a/arithmetic-formatter_freecodecamp-project1
/arithmetic_arranger.py
2,385
4.03125
4
def arithmetic_arranger(problems_list, *solve): if len(problems_list) > 5: return "Error: Too many problems." line1 = "" line2 = "" line3 = "" line4 = "" spaces = " " for i, problem in enumerate(problems_list): # for each argument like '1 - 2' split_problem = p...
c25d7a6a5599f463aed972c6db34a5f7a1c2143b
G1nger19/Courses
/MIPTpython/2.Turtle_Practise/task_4.py
369
3.546875
4
"""draw squares""" from turtle import * def task_4(): x=10 for _ in range(10): pendown() for _ in range(4): forward(x) left(90) penup() right(90) forward(10) right(90) forward(10) right(180) x+=20 done() ...