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
c57ba182e27ada5004d4444fe3ed4d9a9d0d8f06
Mila2305/Bioinformatics-pmfst
/BA1A.py
521
3.546875
4
""" A solution to a ROSALIND bioinformatics problem. Problem Title: Compute the Number of Times a Pattern Appears in a Text Rosalind ID: BA1A URL: http://rosalind.info/problems/ba1a/ """ def kmer(text,i,k): return text[i:(i+k)] def PatternCount(text,pattern): count=0 for i in range(0,len(text)-len(pattern...
b971fd399c5a0f2910e55e7cff15d5359eec7e9c
ThePurpleOne/EulerProject-PYTHON
/Ex10.py
743
3.734375
4
""" https://projecteuler.net/problem=10 The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ import time from math import floor, sqrt def isPrimeNumber(number): if number == 1: # 1 is not prime return False if number == 2: # 2 is a prime number ...
0b6cc860f7be2f3a913863fbae62c577b9d4086d
zingpython/december
/day_eight/MVC_Lecture/view.py
479
3.65625
4
class View: def printOut(self, output): print(output) def printList(self, output_list): for item in output_list: print( " | ".join( map( str, item ) ) ) def takeInput(self, prompt): return input(prompt) def menu(self): print("1. Read from file") print("2. Enter a user manually") print("3. Selec...
a4b1cefec3dd20db93008add41d9b575f161c4d6
zingpython/december
/day_one/Exercise10.py
141
3.671875
4
size = 10 for x in range( 1 , size+1 ): output = "" for y in range( 1 , size+1 ): output = output + " " + str( x*y ) print(output)
783e147de1f4571f4e1eec43c372d2fbbdda8771
zingpython/december
/day_eight/Exercise2/view.py
412
3.71875
4
class View: def printOut(self, output): print(output) def printList(self, shopping_list): for item in shopping_list: print(str(item[0])," | ",item[1]," | ",item[2]) def takeInput(self, prompt): return input(prompt) def menu(self): print("1. Add an item") print("2. Show list") print("3. Check i...
6f1d5c730e20841150ac7b491b56cb52d28b221e
zingpython/december
/day_four/Exercise2.py
1,322
4.28125
4
def intToBinary(number): #Create empty string to hold the binary number binary = "" #To find a binary number divide by 2 untill the number is 0 while number > 0: #Find the remainder to find the binary digit remainder = number % 2 #Add the binary digit to the left of the current binary number binary = str(...
d3aeee87168f127798a10defdc0b62d803ed7451
zingpython/december
/day_seven/Exercise2.py
1,062
3.921875
4
import csv import sqlite3 connection = sqlite3.connect("contacts.db") cursor = connection.cursor() # cursor.execute(""" CREATE TABLE user( # id INTEGER PRIMARY KEY, # name VARCHAR(50), # country VARCHAR(50), # email VARCHAR(100) ) """) # connection.commit() # cursor.execute(""" CREATE TABL...
9259cfbbd39d1ff9273e05655a03c183e8c150d7
alicefriend/aind-term-one
/AIND-Sudoku/solution.py
6,508
3.78125
4
def cross(A, B): """Cross product of elements in A and elements in B.""" return [r + c for r in A for c in B] rows = "ABCDEFGHI" cols = "123456789" boxes = cross(rows, cols) row_units = [cross(row, cols) for row in rows] col_units = [cross(rows, col) for col in cols] square_units = [cross(rs, cs) for rs in [...
733baf54c5b4c8eb6383cb8fb5021a6469bece02
bnconti/Exercises-Primer-Python
/ch4/20_convert_temp.py
2,414
3.90625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Exercise 4.20: Make a complete module # Author: Bruno N. Conti import sys def C2F(C): return C*9/5 + 32 def F2C(F): return (F - 32)*5/9 def C2K(C): return C + 273.15 def K2C(K): return K - 273.15 def F2K(F): return (F + 459.67)*5/9 def K2...
30afe1d9da5fe1f8932017224913afcd57597272
bnconti/Exercises-Primer-Python
/ch1/07_find_errors_sin1.py
256
3.671875
4
# Exercise 1.7: Find error(s) in a program """ SAMPLE RUN: sin(0.0174533)=0.0174524 """ # MY FRIEND, TO FIX THE PROGRAM YOU NEED TO CONVERT x TO RADIANS BY DOING (THETA*PI)/180! from math import sin, pi x = (1*pi)/180 print('sin(%g)=%g' % (x, sin(x)))
2d75661d888d57c0afee9eb481d1cff7a6fa4ee5
bnconti/Exercises-Primer-Python
/ch3/12_midpointint.py
2,288
3.84375
4
# Exercise 3.12: Derive the general Midpoint integration rule """ SAMPLE RUN: One rectangle. Area of cos(x) from 0.000 to 3.142. Approximation: 0.00000. Margin of error: -0.00000 Area of sin(x) from 0.000 to 3.142. Approximation: 3.14159. Margin of error: -1.14159 Area of sin(x) from 0.000 to 1.571. Approximation: 1.1...
b66233dbd730fdd8d9739ecfbe7fd07a046de0b3
bnconti/Exercises-Primer-Python
/ch4/03_f2c_file_read.py
649
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Exercise 4.3: Read a number from a file # Author: Bruno N. Conti """ SAMPLE RUN: Convert from Fahrenheit to Celsius. 67.2 °F => 19.6 °C """ def extract_data(data): infile = open(data, 'r') values = [] for line in infile: words = line.split() ...
7fa0febfb617f172a5f7ee90ec1166fea218751a
bnconti/Exercises-Primer-Python
/ch4/12_ball_cml_tcheck.py
414
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Exercise 4.12: Test validity of input data # Author: Bruno N. Conti """ SAMPLE RUN: python 12_ball_cml_tcheck.py -1 100 Wrong input! 't' must be between 0 and 2*v0/g """ import sys v0 = float(sys.argv[2]) g = 9.81 t = float(sys.argv[1]) if not(0 <= t <= 2*v0/g): p...
a5aee0e98ee87228041d49ebce200407a675fb43
bnconti/Exercises-Primer-Python
/ch3/35_simulate_nested_loops.py
790
3.859375
4
# Exercise 3.35: Simulate nested loops by hand # Author: Bruno N. Conti # Date: 7/26/17 n = 3 # This for will print: -1, 1, 2 for i in range(-1, n): if i != 0: print(i) print("{}".format("-"*40)) # This for will print: (1, 0), (1, 1), (1, 2), (7, 0), (7, 1), (7, 1) for i in range(1, 13, 2*n): for j i...
7b5095691e047f270b25a4c4d8b56362225df1f3
bnconti/Exercises-Primer-Python
/ch1/04_length_conversion.py
548
3.609375
4
# Exercise 1.4: Convert from meters to British length units """ SAMPLE RUN: ORIGINAL LENGHT: 640.00 METERS. 25196.85 INCHES. 2099.74 FEET. 699.91 YARDS. 0.40 MILES. """ lenght_meters = 640 lenght_inches = lenght_meters*100/2.54 lenght_feet = lenght_inches/12.0 lenght_yard = lenght_feet/3.0 lenght_m...
0c7a21fdd306a5aa60a6b7da678dd4bc3c0fdad0
bnconti/Exercises-Primer-Python
/ch2/24_punctuation.py
300
4
4
# Exercise 2.24: Explore punctuation in Python programs """ x = 1 # OK - INTEGER 1. x = 1. # OK - NUMBER SAVED AS FLOAT. x = 1; # OK - USED FOR MULTIPLE DECLARATIONS ON A SINGLE LINE. x = 1! # ERROR. x = 1? # ERROR. x = 1: # I DON'T KNOW WHAT THIS IS, BUT IT WORKS. x = 1, # OK - TUPLE. """
8968cdec1254f91992d7b16a79617b0b8df810e5
vanis-19/Class_Methods
/class_mrthod.py
192
3.5625
4
class Student: name = 'Student' def __init__(self, a, b): self.a = a self.b = b @classmethod def info(cls): return cls.name print(Student.info())
39448417a875e1d522baf66eeb3dba27a1448b0f
subhsamal/Web-Scrapping-Python-Selenium-Facebook-
/selenium_unittest.py
1,632
3.609375
4
# https://gist.github.com/baijum/1047207/c670c7d1fe4a5a60d361d66869b20cc2ab1a4bf4 # https://www.youtube.com/watch?v=oM-yAjUGO-E # Read about unittest module https://seleniumwithjavapython.wordpress.com/selenium-with-python/basics-of-webdriver/pythons-unit-test-framework/ # https://www.obeythetestinggoat.com/book/chapt...
fec712d28d38474fd3e42447fea75822ced87fd9
kohkubo/python02
/ex01/beverage.py
773
3.703125
4
import product as pd class Beverage(pd.Product): def __init__(self, name, price, description, temperature): """ assign its values to name, price, description, temperature attribute, using super(), """ super().__init__(name, price, description) self.temperature = temperature...
034e39176e0da2035316aee43d0a40bdf7e3f093
Skull1991/Calculator
/MyCalculator/calculator.py
4,259
3.6875
4
from tkinter import * root = Tk() root.title('Calculator') root.geometry('355x475') root.config(bg="#333333") root.resizable(False, False) root.iconbitmap("calculator.ico") expression = '' # Creating Function def click(num): global expression expression = expression + str(num) equation.set(expression)...
0bd72c05e8ca1d3d470014ffed4336a77bdd5b57
Carmelly212/anagrams
/anagrams.py
491
3.734375
4
list_of_words = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts'] anagrams = [] temp_anagrams = [] singles = [] for word in list_of_words: temp_anagrams.clear() temp_anagrams.append(sorted(word)) for word_2 in l...
40d88667edf9a8773e35754fd2b6e1586f932b2d
sg10win/version-2-
/tryScrollBar.py
4,072
3.796875
4
import tkinter as tk class VerticalScrolledFrame(tk.Frame): """A pure Tkinter scrollable frame that actually works! * Use the 'interior' attribute to place widgets inside the scrollable frame * Construct and pack/place/grid normally * This frame only allows vertical scrolling """ ...
8cb15496c6ef28903d1ea910ab0abb964522d3d9
missbanks/pythoncodes
/21062018.py
359
4.125
4
# TASK # print(51 % 48) name = input ("Hi what is your name") add_time = 51 current_time = int(input("What is your current time")) alarm_time = 5 extra_time = 3 if current_time == "2pm": print("your alarm will go off at 5pm you have {} extra hours to go".format(extra_time)) else: print("sorry you entered the wron...
6b15b36251bf06d87aa010915f18eeaab9c5b2d9
vasiliy-yashkov/python_tasks
/stepik_3_2/Main.py
561
3.8125
4
from array import * import copy def update_dictionary(d, key, value): if key in d: v = list(d[key]) v.append(value) d[key] = v elif 2 * key in d: v = list(d[2 * key]) v.append(value) d[2 * key] = v else: d[2 * key] = [value] def main(): d = {} ...
fde4e94e554fdd79b567d87ed2405a5974d884ef
Sahil1709/smart-calculator
/smart-calc.py
1,743
3.828125
4
from tkinter import * from functools import partial def add(a,b): return a+b def sub(a,b): return a-b def mul(a,b): return a*b def div(a,b): return a/b def mod(a,b): return a%b def result(text,res): commands = { 'add':add,'+':add,'addition':add,'plus':add,'sum':add, 'minus'...
8ed6a1076f6dfe71e2690f759f5b49572694af37
EventHorizon1003/Using-python-to-organize-files-Note-
/note_of_organizing_files.py
3,962
4.03125
4
# Note of Organizing files #---------------------------------------------------------------- import shutil,os # Introduce shutil module - shell utilities # -let you copy, move, rename, delete files # Copying files and folders -> shutil.copy(<source>,<destination>) # *** the path must be in strings # copy a...
c59248a67b97b564efb5d628f47449184aec1a52
ShengBian/CS325
/HW1/mergesort.py
2,141
3.96875
4
# Author: Sheng Bian # Date: April 8, 2017 # Description: This program implement merge sort algorithms by # python. It read integers from data.txt and write the result # into merge.out file. # The following code get reference from https://www.geeksforgeeks.org/merge-sort/ # and textbook P31 and P34 def merge(a...
c3442993ec049f261b6bcfb56f3f3cf9f0c617db
prajwal-code/python-lab
/classstud 2.py
1,289
3.65625
4
class Student: def __init__(self,StudentID,age,marks): self.StudentID = StudentID self.age = age self.marks = marks def validate_marks(self): if self.marks>0 and self.marks<101: return True else: return False def validate_age(self): ...
c02f16bb0dfa58c5f384de87e4474b6352e90ec0
HUIYINGLEE/HackerRank
/Cracking the Coding Interview Challenges/Tries: Contacts.py
654
3.75
4
def add(name, contacts): firstLetter=name[0] if firstLetter in contacts: contacts[firstLetter].append(name) else: contacts[firstLetter]=[name] def find(name,contacts): firstLetter=name[0] num=len(name) count=0 if firstLetter not in contacts: return 0 else: ...
fe4aa08ae962559ee48a37110639bbcd61791dd9
525642022/learn_pyhton_basic
/day2/zidian.py
602
3.671875
4
# 作者 ljc # 集合 字典 列表 # 字典 key-value 键值对 # 不要用 pop info = { "name1": "ljc1", "name2": "ljc2", "name3": "ljc3", } info1 = { "name3": "ljcmm", 1: 2, 2: 3, } print(info.items()) info.update(info1) print(info["name1"]) info["name1"] = "ljc0" info["name4"] = "ljc4" del info["name1"] print(info) print(...
61c3f982c46561ec7371d42ce295ee466545e385
jwong1MHS/InfraMed
/account.py
811
3.53125
4
from mdb import * from phone_calls import * first_name = "Jason" last_name = "Wong" full_name = first_name + " " + last_name phone_number = "+12027409056" sid = "ACf13af826fa88d4d1b52e226f1a8fe178" token = "d47eeb79017dc730811182330f4e57df" def addPatient(): print('- PATIENT INFORMATION -') print() last_n...
9c9e1f32c5f89f34d5ce3cf060bfcf2f7078a116
radomichel/trening
/kalkulator.py
406
3.625
4
print('Witam w prostym kalkulatorze') wynik=0 x = int(input('Podaj dwie liczby:\n')) y = int(input()) def suma(x,y): wynik=x+y return wynik def iloczyn(x,y): iloczyn=x*y return iloczyn def odejmowanie (x,y): roznica=x-y return roznica print('Suma tych liczb to: ', suma(x,y)) print('Roznica tych ...
8d26e898d5fb745283d627c1a4e13427d2da8fb1
manojvaleti/python
/factorial.py
205
3.953125
4
#!/usr/bin/python #definition for factorial function def fact(n): fact = [1]*(n+1) for i in xrange(1,n+1): fact[i] = fact[i-1]*i return fact[n] #input a = input() #output print fact(a)
5e31acdf8c22423877f2f56b40240592276cd1cc
BeyondDreamers93/HandWrittenDigitReader
/training.py
2,121
3.53125
4
import cv2 import numpy as np class trainModel: def __init__(self): self.trainData = None self.testData = None self.trainLabels = None self.testLabels = None self.inputImagePath = './train/digits.png' return def trainAndTestKNN(self,kValue): ...
a5e15630bd431f77ade5c7d1190ee3526fa32774
essourya/c98
/sawppingFile.py
367
3.796875
4
from os import read def swapfile(): file1=input("enter file 1 name") file2=input("enter file 2 name") with open(file1, 'r')as a: data1=a.read() with open(file2, 'r') as b: data2=b.read() with open(file1,'w')as a: a.write(data2) with open(file2,'...
e3c01ad7dfc60365aad82332e143bd6b9b6abe93
PyMavs/blog
/src/pages/18-10-02 Lists/list.py
4,700
4.3125
4
def example1(): # Python Lists are similar to arrays in C and vectors in C++ # but they are a category of "collection". three = 3 a = [[-1, 0], 1, 'two', three, 4.0, 20/4, '6'] a[0] = "zero" # Unlike strings in python (immutable character lists) # lists are mutable, which means changable. # Lists in Pytho...
9765adef9ee9f48b6b455175a848140a7d22722d
informatique-minute/tri-a-bulles
/python/tri_a_bulles.py
915
3.953125
4
# Tri à bulle en python # Source: http://www.lepython.com/tri-a-bulles/ def Tri_bulle (L) : permutation = True n=len(L) while permutation==True : #on répéte la procédure tant qu'on a trouvé une permutation (c-à-d L[i]&gt;L[i+1] l'élément e de la liste est plus grand que l'élément qui le suit) pe...
01600e408cd225fd971287ea74c898eff25bc65a
cmunozcortes/advent-of-code
/20191203/crossed_wires.py
2,102
3.8125
4
""" Solution to Day 3: Crossed Wires from adventofcode.com """ import re import numpy as np # Function to find the final position given a starting position and a path def find_coordinates(initial, path): # Path is a list of directions in the format (left/right, distance) (x, y) = (initial[0], initial[1]) c...
75e03f156082c03a2170993e90c2507dff58721a
ge01/StartingOut
/Python/chapter_03/programming_exercises/pe_0301/pe_0301/pe_0301.py
1,107
4.65625
5
######################################################### # Kilometer Converter # # This program asks the user to enter a distance in # # kilometers, and then converts that distance to miles. # # The conversion formula is as follows: # # Miles = Kilometers * 0.6214 ...
0d221fdda61f6e695a6e8106a3376fdc0c051ec9
meiziyuan/learn
/base/Generator.py
1,996
3.65625
4
#一边循环一边计算的机制,称为生成器generator #创建generator的第一种方法:将列表生成式中的[]改成(),就创建了一个generator g = (x*x for x in range(1,10)) for x in g: print(x) #创建generator的第二种方法:如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator #斐波那契数列1,1,2,3,5,8,13... 计算第N个数是多少,并打印截止到该数的数列 def fib(N): n, a, b = 0, 0, 1 list=[] while(n < N): ...
49ff48c60460d7e09320f127160081e852867978
meiziyuan/learn
/OOP/learnOOP.py
3,266
4
4
#由于类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。 # 通过定义一个特殊的__init__方法,在创建实例的时候,就把name,score等属性绑上去: class Student(object): mateclass = 0 #类属性 __slots__ = ('name','score','sex') #使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的 #特殊方法“__init__”前后分别有两个下划线!!! def __init__(self,name,score,sex): #类...
92212e96309961c30ab3df40e75c385d42c147dd
stt106/pythonbeyondbasics
/classes/shipping.py
7,578
4.5
4
""" Choose between static method and class method 1) If need to refer to the class object within the method, e.g. to access class attribute then use class method. Otherwise (no need to access either instance or class attribute) prefer to use staticmethod. 2)In practice, most static methods are internal im...
6dc2fb39c5b7118c76d9136cd00ed1ee25878d96
stt106/pythonbeyondbasics
/exceptions/exception.py
1,141
3.546875
4
from random import randrange # The built-in exceptions are in inheritance hierarchy (just like C#) and the most base class is BaseException though in practice custom exceptions should derive from Exception class. # It's recommended that custom exception class only takes a single string as the payload so that it's cons...
5571daf47c52234043ed1f8d6463ad6a25fe06a3
niranjan889/Python_fun
/LP.py
1,453
3.9375
4
''' Created on 2016-09-25 @author: Niranjan ''' import pulp def solve_lp(): #create the LP object, set up as a maximization problem prob = pulp.LpProblem('XYZ', pulp.LpMaximize) #set up decision variables ships = pulp.LpVariable('ships', lowBound=0, cat='Integer') boats = pulp.LpVariable('bo...
8ee4048254084cfc338030f7afb01e173987dce5
cristianrodriguez05/phyton-pool-de-objetos-singleton-herencia-e-hilos
/herencia singleton/area con singleton.py
543
3.515625
4
from math import pi class Figura(object): __instance = None area = None radio = None """ Una figura en el plano. """ def __new__(cls): if Circulo.__instance is None: Circulo.__instance = object.__new__(cls) return Circulo.__instance def area(self): ...
5b3f74622c4a9d4b11b4dfb66a52f32d67c38f79
shekharbiswas/Mukil
/Function/library.py
212
3.578125
4
def unique_item(l1): return list(set(l1)) def sort_list(l1): return l1.sort_list() def fib(n): a, b = 0, 1 while (a < n): print(a, end=' ') a = b b = a + b print()
4d045fb14fb13c42f2043a8fbcde3dcba1b926a4
merveuncu/my-first-blog
/hi.py
161
3.578125
4
def hi (name): print('Merhaba ' + name + '!') kızlar = ['Merve', 'Kübra', 'Beyza', 'Sen'] for name in kızlar: hi(name) print('Sıradaki kız')
d6325c570fb83d419494b868bf508b8dd17247d1
alf200/week6skills
/anagram.py
532
4.0625
4
word_one = input("Enter a word: ").casefold().strip() word_two = input("Enter another word: ").casefold().strip() word_one_list = list(word_one) anagram = f"{word_one} and {word_two} are anagrams!" not_anagram = f"{word_one} and {word_two} are not anagrams!" check_anagram = True if len(word_one) != len(word_two):...
abdd052b5d57d6181e0d12a28283889354f045e5
jjsanabriam/JulianSanabria
/Taller_1/palindromo.py
410
4.4375
4
'''It reads a word and it validates if word is a palindrome Args: PALABRA (string): word to validate Returns (print): resultado (string): Result of validate word (False or True) + word validate ''' print("Ingrese Palabra: ") PALABRA = input() PALABRA_MAYUSCULA = PALABRA.upper() if PALABRA_MAYUSCULA != ...
93e067e85e2094498bc22c5afb0764f4d515eeed
piskunovma/Python_hw
/les2/hw4.py
650
4.0625
4
""" 4. Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове. """ var_str = input('Введите строку из нескольких слов через пробел: ') var_str = var_str.split() for number, ...
5f430dcd768230062b69004348041912274cb180
piskunovma/Python_hw
/les3/hw1.py
873
4.3125
4
""" 1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. """ def my_func(number1, number2): try: number1, number2 = int(number1), int(number2) if number2 == 0: ...
b91944901cb2c351bb0f1844e6436b8067f6138c
piskunovma/Python_hw
/les2/hw3.py
1,843
4.21875
4
""" 3. Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц (зима, весна, лето, осень). Напишите решения через list и через dict. """ # Решение через list # month = input("Введите номер месяца : ") # result_list = ["Зима", "Весна", "Лето", "Осень"] # # if month.isdi...
61345df8cd8eaf9a8f82d3c1fdd2e1b4ae13f0cd
piskunovma/Python_hw
/les2/hw1.py
568
4
4
""" 1. Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа. Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. """ list_new = ['строка', 234, (1, 2, 3), True] for check ...
facc0ddf980a825b8587cc05e4caf70ff85415b8
bdllhdrss3/fizzbuzz
/fizzbuzz.py
556
4.1875
4
#making a fizz buzz app #creating input of list list1 = input("Enter list one : ") list2 = input("Enter list two : ") length1 = len(list(list1)) length2 = len(list(list2)) sumation = length1 + length2 fizz = sumation%3 buzz = sumation%5 #now creating the fizzbuzz function def fizzbuzz(): if buzz == 0 and fizz == ...
0fca0b79a15d6c2edef6e04bf8a9a524b25cc0de
SaintAndrewsmLAB/cwitt_is_compsci
/Test Files/raw_input_test.py
225
3.9375
4
prompt = raw_input ("What...is the airspeed velocity of an unladen swallow?\n") speed = input(prompt) true_speed = 69 if speed == true_speed: print 'Correct!' else: print 'Wrong! The correct answer is ', true_speed
ed0ffb243d94202ba765efb1ad8d721865903ab6
SaintAndrewsmLAB/cwitt_is_compsci
/Python Notes/chapter_2.py
8,966
4.375
4
############# # Carson Witt # Independant Study: Intro. to Computer Science - Fundamentals of Programming # Mr. Nelson # NOTES ############# ### Chapter 2: Variables, Expressions and Statements ### # *VALUES* # A number or string (or other thing to be named later) that can be stored in a varia...
42f2ac7531efbc7b8ecfdb19cdf0039467bedb82
diptejsaner/CheckDataUsage
/backup.py
848
3.59375
4
import os def getFolders(path): templist = os.listdir(path) for item in templist: if (os.path.isfile(item) == True): templist.remove(item) return templist def getBackuplist(llist, hlist): blist = [] for item in llist: if item not in hlist: blist.append(item) return blist laptop_list...
1d321d35e2230dbb5ba144353c8a77509c2be43e
Arun101308/Arun101308
/CALCULATOR.py
351
3.96875
4
a = input("val1 a") #INPUT THE VALUE A IN RUN TIME b = input("val b") #INPUT THE VALUE B IN RUN TIME sum0 = int(a) + int(b) #ADD TWO NUMBER sum1 = int(a) - int(b) #DIV TWO NUMBER sum2 = int(a) * int(b) #MUL TWO NUMBER sum3 = int(a) / int(b) #DIV TWO NUMBER print("add=", sum0, ",sub=", sum1, ",mul=", sum2, ",div...
3bcb0df39685a7f03893db90797e2d11bd7bd46c
kingawel/Python
/algorithms/zad_3.py
198
3.59375
4
def scalarProduct(a,b): result = 0 wectorLen = len(a) # = len(b) for i in range(0, wectorLen): result += a[i] * b[i] return result a = [1, 2, 12, 4] b = [2, 4, 8, 2] print(scalarProduct(a,b))
1997314f38abc0bbb396dd428fe016820cbd0b06
kingawel/Python
/algorithms/zad_6_numpy.py
734
3.765625
4
from random import randint import numpy as np def matrixDet(mat): assert mat.shape[0] == mat.shape[1] #it must be a square matrix dim = mat.shape[0] for x in range(0, dim-1): for y in range(x+1, dim): if mat[y,x] != 0.0: temp = mat [y,x]/mat[x,x] ...
704d7556c9e6cbd093a8c2a60889a260f1e0d763
slemal/MATH0499-1
/source_code/MST.py
3,343
3.609375
4
#!/usr/bin/python3 # -*- coding:utf-8 -*- import networkx as nx from UnionFind import DisjointSet def kruskal_sg(g: nx.Graph) -> None: # O(E log(V)) """ Finds a minimum weight spanning tree in the simple graph g using Kruskal's algorithm. Edges that are part of the spanning tree have a "spanning" value set to tr...
69a7755282da2747c7f9d8bff445bfb554bebfb9
USTC-Titanic/webapp
/database.py
1,085
3.625
4
import sqlite3 DB_USER = 'db/user.db' SCHEMA = 'db/schema_user.sql' def init_db(): try: conn = sqlite3.connect(DB_USER) cur = conn.cursor() with open(SCHEMA, 'r') as f: cur.executescript(f.read()) conn.commit() except Exception as e: pass finally: cur.close() conn.close() class Database(object): ...
39475c90941664b7465f656722385b147ed59e5d
gitpqd/openclassrooms
/vendredi13.py
1,818
3.859375
4
''' Affiche la liste des vendredis 13 présents dans une année paramètres demandés : jour de la semaine au 1er janvier et année bissextile ou non. Python 3.x uniquement. Il s'agit d'un programme que j'ai rédigé il y a un an mais après tout il peut tout à faire servir dans le cadre de cet exercice :) A bientot! Pol ''' ...
b01da5d8d51c5d7e4017041b91f58876ffcf532c
CvsBurak/test-cases
/python-cases/largestrange.py
664
3.71875
4
# gets the largest range of numbers contained in the array def largestRange(arr): nums = {x:0 for x in arr} #creating hashmap for elements in arr left = right = 0 for num in arr: if nums[num] == 0: left_count = num - 1 right_count = num + 1 while left_count in nums: ...
870c0dfd2a231c58333094d896fb1dd786cd3800
yu15846318322/store
/bread.py
1,587
3.5
4
import threading import time bread = 0 class cook(threading.Thread): username = "" bread = 0 def run(self) -> None: global bread num = 0 while True: if self.bread < 500: self.bread += 1 bread +=1 num +...
68b24dd010de17d7f8102398086f0549833e67a3
joaojunior/data_structures_and_algorithms
/python_implementations/algorithms/sorting/insert_sort.py
282
3.78125
4
from typing import List class InsertSort: def sort(self, items: List) -> None: for i in range(1, len(items)): j = i while j > 0 and items[j] < items[j - 1]: items[j], items[j - 1] = items[j - 1], items[j] j -= 1
e64294a7899605acd4f7617bd03283ca431c09b2
joaojunior/data_structures_and_algorithms
/python_implementations/ds/linked_list.py
1,492
3.890625
4
from typing import Any class Node: def __init__(self, item: Any) -> None: self.item = item self.next = None class LinkedListIterator: def __init__(self, head: Node) -> None: self.__node = head def __next__(self) -> Any: if self.__node is not None: item = self...
6f672661f35ddbc64751f9dc921cfcfd247599fc
DaemonStark/Data-Structures-and-Algorithms
/Algorithms/Bubble_Sort.py
383
4.09375
4
def bubblesort(arr): for i in range(len(arr)): for j in range(0, len(arr)-i-1): if arr[j] > arr[j+1]: (arr[j], arr[j+1]) = (arr[j+1], arr[j]) if __name__ == '__main__': arr = [int(i) for i in input().split()] temp = [] bubblesort(arr) print("In ascending order")...
7e12bfbb72921de5a4a388e884abb7507a0847f8
jayden8388/python-beginner-projects
/number.py
149
3.796875
4
guess= input("enter number here"): x = 9 if guess > x: print 'Lower' if guess < x: print"higher" if guess == x: print "that's right"
3143fa40779e12e5e2f54fadfe718d3f2635698e
rauljm/estudos
/examples/estudos.py
1,171
3.890625
4
from collections import defaultdict import heapq class PriorityQueue(object): def __init__(self): self._queue = [] self._index = 0 def push(self, item, priority): heapq.heappush(self._queue, (-priority, self._index, item)) def pop(self): return heapq.heappop(self._queue)...
611dd5f0b15ce1a9d4b9bf08b2f037afe4e2ceb5
sgawalsh/Sudoku
/Sudoklasses.py
11,317
4.09375
4
class square(object): def __init__(self, x, y): self.pot = [1,2,3,4,5,6,7,8,9] self.x = x self.y = y self.solved = False def assignVal(self, val): self.pot = [val] self.solved = True def remPot(self, rems): for el in rems: if el in self....
61667c9ec41dde068517b7fb154b2bcafc23ec14
GuyArieli17/last_resualt
/stemmer.py
1,114
3.5
4
from nltk.stem import snowball, PorterStemmer class Stemmer: def __init__(self): self.stemmer = PorterStemmer() # snowball.SnowballStemmer("english") def stem_term(self, word): """ This function stem a token :param token: string of a token :return: stemmed token ...
02a58b54ac28b1f5736f4e8a2be278e03befe0c6
hallb/learn-to-tensorflow
/templates/01-multiply.py
474
3.546875
4
### imports import tensorflow as tf ## data input1 = [[3. , 5.]] input2 = [[7.],[1.]] # Multiply a 1x2 [[3.,5.]] by a 2x1 [[7.],[1.]] a = # TODO b = # TODO ## induction # Set up two constants to be multiplied # Multiply a by b c = # TODO ## training # Run tensorflow and print the result, the result should be 26 w...
c0abefd6a9ffd73211f80c3250cb333db7840f0c
AlphaLU/RaspberryPi
/RPiCameraLED.py
1,051
3.53125
4
import time import picamera import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(12, GPIO.OUT) camera = picamera.PiCamera() camera.hflip = True camera.vflip = True def BlinkPhoto(num, speed): for i in range(0, num): try: print "[*] Taking photo number: " + str(i) camera.start_preview() GPIO.output...
1626bcfbc0a97017875350604a88af1fcc3b1401
shalinichaturvedi20/fun
/fun10.py
485
3.796875
4
def functionmultiply(a,b): multiply=a*b return multiply print(functionmultiply(3,4)) # def Avg(number1,number2,number3): # avg=number1+number2+number3/3 # print(sum) # Avg(1,3,2) # def voter(age): # if age>=18: # print("eligible") # else: # print("not eligible") # voter(20)...
b1c82f22edf8b33ed3ae9ae9e623421d0dd22b51
adi2423/assignments
/question3.py
304
3.640625
4
def equilibrium(arr): total_sum = sum(arr) leftsum = 0 for i, num in enumerate(arr): total_sum -= num if leftsum == total_sum: return i leftsum += num arr = [2,4,4,1,5,4,1] print ('First equilibrium index is ', equilibrium(arr))
05248ddf4e02263d4d90bf75a12344b474eedc55
cosmicc/docker-postprocess
/remove_music_dupes.py
1,908
3.515625
4
#!/usr/bin/env python3 # Removes duplicate tracks from albums import sys from pathlib import Path try: basepath = Path(sys.argv[1]) except: print('Invalid directory to scan') sys.exit(1) if not basepath.exists(): print('Invalid directory to scan') sys.exit(1) oldfile = '' for file in basepath.rgl...
b5a7dbaf75851eb2c217716e3177ff10527c38d3
emriti/IntroMLKaggle
/creating_model.py
1,099
3.609375
4
import numpy as np # Data Loading Code Hidden Here import pandas as pd # Load data melbourne_file_path = 'input/melbourne-housing-snapshot/melb_data.csv' melbourne_data = pd.read_csv(melbourne_file_path) # Filter rows with missing price values filtered_melbourne_data = melbourne_data.dropna(axis=0) # Choose target a...
12bb0ddd5cbe5ad563d3e0fac434ad1457d3bff6
poulomi-g/Huffman-Encryption
/huffman.py
1,198
3.9375
4
class TreeLeaf: """ Leaf node of a Huffman tree. Stores the value. Should store an 8-bit integer to represent a single byte, or None to indicate the special "end of message" character. """ pass class TreeBranch: """ Simple representation of an internal node on a Huffman tree. Just ...
a628b4557a2f8646e32465c890eb89d648c68648
tbiehle/spelling-bee
/main.py
1,738
3.6875
4
import pyautogui words = open('words', 'r') words_list = [word[:-1] for word in words] class Hive: """A solver for the New York Times' Spelling Bee. Takes the outer letters and center letter as parameters, then solves the puzzle.""" def __init__(self, outer_letters, center_letter): self.oute...
f20880c0bec81b40b19ed02e1e13e2549c2d033f
lttviet/randomPy
/singleByteXOR.py
2,057
3.84375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Give a hex string which has been xor against a single char. # Find the key and decrypt the message import sys import string import util def score(text): """ Based on the letter frequency in English, give a text a score. """ freq = {"a": 8, "b": 1, "c": 3, "...
be44021a4addcc2a1c0683908943160924fdcfd0
GrabbarnaPython/kval20_uppg5
/main.py
421
3.609375
4
#allt koden gör är att integrera ihop de olika programmen och dess funktioner. Den hämtar listans värde från List.py. Sedan skjuter den in imformation om nuvarande position till FindPath import List import FindPaths coords = List.makeLists() lista = [] print(FindPaths.lookAround(1, 1, 1, lista, coords)) # for x in...
295e2aaeb0d34f887942fc455117d2ccb0c7b29b
mahoep/ME-499
/HW1/grade_cutoff.py
661
3.609375
4
#!/usr/bin/env python3 ''' @author Matthew Hoeper ''' def grade_cutoff(scores): ''' Calculates the grade cutoff marks based on 10% get an A, 20% get a B, 30% get a C, 30% get a D, and the rest get an F :requires a list with the final scores :returns grade cutoff for A,B,C,D ...
937d3e8f9db7f22bdfd0c9cf24f8acbc2bf97850
mahoep/ME-499
/HW1/hardest_lab.py
868
3.796875
4
#!/usr/bin/env python3 ''' @author Matthew Hoeper ''' def hardest_lab(headers, data): ''' Calculates the most difficult lab in grades.csv based on lowest average :requires a list with the headers from the csv file :requires a numpy array with all of the data from csv file :returns...
8c596edd04c16ddb0d9b8abde49099ed1f28542d
mahoep/ME-499
/HW1/hardest_assignment.py
775
4.0625
4
#!/usr/bin/env python3 ''' @author Matthew Hoeper ''' def hardest_assignment(headers, data): ''' Calculates the most difficult homework assignment in grades.csv based on lowest average :requires a list with the headers from the csv file :requires a numpy array with all of the data from csv file ...
5edbf9e19500e80d52c7fbc9ba053b11fb0873af
avast/retdec
/scripts/type_extractor/type_extractor/substitute_json_keys.py
3,072
3.578125
4
"""Substitutes all types' keys in JSON with natural numbers.""" from .json_types import TYPES def substitute_json_keys_with_natural_numbers(content): new_keys = generate_new_keys(content['types']) substitute_json_keys(content, new_keys) def substitute_json_keys(content, new_keys): """Substitutes json ...
e49cb03a0b1432747ad801b4a513131fce21213e
kingbob2015/python_playground
/practice_problems/merge_k_sorted_linked_lists.py
3,545
4.4375
4
# Given K sorted linked lists of different sizes. The task is to merge them in such a way that after merging they will be a single sorted linked list. # Input: # First line of input contains number of testcases T. For each testcase, first line of input contains number of linked lists N and next line contains data of n...
70450e548022bcece5d81760ff73ab184b5ab605
kingbob2015/python_playground
/algorithms/binary_search.py
371
3.859375
4
def binary_search(arr, target): low,high = 0, len(arr)-1 while(low<=high): mid = low + (high+low)//2 if arr[mid]==target: return mid elif arr[mid] < target: low = mid+1 else: high = mid-1 return -1 if __name__ == '__main__': test = [1,...
a8b0b1306df3c42d9333f9d979b494a39ca79d96
Resham1458/Max_Min_Number
/max_min_nums.py
520
4.34375
4
total=int(input("How many numbers you want to enter?")) #asks user the total number he/she wants to enter numbers = [int(input("Enter any whole number:")) for i in range(total)] # lets the user to enter desired number of numbers print("The list of numbers you entered is:",numb...
0cc4375b4bdce67644fa9a56784738b057b847f5
kathytuan/CoffeeMachine
/main.py
2,606
4.125
4
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { ...
8dea95c2fd8f0d5863b6188584304812f7b3d0ff
froggie901/interactive_dictionary
/scripts/dictionary.py
1,053
3.875
4
#import libraries import json from difflib import get_close_matches #data import data = json.load(open('../data/english_dictionary_data.json')) # function searches the json libary based on user input def translate (w): #input is case agnostics w = w.lower() #user provided word is in the dictionary ...
18badfd7dde9091b84f8964e8d4993e1e382baed
berkcohadar/River-Problem-AI-Backtracking
/Graph.py
1,716
3.59375
4
from collections import defaultdict from State import FINALSTATE import time class Graph: def __init__(self): self.bfs_parent = {} def heuristic(self, node): print("Sum of People: "+ str(node.island1people)+ "\n") sum = node.island1people if sum == 1: return 1 return 2*sum-3 def closest(self, queue): ...
b3d95cbab7a7bc2cf80758bc7e3dc951201334b9
Hosuke/Python
/MIT_6.00.1x/Problem Set 2/PS2Q3.py
699
3.65625
4
#MIT 6.00.1x Problem Set 2 Q3 #By Huang Geyang balance = 999999 annualInterestRate = 0.18 monthInterestRate = annualInterestRate / 12.0 low = balance / 12 high = (balance * (1 + monthInterestRate) ** 12) / 12.0 epsilon = 0.01 while True : totalPaid = 0 tempBalance = balance monthlyPaymentRate = (low + hi...
a281a9d3c6e8037b709b7eb717662368e16190b2
Hosuke/Python
/Algorithms/graph.py
4,774
4.15625
4
"""Graph Module Graphs can be represented as adjacency lists or matrices. In this module, the adjacency list approach is taken. If a matrix graph is required, see the matrix module. In this module, a graph is simply a set of vertices V and a set of edges E. In python-speak, E is a set of tuples of e...
70e01caa256ca17348f229e26a8f7e082677bfd8
Hosuke/Python
/MIT_6.00.1x/Problem Set 2/PS2Q2.py
474
3.515625
4
#MIT 6.00.1x Problem Set 2 Q2 #By Huang Geyang balance = 3329 annualInterestRate = 0.2 monthInterestRate = annualInterestRate / 12 for monthlyPaymentRate in range(10,balance,10): totalPaid = 0 tempBalance = balance for i in range(1,13): totalPaid += monthlyPaymentRate tempBalance -= mont...
6137f2c8970fd7c5e0ab361f20c7a3e0cb5e98df
umesh-gattem/Python_Programs
/PluralAlphaUsingFiles.py
531
3.703125
4
import re def match_rule(pattern, word): return re.search(pattern, word) def apply_rule(search, replace, word): return re.sub(search, replace, word) rules = [] words = ["coach", "wax", "vacancy", "day"] for word in words: with open("plural.txt", encoding="utf-8") as plural_file: for line in pl...
ab3c4345a3641a69eb69bd09d7b440b09f17b3b4
adityaapi444/python_class
/q3ass4.py
161
4.15625
4
s=input("enter a string") vowel=['a','i','e','o','u'] for each in s: if each.lower() in vowel: print("buzzzzz") else: print(each)
8c52362be660a0fd177044eb209070955f6d32ec
adityaapi444/python_class
/create list 1to n.py
87
3.640625
4
n=int(input("enter a no.")) b=[] for i in range(1,n+1): b.append(i) print(b)
92659a412c2e7ea49f3e72db8063eea474621e06
adityaapi444/python_class
/count.py
169
3.53125
4
L=['Apple','Mango',2,4.5,6,2,'Apple',4.5,2,'Apple'] L_uni=[] for each in L: if each not in L_uni: L_uni.append(each) print(each,L.count(each))
24d9af11936e79284b816be361cc3f4a9fcfce98
adityaapi444/python_class
/discountelif.py
379
3.796875
4
MRP=float(input("enter the price\t")) offer=int(input("select any one offer\n1. 75%\n2. 60%\n3. 40%\t")) if(offer==1): MRP=MRP-MRP*0.75 print("To Pay : {}".format(MRP)) elif(offer==2): MRP=MRP-MRP*0.6 print("To Pay : {}".format(MRP)) elif(offer==3): MRP=MRP-MRP*0.4 print("To Pay : {}"....