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
d5a5865ba7093b98233327b3f159751422511629
frollo/AdvancedProgramming
/Lab-4/es2.py
1,097
3.6875
4
class SocialNode(object): def __init__(self, name): self.name = name self.connections = list() def addConnection(self, tag, other): self.connections.append((tag, other)) other.connections.append((tag, self)) def __visit__(self, visited=None): if visited is None: vis...
67fcb010226731a071c51b6b0e59f254eaf7a106
frollo/AdvancedProgramming
/exams/2015-06-16/quickrecursion.py
903
3.875
4
def memoization(fun): past_values = dict() def wrapper (*args): if args in past_values: print ("### cached value for {0} --> {1}".format(args, past_values[args])) else: past_values[args] = fun(*args) return past_values[args] return wrapper @memoization def fi...
97fbde95357d10d54ef0533a0a2ea5b8ac4086e7
ninnin92/Pyworks
/auto_analysis/days to age.py
3,286
3.78125
4
#!/usr/bin/env # -*- coding: utf-8 -*- import pandas as pd from datetime import date, timedelta, datetime ################################################ # 宣言 ################################################ s_data = pd.read_csv("subject_age.csv") ################################################ # 処理関数 #########...
6d16dd48bab98affcb0df5e64cd1158e846b1e57
foundjem/COMP551-Applied-Machine-Learning
/Project 3/Code/train_test_LR_SVM_NN_raw_pixels.py
1,872
3.53125
4
# -*- coding: utf-8 -*- ''' Perform Logistic Regression, SVM and feed-forward neural network using raw pixel values on the test data ''' import sklearn import numpy as np import scipy.misc # to visualize only from scipy import stats from sklearn.decomposition import PCA as sklearnPCA from sklearn.featur...
e0a5afb486454fc6def28ed6c5bb593528bcd246
foundjem/COMP551-Applied-Machine-Learning
/Project 3/Code/train_test_LR_SVM_NN_Daisy.py
2,580
3.5
4
# -*- coding: utf-8 -*- ''' Perform Logistic Regression, SVM and feed-forward neural network using Daisy features on the test data ''' import sklearn import numpy as np import scipy.misc # to visualize only from scipy import stats from sklearn.decomposition import PCA as sklearnPCA from sklearn.feature_se...
2c4ac0b414a5644612b8c956b253d40c6329b94b
PeterPZhang/CrossRiver
/CrossRiver.py
6,117
3.53125
4
edgeFlag1=True #河岸标识符现在在A岸 edgeFlag2=False#河岸标识符 与上面一样 用这两个就可以表示船 sheep1=[1,1,1]#河岸A的羊 sheep2=[]#河岸B的狼 wolf1=[1,1,1]#河岸A的狼 wolf2=[]#河岸B的狼 GameFlag=True#游戏开始标志 edge1="A"#用来识别A岸 edge2="B"#用来识别B岸 step=0 winner_list=[] winner={} def oprate(SheepA, SheepB, WolfA, WolfB,EdgeFlag1,EdgeFlag2):#键入操作进行游戏 global edgeFlag1,...
b32fa0aa5cf1525a58af1887b5616554f97b767f
atanasbozhinov/simple_2d_array_operations
/core/matrix_operations.py
480
3.546875
4
import numpy as np def append(input_x, input_y): try: output = np.append(input_x, input_y, axis=0) except ValueError: return None return output def combine(input_x, input_y): try: output = np.append(input_x, input_y, axis=1) except ValueError: return None retu...
dec49accb05722be663a3b935e948db291948826
lerrigatto/algo2
/src/lesson7/bfs.py
1,014
3.6875
4
# Implement DFS algorithm import networkx as nx import random def bfs(G,u): """ Breath First Search """ visited = [] visited_edges = [] walk = [] visited.append(u) walk.insert(0,u) while len(walk) > 0: v = walk.pop() adj = G.successors(v) print(f"v:{v}, adj:{list(G...
77b80551538eb2521a2244e396b166336b6bff7d
lerrigatto/algo2
/src/es07-bt/es0708.py
1,277
3.75
4
# Dato n, si stampino tutte le matrici di interi n x n tali che # le righe e le colonne della matrice siano in ordine crescente def print_matr(M): for line in M: print(''.join(str(line))) print("---") def stampa_bt(n, M, i=0, j=0, c=0): if i == n: print_matr(M) return else: ...
9ce0934bfba140a3fef6e1f11dba2817a7d120f0
SwapnaSubbagari/python-challenge
/PyBank/main.py
1,793
3.625
4
import os import csv import pandas as pd datapath = os.path.join('Resources','budget_data.csv') #Opening the file with open(datapath) as budget_data_file: df = pd.read_csv(datapath, usecols = ['Date','Profit/Losses']) #Calculating unique list of Months and count of Months unique_TotalMonths = df['Date'].unique...
fa3cf86e4519a406c8de6544c9acac1c0e6a3813
tahabroachwala/lists
/DigitsReturn.py
256
4.03125
4
# Write a function that takes a number and returns a list of its digits. # So for 2342 it should return [2,3,4,2]. def returnDigits(num): num_string = str(num) num_list = [int(i) for i in num_string] return num_list print(returnDigits(2432))
f4890460ff11e22734a6fbd86de168a5c28f5ba9
tahabroachwala/lists
/BubbleSort.py
314
4.03125
4
def bubbleSort(list1): for passnum in range(len(list1) - 1, 0, -1): for i in range(passnum): if list1[i] > list1[i+1]: list1[i], list1[i+1] = list1[i+1], list1[i] else: continue list1 = [54,26,93,17,77,31,44,55,20] bubbleSort(list1) print(list1)
e7c0cc03577d1dee49c6618f998312af4d18aa84
abbeychrystal/CodingDojo_PythonRepo
/pythonFeb2021/python_fundamentals/for_loop_basic1.py
1,159
4.09375
4
# Basic - Print all integers of 5 from 5-1000 for i in range(0, 151, 1): print(i) # Multiples of Five - Print all the multiples of 5 from 5 to 1,000 for i in range(5, 1001, 5): print(i) # Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If divisible by 10, print "Co...
4e1a29434d93da6c303babfbfb477f5cd0ac6ecf
abbeychrystal/CodingDojo_PythonRepo
/_python/OOP/INtroOOPnotes.py
5,581
4.6875
5
# As almost all applications revolve around users, almost all applications define a User class. Say we have been contracted to build a banking application. The information we need about a user for a banking application would be different than what we would need if we were building a social media application. If we allo...
afce4efaa47e3addf871f4a1df08c4f620a292da
willwburdick/Shared_Class_Work
/Assignment_05.py
3,627
4.3125
4
# ---------------------------------------------------------------------------------------------------------------------- # Title: Assignment 05 # Dev: William Burdick # Date: 04/30/2018 # Description: Read and write a text file # This project is like to the last one, but this time The To Do file will contain two c...
6575a721c66f1f75f16f6662c2cca21dc3bb03c8
EricB2745/Data_Analytics_and_Visualizations
/Numpy/CreatingArrays.py
808
3.515625
4
import numpy as np # Create an array by converting a list my_list1 = [1,2,3,4] my_array1 = np.array(my_list1) print my_array1 my_list2 = [11,22,33,44] my_lists = [my_list1,my_list2] my_array2 = np.array(my_lists) print my_array2 print 'Shape of array: ' + str(my_array2.shape) print 'Type of array: ' + str(my_array2.d...
541bd87f9ff8191ea2b7758fad6d4af7206024d2
BeginnerA234/codewars
/задача_35_7kyu.py
306
3.546875
4
# https://www.codewars.com/kata/5667e8f4e3f572a8f2000039/train/python def accum(string): res = '' for i, s in enumerate(string): if i == 0: res = res + s.capitalize() else: res = res + '-' + (s * i).capitalize() return res print(accum('ZpglnRxqenU'))
173c8cb3559bb0b12cb3b93339ab0d69df5b9d8f
BeginnerA234/codewars
/задача_30_6kyu.py
483
3.71875
4
# https://www.codewars.com/kata/54da539698b8a2ad76000228/train/python def is_valid_walk(walk): print(walk) res = 0 random_name = '' for i in walk: if i in random_name or len(random_name) == 0: random_name += i res += 1 else: res -= 1 i...
8c93f27cd772c1b1dc179921157c51eb5419b32a
BeginnerA234/codewars
/задача_24_6kyu.py
301
3.75
4
# https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1/train/python def duplicate_count(text): res = 0 text = text.lower() for i in text: if text.count(i)>1: res+=1 text = text.replace(i,'') return res print(duplicate_count("abcdabcd"))
83bdc36e4e00b6aa0b7afcd4dee64707c1b3faf1
mpwesthuizen/eng57_factory
/general_functions.py
868
3.90625
4
# recap function # define a function def say_hello(name): return (f'Hello {name}' ) # #BAD! # def return_formatted_name(name): # print(name.title().strip()) def return_formatted_name(name): return name.title().strip() # print the return of the function outside - NOT print inside the function. If you d...
f78f63eee3f5c35d2a564abb81adf7a24f5dba3f
BryCant/Intro-to-Programming-MSMS-
/FInal/finalLibrary.py
2,489
3.84375
4
import random class Student: def __init__(self, name, age, glasses, volume, nag_level): self.name = name self.age = age self.glasses = glasses self.volume = volume self.nag_level = nag_level def __str__(self): return f"Hi I am {self.name} and I am {self.age} ye...
53439bc9fed95069408cec769fddd8fc2fc9376d
BryCant/Intro-to-Programming-MSMS-
/Chapter13.py
2,435
4.34375
4
# Exception Handling # encapsulation take all data associated with an object and put it in one class # data hiding # inheritance # polymorphism ; function that syntactically looks same is different based on how you use it """ # basic syntax try: # Your normal code goes here. # Your code should include function ...
ec9dc44facac9d6f6bdda9f3eb7c178c0b67ff0f
iannase/win2k17
/cycles.py
508
3.796875
4
wholeString = input() shifter = "" stringList = [] stringSize = "" stringShift = "" shift = 0 size = 0 z = 0 for x in wholeString: if z == 0: stringSize += x if z == 1: stringList.append(x) if z == 2: stringShift+= x if x == " ": z += 1 size = int(stringSize) shift = int(stringShift) stringList.pop(size) f...
2679e524fb70ea8bc6a8801a3a9149ee258d9090
daviscuen/Astro-119-hw-1
/check_in_solution.py
818
4.125
4
#this imports numpy import numpy as np #this step creates a function called main def main(): i = 0 #sets a variable i equal to 0 x = 119. # sets a variable x equal to 119 and the decimal makes it a float (do you need the 0?) for i in range(120): #starting at i, add one everytime the program gets to t...
d0da8ed0d77bc22e2b4212747ecbcf6c82b9a30c
mvinovivek/BA_Python
/Class_3/1_4_ValueError.py
303
3.671875
4
#Value error will be raised when you try to change the type of an argument with improper value #most common example of the value error is while converting string to int or float number=int("number") #The above statement will throw an error as "number" as a string cannot be considered as int or float
0d4aad51ef559c9bf11cd905cf14de63a6011457
mvinovivek/BA_Python
/Class_3/8_functions_with_return.py
982
4.375
4
#Function can return a value #Defining the function def cbrt(X): """ This is called as docstring short form of Document String This is useful to give information about the function. For example, This function computes the cube root of the given number """ cuberoot=X**(1/3) retur...
53cee6f939c97b0d84be910eee64b6e7f515b12f
mvinovivek/BA_Python
/Class_3/7_functions_with_default.py
680
4.1875
4
# We can set some default values for the function arguments #Passing Multiple Arguments def greet(name, message="How are you!"): print("Hi {}".format(name)) print(message) greet("Bellatrix", "You are Awesome!") greet("Bellatrix") #NOTE Default arguments must come at the last. All arguments before default are...
626da3ed48d7dabc2074e13c6c6fda948a5ab34c
mvinovivek/BA_Python
/Class_3/1_7_IndexError.py
327
3.953125
4
#index errors will be raised when you try to access an index which is not present in the list or tuple or array X=[1,2,3,4,5] print(X[41]) #in case of dictionaries it will be KeyError Person={ 'Name': 'Vivek', 'Company' : 'Bellatrix' } print(Person['Name']) #it will work print(Person['Age']) #it will throw K...
0eb58cd27ce6822be0c7dc2d66524bbd6a207659
mvinovivek/BA_Python
/Class_4/10_comparting_projectiles_class.py
2,365
3.90625
4
import numpy as np import matplotlib.pyplot as plt class projectile(): g=9.81 def __init__(self,launch_angle,launch_velocity): self.launch_angle=launch_angle self.launch_velocity=launch_velocity def duration(self): duration=2*self.launch_velocity*np.sin(np.radians(self.launch_angl...
3cb1bc2560b5771e4c9ec69d429fcfd9c0eadd2c
mvinovivek/BA_Python
/Class_2/7_for_loop_2.py
1,009
4.625
5
#In case if we want to loop over several lists in one go, or need to access corresponding #values of any list pairs, we can make use of the range method # # range is a method when called will create an array of integers upto the given value # for example range(3) will return an array with elements [0,1,2] #now we can...
3cbfde72e5c26d2a8f498273e1e11ce7c8d65fe1
mvinovivek/BA_Python
/Class_5/7_widgets_radio_use.py
855
3.71875
4
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import RadioButtons Xvals=np.linspace(0,2*np.pi,50) Yvals=np.sin(Xvals) Zvals=np.cos(Xvals) #Creating the Plot # Plotting fig = plt.figure() ax = fig.subplots() plt.subplots_adjust(right=0.8) plt.title("Click the Radio Button to Change the C...
c9a6c2f6b8f0655b3e417057f7e52015794d26d6
316126510004/ostlab04
/scramble.py
1,456
4.40625
4
def scramble(word, stop): ''' scramble(word, stop) word -> the text to be scrambled stop -> The last index it can extract word from returns a scrambled version of the word. This function takes a word as input and returns a scrambled version of it. However, the letters in the beginning and ending do not change. ...
c456b13bb5316097a6856510e0e0140765216f18
Rahulllkumarrr/Simple-Program
/Cut the sticks.py
2,366
3.65625
4
''' Cut the stick ------------- You are given a number of sticks of varying lengths. You will iteratively cut the sticks into smaller sticks, discarding the shortest pieces until there are none left. At each iteration you will determine the length of the shortest stick remaining, cut that length from each of th...
a7a2abaa6a70a9da4f81c1c5a9d7d231e9551434
Rahulllkumarrr/Simple-Program
/diagonal Difference.py
492
3.796875
4
def diagonalDifference(a): right,left=0,0 n=len(a) l=n-1 r=0 for i in range(n): right=right+(a[r][r]) left=left+a[r][l] r+=1 l+=-1 difference=abs(right-left) return difference if __name__ == "__main__": n = int(input().strip()) a = []...
476f71e3734a9ab494dd28662b5ceac58f321ffc
TundraStorm/raticus
/MyGame/on_key_press.py
555
3.671875
4
import arcade def on_key_press(self, key, modifiers): """Called whenever a key is pressed. """ # If the player presses a key, update the speed if key == arcade.key.UP: self.player_sprite.change_y = 7 #self.player_sprite.change_y = -MOVEMENT_SPEED*0.5 elif key == arcade.key.DOWN: ...
d24514f8bed4e72aaaee68ae96076ec3921f5898
ChanghaoWang/py4e
/Chapter9_Dictionaries/TwoIterationVariable.py
429
4.375
4
# Two iteration varibales # We can have multiple itertion variables in a for loop name = {'first name':'Changhao','middle name':None,'last name':'Wang'} keys = list(name.keys()) values = list(name.values()) items = list(name.items()) print("Keys of the dict:",keys) print("Values of the dict:",values) print("Items of th...
d22d71b73ef371210d49a71f2abb69383e97cca8
ChanghaoWang/py4e
/Chapter2/assignment2_3.py
260
3.78125
4
inp_hour=float(input('Enter the hour:')) inp_rate=float(input('Enter the rate per hour:')) if inp_hour > 40: inp_rate_new=1.5*inp_rate grosspay = inp_rate_new*(inp_hour-40)+40*inp_rate else: grosspay=inp_hour*inp_rate print('Grosspay is',grosspay)
47675250b07dd0f5a0c3eae348b35ee4885a04a2
ChanghaoWang/py4e
/Chapter10_Tuples/Commonwords.py
671
3.921875
4
#Count words Chapter 10 Page 131 import string inp = input("Please enter the filename: ") if len(inp) < 1: inp = 'romeo-full.txt' try: fhand = open(inp) except: print("Cannot open the file:",inp) quit() count_dict = dict() for line in fhand: line = line.translate(str.maketrans('','',string.punctuati...
3cae3e36c80ac6d2040d872705091194edc954af
ChanghaoWang/py4e
/Chapter8_Lists/modify.py
612
4.09375
4
# List modify #It's important to remember which methods modify the list or create a new one def delete_head(t): del t[0] def pop_head(t): t.pop(0) def add_append(t1,t2): t1.append(t2) def add(t1,t2): return t1 + t2 def delete_head_alternative(t): return t[1:] letters = ['a',1,'b',2,'c',3] delete_hea...
6d325039a3caa4c331ecc6fa6bb058ff431218f8
ChanghaoWang/py4e
/Chapter8_Lists/note.py
921
4.21875
4
# Chapter 8 Lists Page 97 a = ['Changhao','Wang','scores',[100,200],'points','.'] # method: append & extend a.append('Yeah!') #Note, the method returns None. it is different with str a.extend(['He','is','so','clever','!']) # method : sort (arranges the elements of the list from low to high) b= ['He','is','clever','!'] ...
4be436e6a4b5aff0bcdd99dded5d1a2c3ce0763e
ChanghaoWang/py4e
/Chapter11_Expressions/Exercise1.py
329
3.921875
4
# Exercise 1 Chapter 11 Page 149 import re inp = input("Enter a regular expression: ") if len(inp) < 1: inp = '^From:' fhand = open("mbox.txt") count = 0 for line in fhand: line = line.strip() words = re.findall(inp,line) if len(words) > 0: count += 1 print("mbox.txt had",count,"lines that match...
c2b24f3f587202bdea4e6ec7895d06f70e9c3d04
celine5/GUVIrepo
/even.py
118
4.25
4
num=int(input("enter a number:")) if(num%2)==0: print("{0} is even".fomat(num)) else: print("{0} is odd".format(num))
802707f723581bda40c9d53b34d12858a58592d5
celine5/GUVIrepo
/vowelc.py
245
3.859375
4
original =input('Enter a character:') character= original.lower() first =character[0] if len(original) > 0 and original.isalpha(): if first in 'aeiou': print("Vowel") else: print("Consonant") else: print ("invalid")
1f36f982a91c6257911b91f1f5005d900fac104c
junbeomLim/Algorithm
/BOJ/backjoon 2750.py
129
3.59375
4
N = int(input()) n = [0 for i in range(N)] for i in range(N): n[i] = int(input()) n.sort() for i in range(N): print(n[i])
d21ea5dda881f239defc04d28018acc89ac99c86
ArpitaBawgi/Devops-Training
/third.py
274
3.984375
4
name='' condition=True while(condition): print('who are you') name=input() if(name!='joe'): continue else: print("Hello Joe, What is password?(it is fish)"); password=input(); if(password =='swoardfish'): #condition=False; break; print('Access Granted')
a632cf8c425a392504331ee4413aeb4727ea4318
wesyang/sudoku_solver
/misc/findIslands.py
1,606
3.625
4
class Solution(object): def printMap(self, map): for r in map: for c in r: print(f'{c} ', end='') print() print('-----------------') def checkAndMarkIsland(self, map, x, y, cc, rc): if x < 0 or y < 0: return if x >= cc or y >= rc: return ...
63155a1d3a461b958561d57c38adbea2c8be1e26
wesyang/sudoku_solver
/misc/getSqrt.py
1,394
3.65625
4
class Solution(object): @staticmethod def getSqrt(min, max, x): while (True): mid = int((max - min +1) / 2) + min mm = mid * mid #print (min, mid, max, mm, x) if mm == x: return mid elif mm < x: nextSqrt = (mid...
c76f613f2855a56d738d64439a2d857d1ca15781
jayashreemohan29/pmemkv-testing
/count_ops.py
882
3.640625
4
#!/usr/bin/env python import getopt import sys def main(): #input arg : file name if (len(sys.argv) != 2): print("Please input log file") exit(1) log_file = sys.argv[1] count = 0 count_fence = 0 count_flush = 0 count_store = 0 count_others = 0 operations = open(log_file).read().split("|") for op in ...
007064524296a592bf238f413029a41a12bafc0b
bharath144/PythonWorkshop
/sorting/bubble_sort.py
1,481
3.703125
4
import random import time input_a = [x for x in range(0, 1000)] input_b = random.sample(input_a, 10) input_c = input_b.copy() def iterative_sort(unsorted_list): print(unsorted_list) for i in range(0, len(unsorted_list)): # Improved exit condition, if there are no swaps, all numbers are sorted ...
3422c8df4de8e5e1bf18e154be725f7879f797c5
MaxMcCarthy/Recommender-System
/Scraper/web_scraper.py
6,479
3.71875
4
from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup import csv # with help from: # https://realpython.com/python-web-scraping-practical-introduction/ def simple_get(url): """ Attempts to get the content at `url` by making an ...
b2e057bd9d63ba6da9a755f2c879bc58ae65086b
tomcat1969/CodingDojo_python_stack
/python/fundamentals/forloopbasic2.py
1,654
3.953125
4
# def biggie_size(list): # for i in range(len(list)): # if list[i] > 0: # list[i] = "big" # return list # print(biggie_size([-1,3,5,-5])) # def count_positives(list): # count = 0 # for i in range(len(list)): # if list[i] > 0: # count = count + 1 # list[len(list)-1] = count # return list # print...
d593ffafc59015480c713c213b59f6304914d660
Ayush10/python-programs
/vowel_or_consonant.py
1,451
4.40625
4
# Program to check if the given alphabet is vowel or consonant # Taking user input alphabet = input("Enter any alphabet: ") # Function to check if the given alphabet is vowel or consonant def check_alphabets(letter): lower_case_letter = letter.lower() if lower_case_letter == 'a' or lower_case_letter == 'e' or...
2676477d211e0702d1c44802f9295e8457df21a8
Ayush10/python-programs
/greatest_of_three_numbers.py
492
4.3125
4
# Program to find greatest among three numbers # Taking user input a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) c = int(input("Enter third number: ")) # Comparison Algorithm and displaying result if a > b > c: print("%d is the greatest number among %d, %d and %d." % (a, a, b, c)) ...
172102809e9f1fc0ebf8516b78f7dab417f05e5e
ecarlos09/procedural-python-exercises
/name_generator/penguin_name.py
423
3.5
4
penguin_converter = { "January": "Mumble", "February": "Squeak", "March": "Skipper", "April": "Gloria", "May": "Kowalski", "June": "Rico", "July": "Private", "August": "King", "September": "Pingu", "October": "Feathers McGraw", "November": "Chocolatey", "December": "Ice C...
82b3b3358fc08521b6e714a7d1b5cf2c40aee47c
MiriSilva/Avaliacao1
/Questao2.py
354
4.09375
4
n1 = int(input("informe um numero inteiro: ")) n2 = int(input("informe um numero inteiro: ")) n3 = float(input("informe um numero real: ")) print ("o produto do dobro do primeiro com metade do segundo è :", n1*2*(n2/2)) print ("a soma do triplo do primeiro com o terceiro é:", (n1*3)+n3 ) print ("o terceiro...
a42ff81b035de48e6628dbac29315ae1e2e78bb1
MiriSilva/Avaliacao1
/Questao4.py
363
3.828125
4
x = float(input("Informe quanto ganha por hora:")) y = float(input("Informe quantas horas trabalhadas no mês:")) SB = (x*y) IR = SB * 0.11 INSS = SB* 0.08 SD = SB*0.05 SL = SB-(IR+INSS+SD) print("Salário Bruto : R$",SB) print("IR (11%) : R$",IR ) print("INSS (8%) : R$",INSS ) print("Sindicato ( 5%) : R$"...
3fefcd97afaccac58e7c18e5303c44d2c11699a0
hendy3/A-beautiful-code-in-Python
/Teil_15_Sudoku_Algorithm_x.py
2,701
3.8125
4
#!/usr/bin/env python3 # Author: Ali Assaf <ali.assaf.mail@gmail.com> # Copyright: (C) 2010 Ali Assaf # License: GNU General Public License <http://www.gnu.org/licenses/> from itertools import product import time def solve_sudoku(size, grid): """ An efficient Sudoku solver using Algorithm X. """ R, C = size ...
e50f8e37210054df2e5c54eb55e7dee381a91aff
super468/leetcode
/python/src/BestMeetingPoint.py
1,219
4.15625
4
class Solution: def minTotalDistance(self, grid): """ the point is that median can minimize the total distance of different points. the math explanation is https://leetcode.com/problems/best-meeting-point/discuss/74217/The-theory-behind-(why-the-median-works) the more human language ...
71c87f644ac21e84586fa2fcb51e9c160151c6a7
super468/leetcode
/python/src/FlipGameII.py
749
3.734375
4
""" the basic idea is that track every movement of the first player, if the other player can not make a movement, then movement the first player made is a winning movement. the optimization is to use memorization to memorize the string state that we have seen. this is a backtracking problem with memorization optimizati...
3228d9c857bd5e39ca56b0d8d5f4f43b8c8f8d5c
scotchka/scotchka.github.io
/2018/06/16/balance_brackets.py
821
3.578125
4
import inspect BRACKETS = {")": "(", "]": "[", "}": "{"} def _stack(chars): """Push/pop frames to/from call stack.""" while chars: char = chars.pop(0) if char in BRACKETS.values(): _stack(chars) # push elif char in BRACKETS: previous = inspect.stack()[1] ...
cdccb6138c604da36be9d9b97d65e0270bc57cb8
monicadsong/matrix_factorization_mp
/test_multiprocessing.py
3,289
3.5625
4
import multiprocessing from multiprocessing import pool print("cpu count: ", multiprocessing.pool.cpu_count()) import os, time # g_cnt is not shared with each worker def test_process_with_global_variable(): g_cnt = 4 def worker(idx, data, g_cnt): global g_cnt g_cnt += 1 time.sleep(1) print("wo...
a5333df631bfbbc3f2ab5e6f8631eb7cb17611f1
PanchoF1/56107-Francisco-Saldana
/Clase05 Calculadora/calculadora_test.py
1,052
3.546875
4
import unittest from clases import Calculator class TestCalculador(unittest.TestCase): def resul_calculator_1_add_1_(self): calc = Calculator() calc.ingresar('1') calc.ingresar('+') calc.ingresar('1') calc.ingresar('=') self.assertEqual(calc.display(),'2') ...
3da888a1d429023b69d7e4efd7e4f7d6909e3f75
afterthought325/cp_lab
/atm_machine-0.5.py
3,095
3.84375
4
################################################################################ # Name: Chaise Farrar Date Assigned:10/16/2014 # # Partner: Rebecca Siciliano # # Course: CSE 1284 Sec 10 Date Due: 10/16/2014 ...
977125662ad8ba83bbe8cedc6bce54ab9836d207
kunxin-chor/tgc-python
/select-example/main.py
343
3.515625
4
import pymysql connection = pymysql.connect(host='localhost', user="admin", password="password", database="Chinook" ) cursor = connection.cursor() cursor.execute("SELECT * from Employee") for r in cursor: # print (r) # We have to refer each field by its index print ("Name: " + r[1] + " " + r[2...
8b46f6ce79908a511e258e2af636e398387f0474
accimeesterlin/scrape_linkedin
/filter_contact.py
2,087
3.59375
4
import json from pprint import pprint data = json.load(open("contacts.json")) def set_max(arr, limit): for index, contact in enumerate(arr): if index <= int(limit) - 1: print("_______________________________________") print("_______________________________________") pr...
5e6544c168eba12bfd9cc44e1734ec5dd5691dac
ajaycode/study
/class05/math/tests/test_temperature.py
827
3.5
4
# ..\tests>python test_fraction.py import unittest from unittest import TestCase __author__ = 'Ajay' import sys sys.path.append('..\\') from temperature import * class TestTemperature(TestCase): def test_celsius_from_fahrenheit(self): question, answer = celsius_from_fahrenheit (60) self.assertE...
d60032107ecb73851a9abeb29cc1f5dedcf0b111
nicolassnider/udemy_machine_learning_r_python
/testProject/seccion08/tuplas.py
268
3.78125
4
p1=(1,) p2=(1,2,3,4) p3=(1,2,'e',3.1415) print(p1) print(p2) print(p3) print(p3[0:2]) a,b,c,d=p3 print(a) print(c) # L4 = list(p3) print(L4) p5=tuple(L4) print(p5) # L=tuple(input('Escribe numeros separados por comas: \n').split(',')) for n in L: print(2*int(n))
10c930abce072e05a3e4b1f1608f918c3b7c5afe
vinaybommana/twitter-analytics
/step_4/influentials_users.py
1,671
3.625
4
import csv import codecs import math def read_csv(filename): rows = list() with open(str(filename), "r") as c: csvreader = csv.reader(c) next(csvreader) for row in csvreader: rows.append(row) return rows def main(): second_rows = read_csv("step_two_output.csv") ...
819cdf9e9e096ce54c22847b91c165171bba45be
Ruslan-Skira/PythonHW1
/listModification.py
4,631
4.375
4
"""Первая версия функции извлекает первый аргумент (args – это кортеж) и обходит остальную часть коллекции, отсекая первый элемент (нет никакого смысла сравнивать объект сам с собой, особенно если это довольно крупная структура данных).""" def min1(*args): current = args[0] for i in args[1:]: # all but the fir...
69c903b677e32ce1de2e292ef315f68c05361452
Ruslan-Skira/PythonHW1
/OOP/test_resource.py
349
3.703125
4
import unittest from math import pi import resource class TestCircleArea(unittest.TestCase): def test_area(self): # Test areas when radius > = 0 self.assertAlmostEqual(resource.circle_area(1), pi) self.assertAlmostEqual(resource.circle_area(55), 1) self.assertAlmostEqual(resource.c...
f40434748d69a754a43d733df64129d39bc12e48
kevinmartinjos/mapleblow
/game.py
2,270
3.640625
4
import pygame from world import Hurdle from vector2 import Vector2 from pygame.locals import * from sys import exit from leaf import Leaf from wind import Wind import wx start=False def run_game(run_is_pressed): pygame.init() clock=pygame.time.Clock() screen=pygame.display.set_mode((640,480)) picture='leaf.png' bl...
5234c1163f18bfd1e095b287f5a75ec97a37a898
tfmorris/wrangler
/runtime/python/wrangler/sort.py
1,806
3.5
4
from transform import Transform def mergesort(list, comparison): if len(list) < 2: return list else: middle = len(list) / 2 left = mergesort(list[:middle], comparison) right = mergesort(list[middle:], comparison) return merge(left, right, comparison) def merge(left, r...
72cdf859ab9d5adcbddf25295b4da9dea6015c90
EdwardTFS/TensorflowExamples
/example1.py
999
3.84375
4
#based on https://developers.google.com/codelabs/tensorflow-1-helloworld #fitting a linear function import sys print("Python version:",sys.version) import tensorflow as tf import numpy as np print("TensorFlow version:", tf.__version__) from tensorflow import keras #create model model = keras.Sequential([keras.laye...
5d0b56e2c02f10090b62c259d5b7782c144eb840
prajwolshakya/visualization-sorting-algorithms
/shell_sort.py
762
3.859375
4
from cube import Run def shell_sort(): run = Run() arr = run.display() sublistcount = len(arr) // 2 while sublistcount > 0: for start in range(sublistcount): gap_insertion_sort(arr,start,sublistcount,run) #print(sublistcount) #print(arr) sublistcount = sublistcount // 2 return arr def gap_insertio...
42167b22a0b27f5172f2c432979a397201cffde4
2508Fernan/Taller-3
/FernandaUshcasina_EstrellaPar_Turtle.py
507
3.921875
4
from turtle import* import time import turtle t= turtle.Pen() ##tamaño de la ventana turtle.setup (500,600) ##establecer el objeto en pantalla wn= turtle.Screen() ##color de la pantalla wn.bgcolor("pink") ##titulo de la pantalla wn.title("Estrella de Puntas Pares") a=int(input("ingrese un numero par:")) pr...
045cc9ae2292052a918ccca9ab13c76b442ea0bc
SamSweere/MRS
/gui/localization_path.py
2,861
3.578125
4
import pygame import math # Draws a dashed curve # Works by using the fraction variable to keep track of the dash strokes # fraction from 0 to 1 means dash # fraction from 1 to 2 means no dash def draw_dashed_curve(surf, color, start, end, fraction, dash_length=10): start = pygame.Vector2(start) end = pygame.V...
4934d8f72ee6a0b00a6350c29e00f9994ef862ed
marccathomen/troccas
/app/card.py
516
3.5625
4
class Card: def __init__(self, id, power, value, suit, label): self.id = id # unique identification number self.power = power # beating power # value of the card in points self.value = value # suit of the card [r osa,s pada,c uppa,b astun,t rocca,n arr] self.suit = ...
1e37be68e28933fc50eb1eff40c74f6fb2d08da0
Krikiba/ATM
/fonction_atm.py
466
3.515625
4
def withdraw(request): i=0 liste=[100,50,10,5,4,3,2,1] for lis in liste: if request>=lis : request-=lis return request else : i+=1 def atm(money,request): balence=request print "Current balance =" +str(money) while request>0: if request>money : print ("le montant n'existe pas en ATM"...
3aeec4d5aae9f02d788af92f97af7e1ad5453940
mhurtad14/1500-intergration
/intergration project version 2.py
6,185
4
4
#Mijail Hurtado #Integration Project #COP 1500 #Professor Vanselow import math def get_bmr(): gender = input("What is your gender: M or F?") age = int(input("What is your age?")) height = int(input("What is your height in inches?")) weight = (int(input("What is your weight in pounds?"))) ...
aec194198be1a68b82f0fa306aff480d9e4fc396
rbusquet/advent-of-code
/aoc_2021/day11.py
1,880
3.53125
4
from itertools import count, product from pathlib import Path from typing import Iterator Point = tuple[int, int] def neighborhood(point: Point) -> Iterator[Point]: x, y = point for i, j in product([-1, 0, 1], repeat=2): if i == j == 0: continue yield x + i, y + j def flash(poin...
c1232f17b340a952c18208ffe66c59ad3e5b9243
rbusquet/advent-of-code
/aoc_2015/day1.py
622
3.640625
4
from pathlib import Path def part_1() -> int: with open(Path(__file__).parent / "input.txt") as file: floor = 0 while step := file.read(1): floor += step == "(" or -1 return floor def part_2() -> int: with open(Path(__file__).parent / "input.txt") as file: floor =...
48a7d98ef8acfdd3fc5c7ace832810e2fe3c6092
rbusquet/advent-of-code
/aoc_2020/day3.py
771
3.65625
4
from functools import reduce from itertools import count from operator import mul from typing import Iterator def read_file() -> Iterator[str]: with open("./input.txt") as f: yield from f.readlines() def count_trees(right: int, down: int) -> int: counter = count(step=right) total_trees = 0 f...
9abc4c7c745318043728354a75b0e6cc58e532e7
rbusquet/advent-of-code
/aoc_2020/day24.py
2,339
3.78125
4
from collections import defaultdict from dataclasses import dataclass @dataclass class Cube: x: int y: int z: int def __add__(self, cube: "Cube") -> "Cube": return Cube(self.x + cube.x, self.y + cube.y, self.z + cube.z) @classmethod def new(cls) -> "Cube": return Cube(0, 0, 0...
bedc3696e18c0810fffc6e0095d884de1c42b970
rbusquet/advent-of-code
/aoc_2020/day17.py
1,673
3.578125
4
from collections import defaultdict from itertools import product initial = """ ####.#.. .......# #..##### .....##. ##...### #..#.#.# .##...#. #...##.. """.strip() def neighborhood(*position: int): for diff in product([-1, 0, 1], repeat=len(position)): neighbor = tuple(pos + diff[i] for i, pos in enumera...
dbcf6b5acffdf9a54c1a18efc214dcaed6bae1c7
HanniSYC/Practice_code
/二维数组中的查找练习.py
1,405
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/11/3 下午9:38 # @Author : Hanni # @Fun : 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。 # 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 print '欢迎来到二维数组中的查找v1.0 @星辰\n' class Solution: def Find(self, target, array): rowcount = len(array)...
98144aeef549d072b82e1ec8b6fe04b231c4016d
rollingonroad/Python005-01
/week06/assignment.py
1,777
3.984375
4
from abc import ABCMeta, abstractmethod # 动物 class Animal(metaclass=ABCMeta): def __init__(self, food_type, body_size, character): self.food_type = food_type self.body_size = body_size self.character = character @property def is_fierce(self): return self.body_size != '小' ...
fc9366b9c351ebcc8ee1408a82cbb2a051785b40
schardt8237/Codecademy
/Data Science Career Path/Unit 14: Learn Statistics With Python/life_expectancy_by_country.py
840
3.75
4
import codecademylib3_seaborn import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv("country_data.csv") #print(data.head()) life_expectancy = data["Life Expectancy"] life_expectancy_quartiles = np.quantile(life_expectancy, [0.25, 0.5, 0.75]) print(life_expectancy_quartiles)...
e1ecce71b4e466e4028e2528e627a61486137ee5
IzMasters/timefuzz
/timefuzz.py
3,720
3.546875
4
class Namespace: def __init__(self, **names): for name in names.keys(): setattr(self, name, names[name]) # helper class for "speaking" units.. # singular and plural are the respective forms, plural defaults to a regular "s"-plural # vowel_onset determines whether or not to use "an" for the indefinite article cla...
7c7e46570e38bc54ba1c1fabd9c11de78f8f27b9
CharlieGodfrey1/Python-practice
/divisors practice.py
409
4
4
#user enters number num=int(input("Please enter a number: ")) #works out the intigers from 1 to the entered number listrange = list(range(1,num+1)) #list of divisors divisors = [] #for loop to work out divisors for i in listrange: #divides the entered number by the list range integers and if they have a modula...
cb69532884a199d684d49739f1bc17e3076600a8
calcsam/toyprojects
/socialwire_example.py
3,142
3.65625
4
# in response to http://www.socialwire.com/exercise1.html; took me about 2 hours to code # python 2.7 def test(aString): stillNumber = True expectedExpressions = 0 allExp = [] currentExp = [] for char in aString: #print "iterate" + char if is_number(char) and stillNumber: expectedExpressions = expectedExp...
63825db8fd9cd5e9e6aaa551ef7bfec29713a925
Rohit439/pythonLab-file
/lab 9 .py
1,686
4.28125
4
#!/usr/bin/env python # coding: utf-8 # ### q1 # In[2]: class Triangle: def _init_(self): self.a=0 self.b=0 self.c=0 def create_triangle(self): self.a=int(input("enter the first side")) self.b=int(input("enter the second side")) self.c=int(input("e...
100419d5cdb569188d4c1231a7e603bc6c16353b
racheltsitomeneas/python_homework
/Python Homework/PyBank/Analysis/PyBank.py
1,915
3.84375
4
#pybank homework import os import csv #variables months = [] profit_loss_changes = [] count_months = 0 net_profit_loss = 0 previous_month_profit_loss = 0 current_month_profit_loss = 0 profit_loss_change = 0 os.chdir(os.path.dirname(__file__)) budget_data_csv_path = os.path.join("budget_data.csv") ...
b3717109102391a9eed15d86869e05c0866d6c29
MusawerAli/python_practise
/nesteddict.py
512
3.84375
4
#nested dictionary parent_child = { "child1": { "name": "jorg", "age": 22 }, "child": { "name": "bush", "age": 30 } } parent_brother = { "brother1": { "name": "jonze", "age": 43 }, "brother2": { "name": "bus", "age": 65 ...
34c328e731795ee17c1e887a966c33a6bf2ca327
MusawerAli/python_practise
/regex/regex.py
125
3.890625
4
import re txt = "The rain in Spain" x = re.search("^The.*Spain$", txt) print("Have a match") if (x) else print("no match")
644dd04680b280b1def7e3d5023e2dfa0a253161
MusawerAli/python_practise
/regex/endwithword.py
182
4.59375
5
import re str = "hello world" #Check if the string ends with 'world': x = re.findall("world$", str) if (x): print("Yes, the string ends with 'world'") else: print("No match")
ea81873f62f22fb784403d68c7c443a4b3749a40
MusawerAli/python_practise
/if_else.py
501
3.890625
4
a = 50 b =20 c = 54 d=50 if b > a: print("b is greater than b") elif c>a: print("c is grater than a") else: print("a is grater than b") #Short Hand if...Else print("A") if a > b else print("B") #print Multiple print("A") if a< d else print("=") if a == d else print("B") if a>b and d>b: print("Bo...
80656a2831924d203537b5788143bf03e149dd7d
lalitasharma04/Computer_Networks
/source codes/Bit_Stuffing_and_character_stuffing.py
4,154
3.984375
4
''' ============================================================================== Name :Lalita Sharma RNo :06 =============================================================================== Experiment :02 *************** Aim:W...
63e1f1008273f5dcd65fd12e22b47886a6be3bec
lautaroGonzalez97/practica2
/ejercicio3.py
262
3.796875
4
texto="Tres tristes tigres, tragaban trigo en un trigal, en tres tristes trastos, tragaban trigo tres tristes tigres." letra = input("ingrese una letra") lista= texto.lower().replace(",","").split() for ele in lista: if ele[0] == letra: print(ele)
332b831f3602141a6dac113e04bf7caee197b9ce
bartkim0426/algorithm-study
/questions/leetcode_199.py
7,815
4.03125
4
# https://leetcode.com/problems/binary-tree-right-side-view/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right ''' TreeNode{ val:1, left: TreeNode{ val: 2...
6cca9c50b24c23b7b0f45721b84cb06646185442
brpasiliao/Girls_Who_Code_Projects
/commute.py
1,814
3.953125
4
qhome = "walk or drive: " qwalk = "bus or lirr: " qlirr = "subway or speedwalk: " qdrive1 = "lirr or drive: " qdrive2 = "bridge or tunnel: " # def plurality() # if plural == True: # word += "s" # else: # None def end(time, money): hours = time // 60 minutes = time - hours * 60 if ...