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
00b062fe411ebec0630d2e6283cc2adbc30253e2
sunjiyun26/pythonstep
/collectionSunjy/MyIterators.py
292
3.53125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'sunjiyun' import itertools natural = itertools.count(1) for n in natural: # print n pass nchar = itertools.cycle("abc") for n in nchar: # print n pass nrepeat = itertools.repeat("a",10) for n in nrepeat: print n
e4b174e4142dba7c0d1e88fd16f457a6399684d0
HHOSSAIN/COMP10001
/Toy_world/Shortest_path.py
4,152
4.03125
4
import math def shortest_path(data, start, end, has_sword): # TODO implement this function. # node = start(initially), symbols:'W'=dragon, 't'=sword unexplored = [start] # my queue explored = set() steps = 0 rows = data["size"] columns = data["size"] if unexplored == []: return None if start == end: return steps while unexplored: new_coordinates=[] for i in unexplored: explored.add(i) # probable next moves from a point a = i[0] + 1 # a=dx, (south), (row change) b = i[0] - 1 # b=dx, (north), (row change) c = i[1] + 1 # c=dy, (east), (column change) d = i[1] - 1 # d=dy, (west), (column change) coordinates = [(i[0], c), (i[0], d), (a, i[1]), (b, i[1])] ''' if 't' taken, path is same to path in absence of 'W', i.e. the path is unaffected by presence or absence of 'W' if carrying 't'('t' = sword, 'W' = dragon). ''' if 'dragon' not in data or has_sword: for j in coordinates: if (j[0]>=0 and j[1]>=0 and j[0]< rows and j[1] < columns): if 'walls' in data and j not in data['walls']: if j not in unexplored and j not in explored: if j not in new_coordinates: new_coordinates.append(j) elif 'walls' not in data: if j not in unexplored and j not in explored: if j not in new_coordinates: new_coordinates.append(j) if 'dragon' in data: if not has_sword: # not carrying a sword # ensuring move is inside cave for j in coordinates: # j=next move if (j[0] >= 0 and j[1]>=0 and j[0]<rows and j[1]< columns): if j not in new_coordinates: new_coordinates.append(j) distance = (math.sqrt((j[0] - data['dragon'][0])** 2 +(j[1] - data['dragon'][1]) ** 2)) # ensuring move not in 8 adjacent blocks to 'W' if distance in (1, math.sqrt(2)): new_coordinates.remove(j) # ensuring moves aren't repeated or in wall positions for k in new_coordinates: if 'walls' in data and k not in data['walls'] \ and k not in unexplored and k not in explored: True elif 'walls' not in data: if k not in unexplored and k not in explored: True else: new_coordinates.remove(k) for l in new_coordinates: if l in explored or l in unexplored: if 'walls' in data and l in data['walls']: new_coordinates.remove(l) elif 'walls' not in data: if l in explored or l in unexplored: new_coordinates.remove(l) # changing queue to its child nodes after iteration of 1 level done unexplored = new_coordinates if unexplored == []: return None if end not in unexplored: steps += 1 else: steps += 1 return steps
c13da31deb04f6148a1e8aebb6ac842b23a291e7
unorthodox-character/Desktop_repo
/everything_python/python_practice/continue.py
164
4.03125
4
'''program demonstrating continue statement ''' list1 = ['tomato', 'potato', 'onion', 'biscuits'] for i in list1: if i == 'onion': continue print(i)
d48f7fe7caa442087dd7bbcda1fcd03364e211ce
etopiacn/PyProject
/Day1/chinese_zodiac_v2.py
972
3.6875
4
#序列:字符串、列表、元组 # 根据年份判断生肖 chinese_zodiac = '猴鸡狗猪鼠牛虎兔龙蛇马羊' #取余不是从鼠开始的,偷懒做法 #year = int(input('请用户输入出生年份:')) #print(year%12) #print(chinese_zodiac[year%12]) #if (chinese_zodiac[year%12]) == '狗': # print('狗年运势如何?') # for cz in chinese_zodiac: # print(cz) # # for i in range(13): # print(i) # # for year in range(2000,2019): # print('%s年的生肖是%s' %(year,chinese_zodiac[year%12])) # num = 5 # while True: # print('a') # num = num + 1 # if num == 10: # break # import time # num = 5 # while True: # num = num + 1 # if num == 10: # continue # print(num) # time.sleep(1) #print(list(chinese_zodiac)) #print(chinese_zodiac[0]) #print(chinese_zodiac[0:4]) #print(chinese_zodiac[-1]) # print('狗' not in chinese_zodiac) # # print(chinese_zodiac + 'abcd') # # print(chinese_zodiac * 3)
541dcd66126791a784c2265ce35c1800e277f301
aludkiewicz/comparativefunc
/python_examples/TailRecursion.py
228
3.734375
4
## Tail recursion in Python. Tail call optimization is not implemented though! def call_1000_times(count): if count == 1000: return True else: return call_1000_times(count + 1) call_1000_times(10000)
556032950c50dec1881145df8da4ccef3de2ceb5
David-boo/Rosalind
/Rosalind_GC.py
923
3.515625
4
# Code on Python 3.7.4 # Working @ Dec, 2020 # david-boo.github.io # In this code I'll use SeqIO, the standard sequence input/output interface for BioPython. You can find more information about BioPython on david-boo.github.io, be sure to check it out. # Using Bio.SeqUtils package aswell, which contains a G+C content function that really simplifies this problem. # Importing both of them from Bio import SeqIO from Bio.SeqUtils import GC # Opening the DNA strings, creating a GCcont and a GCsequence variable to print result later. GCcont=0 GCseq="" file=open("rosalind_GC.txt", "r") # Small loop that checks the GC content of every sequence and stores the highest value + seq id. for record in SeqIO.parse(file, "fasta"): if GCcont < GC(record.seq): GCcont = GC(record.seq) GCseq = record.id # Printing answer on % print(GCseq,round(GCcont,2),"%")
53181c9a84603d0180042085c01f488eef574d07
ralinc/learning-python
/plural.py
969
3.546875
4
import re def build_match_and_apply_functions(pattern, search, replace): def matches_rule(word): return re.search(pattern, word) def apply_rule(word): return re.sub(search, replace, word) return (matches_rule, apply_rule) patterns = \ ( ('[sxz]$', '$', 'es'), ('[^aeioudgkprt]h$', '$', 'es'), ('(qu|[^aeiou])y$', 'y$', 'ies'), ('$', '$', 's') ) rules = [ build_match_and_apply_functions(pattern, search, replace) for (pattern, search, replace) in patterns ] def plural(noun): for matches_rule, apply_rule in rules: if matches_rule(noun): return apply_rule(noun) if __name__ == '__main__': print(plural('dog')) print(plural('cat')) print(plural('coach')) print(plural('rash')) print(plural('bass')) print(plural('fax')) print(plural('vacancy')) print(plural('day')) print(plural('knife')) print(plural('house'))
45383257608d2cbeb76cffff05ec0e909a7e145a
ArturoBarrios9000/CYPEnriqueBC
/libro/problemas_resueltos/capitulo1/problema1_8.py
229
3.765625
4
X1=float(input("Ingrese X1:")) Y1=float(input("Ingrese Y1:")) X2=float(input("Ingrese X2:")) Y2=float(input("Ingrese Y2:")) D=((X1-X2)**2+(Y1-Y2)**2)**0.5 print(f"La distancia entre los puntos ({X1},{Y1}) y ({X2},{Y2}) es: {D}")
4a5d6a229b82007877b6f0225115c3fdf7f4f8a7
ArturoBarrios9000/CYPEnriqueBC
/libro/ejemplo3_2.py
164
3.828125
4
NOMINA=0 for i in range (1,11,1): SUE=float(input("Ingrese el sueldo:")) NOMINA += SUE # NOMINA = NOMINA + SUE print("La nomina de la empresa es:", NOMINA)
e6229545b1936b0d9c9b542508bd30847c83d1f4
ArturoBarrios9000/CYPEnriqueBC
/libro/ejemplo2_8.py
317
3.78125
4
CAT=int(input("Introdusca la categoria del trabajador (1-4):")) SUE=float(input("Introdusca el sueldo del trabajador:")) NSUE=0 if CAT ==1: NSUE=SUE*1.15 elif CAT==2: NSUE=SUE*1.10 elif CAT==3: NSUE=SUE*1.08 elif CAT==4: NSUE=SUE*1.07 print(f"El sueldo con categoria {CAT} con el aumento es: {NSUE}")
75e2df6d2e22a1c80dbb30403f8e48665c271b8d
ArturoBarrios9000/CYPEnriqueBC
/libro/problemas_resueltos/Capitulo2/Problema2_6.py
201
4.03125
4
A=int(input("Ingrese un numero entero para A:")) if A==0: print(f"El numero es nulo {A}") elif (-1**A)>0: print(f"El numero {A} es par") else: print(f"El numero {A} es impar") print("Fin")
a0641334cc478b267c205e47b475129a8e42fcaa
tanuj87/Deep_Learning
/Tensorflow_basic_using_Keras.py
5,352
3.53125
4
# coding: utf-8 # # TensorFlow basics # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # In[2]: df = pd.read_csv('TensorFlow_FILES/DATA/fake_reg.csv') # In[3]: df.head() # In[4]: # very simple dataset # we will treat it as a regression problem, feature 1, feature 2 and price to predict # In[5]: # supervised learning model # In[6]: sns.pairplot(df) # In[7]: plt.show() # In[8]: # feature 2 is veru corelated with price # In[9]: from sklearn.model_selection import train_test_split # In[10]: X = df[['feature1', 'feature2']].values # we will have to pass "Numpy arrays" instead of "Pandas arrays or series" # adding .values to the dataframe returns a numpy array # In[11]: y = df['price'].values # In[12]: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state = 42) # In[13]: X_train.shape # In[14]: X_test.shape # In[14]: # normalize or scale your data # In[15]: # if we have really large values it could cause an error with weights # In[15]: from sklearn.preprocessing import MinMaxScaler # In[17]: help(MinMaxScaler) # In[16]: scaler = MinMaxScaler() # In[17]: scaler.fit(X_train) #calculates the parameter it needs to perform the actual scaling later on # standard deviation, min amd max # In[18]: X_train = scaler.transform(X_train) # this actually performs the transformation # In[21]: # we ran 'fit' only on train set because we want to prevent 'Data leakage' from the test set, # we dont want to assume that we have prior information fo the test set # so we only try to fit our scalar tot he training set, and donot try to look into the test set # In[19]: X_test = scaler.transform(X_test) # In[20]: X_train # In[21]: X_train.max() # In[22]: X_train.min() # In[26]: # it has been scaled now # In[27]: # time to create our neural network # In[23]: from tensorflow.keras.models import Sequential # In[24]: from tensorflow.keras.layers import Dense # In[25]: #help(Sequential) # In[26]: # there is 2 ways to making a Keras based model # In[36]: # 1 way to do this is: model = Sequential([Dense(4, activation='relu'), # Layer 1, 4 neurons, activation function = Relu Dense(2, activation='relu'), # Layer 2, 2 neurons, activation function = Relu Dense(1)]) # output layer # In[38]: # other way to do this is: model = Sequential() # empty sequential model model.add(Dense(4, activation='relu')) model.add(Dense(2, activation='relu')) model.add(Dense(1)) # easier to turn off a layer in this # In[27]: model = Sequential() # empty sequential model model.add(Dense(4, activation='relu')) model.add(Dense(4, activation='relu')) model.add(Dense(4, activation='relu')) model.add(Dense(1)) model.compile(optimizer='rmsprop', loss='mse') # In[28]: model.fit(x=X_train,y=y_train,epochs=250) # In[29]: loss_df = pd.DataFrame(model.history.history) # In[30]: loss_df.plot() plt.show() # In[31]: # how well this model peroforms on test data # In[33]: # It outputs the model's Loss model.evaluate(X_test, y_test, verbose=0) # In[34]: # in our case the loss metric ins MSE # so MSE is 25.11 # In[35]: model.evaluate(X_train, y_train, verbose=0) # In[36]: test_predictions = model.predict(X_test) # In[37]: test_predictions # In[38]: test_predictions = pd.Series(test_predictions.reshape(300,)) # In[39]: test_predictions # In[43]: pred_df = pd.DataFrame(y_test, columns=['Test True Y']) # In[44]: pred_df # In[45]: pred_df = pd.concat([pred_df, test_predictions], axis=1) # In[47]: pred_df.columns = ['Test True Y', 'Model Predictions'] # In[48]: pred_df # In[54]: sns.lmplot(x = 'Test True Y', y = 'Model Predictions', data = pred_df, scatter=True, fit_reg=False) plt.show() # In[55]: # to grab different error metrics # In[56]: from sklearn.metrics import mean_absolute_error, mean_squared_error # In[57]: mean_absolute_error(pred_df['Test True Y'], pred_df['Model Predictions']) # In[58]: # how do i know if it is good or bad? # that depends on training data # In[59]: df.describe() # In[60]: # here mean price is 498 $ and our mean absolute error is 1.01 which is roughly 1%, so this error is pretty good # In[61]: mean_squared_error(pred_df['Test True Y'], pred_df['Model Predictions']) # In[62]: # this is exactly same as : # model.evaluate(X_test, y_test, verbose=0) # In[63]: # RMSE mean_squared_error(pred_df['Test True Y'], pred_df['Model Predictions'])**0.5 # In[64]: # predicting on brand new data # i pick this gemstone from the ground new_gem = [[998, 1000]] # In[65]: # first thing is, our model is trained on 'scaled features' # so we first need to scale this new data as per our scaler # In[68]: new_gem = scaler.transform(new_gem) # In[69]: model.predict(new_gem) # In[70]: # we should price it at 420 $ # In[71]: # IF your are running a very complex model that took a lot of time to train # yout would want to make sure you save that model from tensorflow.keras.models import load_model # In[72]: model.save('my_gem_model.h5') # In[73]: # now I can use the load model command # In[75]: later_model = load_model('my_gem_model.h5') # In[76]: later_model.predict(new_gem) # In[ ]: # works as well!!!
1d80ed6d34f0034acdf6268151663be23a105f64
devanshmanu/tetris
/a1.py
492
3.671875
4
BRICK = "o" CHK = "x" SPACE = " " NEWLINE = "\n" LEVEL = 1 GV=0 L=1 R="r" var_fill=0 total=0 def percentage(numerator, denominator): temp1 = float(numerator)*100 temp2 = float(denominator) fin = temp1/temp2 fin2 = math.ceil(fin*100) return fin2/100 def brickfunction(jk): matrixvar = 50 if jk < 0: matrixvar +=1 elif jk == 0: matrixvar +=0 else: matrixvar -=1 matrixvar = 1 answer = jk * matrixvar return answer
d3eb57ca3377dcb7462afd86e43997a1f220e940
shivanshutyagi/python-works
/primeFactors.py
566
4.3125
4
def printPrimeFactors(num): ''' prints primeFactors of num :argument: number whose prime factors need to be printed :return: ''' for i in range(2, num+1): if isPrime(i) and num%i==0: print(i) def isPrime(num): ''' Checks if num is prime or not :param num: :return: true if num is prime, else false ''' for i in range(2, int(num/2)+1): if num % i == 0: return False return True if __name__ == "__main__": n = int(input('Enter the number: ')) printPrimeFactors(n)
5070036543d29c4130456e7ded0ae21f694c7849
tsh/edx_algs201x_data_structures_fundamentals
/1-1_check_brackets_in_the_code.py
968
4.03125
4
from collections import namedtuple Bracket = namedtuple("Bracket", ["char", "position"]) def are_matching(left, right): return (left + right) in ["()", "[]", "{}"] def find_mismatch(text): stack = [] for i, char in enumerate(text, start=1): if char in "([{": stack.append((char, i)) if char in ")]}": if len(stack) == 0: return i top = stack.pop()[0] if (char == ')' and top != '(') or\ (char == ']' and top != '[') or\ (char == '}' and top != '{'): return i return stack.pop()[1] if len(stack) > 0 else 'Success' def main(): text = input() mismatch = find_mismatch(text) # Printing answer, write your code here if __name__ == "__main__": print(find_mismatch('[]')) # Success print(find_mismatch('{}[]')) # Success print(find_mismatch('{[}')) # 3 print(find_mismatch('[](()')) # 3
319e1c14b1b90d04c1202466eaf6a397a952e7c3
roberg11/is-206-2013
/ex45-workingGame/ex45scenes.py
9,959
3.828125
4
class Scene(object): # Empty dictionaries of hints and dialogs hints = {} dialogs = {} def enter(self, game): print "This scene is not yet configured. Subclass it and implement enter()." exit(1) # Action handling def actions(self, actions): actionText = { 'goto': 'Go to', 'talkto': 'Talk to', 'examine': 'Examine', } actionKeys = {} # Loop that always runs (always is True) while(True): # Prints the current room name print "-------------------------------" print self.__class__.__name__ print "-------------------------------" actionIndex = 0 # Iterate over player actions and compares user input with possible actions in actionKeys dict for action in actions: actionIndex+=1 actionKeys[action] = actionIndex print "[%s]: %s" % (actionIndex, actionText[action]) playerAction = raw_input("> ") # Read action input and calls the definition equal to input in actionText[action] dictionary # Calls the goto function if user input does not equal any elements to actionText[action] if('goto' in actions): if(playerAction == str(actionKeys['goto'])): goto = self.goto(self.__class__.__name__.lower()) if(goto != False): return goto if('talkto' in actions): if(playerAction == str(actionKeys['talkto'])): self.talkto() if('examine' in actions): if(playerAction == str(actionKeys['examine'])): self.examine() # Go to handling def goto(self, currentSceneName): index_of_scene = 0 list_of_scene = [] print "Go to:" # Iterate over scenes for scene in self.game.map.scenes: if(scene in ['end','start']): continue # Print all scene options that the player is not in if(scene != currentSceneName): list_of_scene.append(scene) index_of_scene+=1 print "[%s]: %s" % (index_of_scene,scene.capitalize()) playerAction = raw_input("> ") # If player does not enter a digit return False if(playerAction.isdigit() != True): return False # If player input number is more than lenght of list_of_scenes return False if(len(list_of_scene) < int(playerAction)): return False return list_of_scene[int(playerAction)-1] # Dialog handling def talkto(self): dialogNum = 0 list_of_dialog = [] # Appends all dialogs available in each scene to list_of_dialog and prints them for dialog in self.dialogs.keys(): list_of_dialog.append("%s: %s" % (dialog.capitalize(), self.dialogs[dialog])) dialogNum += 1 print "[%s]: %s" % (dialogNum, dialog.capitalize()) playerAction = raw_input("> ") # If player does not enter a digit return False if(playerAction.isdigit() != True): return False # If player input number is more than lenght of list_of_dialog return False if(len(list_of_dialog) < int(playerAction)): return False print list_of_dialog[int(playerAction)-1] # Examine handling def examine(self): hint_number = 0 list_of_hints = [] # Appends all hints available in each scene to list_of_hints and prints them for hint in self.hints.keys(): list_of_hints.append(self.hints[hint]) hint_number += 1 print "[%s]: %s" % (hint_number, hint.capitalize()) playerAction = raw_input("> ") # If player does not enter a digit return False if(playerAction.isdigit() != True): return False # If player input number is more than lenght of list_of_hints return False if(len(list_of_hints) < int(playerAction)): return False print list_of_hints[int(playerAction)-1] class Start(Scene): def enter(self, game): self.game = game print "Enter your name: " # Calls the definition inside Player class and assigns player name to self.name game.player.name = raw_input("> ") print "You have arrived at a dark and loomy place %s" % game.player.name print "Type in some numbers to see where you can go." return self.actions(['goto']) class House(Scene): hints = { 'zombie': 'His left arm seems to be ripped off!' } dialogs = { 'stay': 'Wonderful, this way please', 'leave': 'Please come again' } def enter(self, game): self.game = game print "Zombie: \"Welcome %s, I will be your host for the evening." % game.player.name # calls player name print "%s: \"What is this place?\"" print "Zombie: \"This is the Late Brain Inn. Do you want a room?\"" print "*****************************" print "What do you want to do next?" actions = ['goto'] # If dialogs dictionary has elements, calls actions parameter in talkto definition of class Scene if(len(self.dialogs)>0): actions.append('talkto') # If hints dictionary has elements, calls actions parameter in examine definition of class Scene if(len(self.hints)>0): actions.append('examine') return self.actions(actions) class Church(Scene): hints = { 'vampire': 'The creature is very pale with just one pointy tooth, the other one seems to be lost.' } dialog = { 'vampire': 'Leave this place!!' } def enter(self, game): self.game = game print "A sudden flash followed by white smoke appears as you enter the church and a vampire shows up from the smoke" print "Vampire: Welcome to this holy place %s" % game.player.name print "%s: Can I enter the churc?" print "Vampire: No!" print "%s: Why did you say welcome then?" print "Vampire: I thought you were someone else." print "*****************************" print "What do you want to do next?" actions = ['goto'] if(len(self.dialogs)>0): actions.append('talkto') if(len(self.hints)>0): actions.append('examine') return self.actions(actions) class Toolshed(Scene): hints = { 'bats': 'The bats are completely still.' } dialogs = { 'bats': 'No response' } def enter(self, game): self.game = game print "Inside the toolshed you see alot of junk and some bats hanging from the ceeling." print "The bats seems to be sleeping... for now." print "*****************************" print "What do you want to do next?" actions = ['goto'] if(len(self.dialogs)>0): actions.append('talkto') if(len(self.hints)>0): actions.append('examine') return self.actions(actions) class Graveyard(Scene): hints = { 'gravekeeper': 'The gravekeeper looks tired, and you notice he has a long thin chain around his neck' } dialogs = { 'gravekeeper': 'Why are you staring at me? Haven\'t you seen a hunchback before?', 'chain': 'Gravekeeper: Fine, I\'ll give you the chain' } def enter(self, game): self.game = game print "You enter the graveyard and see a man with a hunchback approaching" print "Gravekeeper: Welcome to the graveyard young %s" % game.player.name print "*****************************" print "What do you want to do next?" actions = ['goto'] if(len(self.dialogs)>0): actions.append('talkto') if(len(self.hints)>0): actions.append('examine') return self.actions(actions) class Crypt(Scene): hints = { 'trash_can': 'You see a red gem lying in the bottom.', 'skeleton': 'Looks like a normal skeleton apart from a few missing teeths.', } dialogs = { 'murray' : 'The red light scares me, but I\'m still evil!' } def enter(self, game): self.game = game print "You enter the crypt and see a skeleton without its head." print "Suddenly a dark voice echoes in by the entrance." print "Murray: \"Greetings %s, I am the evil demonic skull, Murray.\"" % game.player.name print "%s: \"Why is your head placed in a trashcan?\"." % game.player.name print "Murray: \"It's those damned voodoo kids.\"" print "%s: \"Do you want me to attach your head to your body?\"." % game.player.name print "Murray: \"That's not my body but yes, please do\"." print "*****************************" print "What do you want to do next?" actions = ['goto'] if(len(self.dialogs)>0): actions.append('talkto') if(len(self.hints)>0): actions.append('examine') return self.actions(actions) class End(Scene): # Not yet implemented def enter(self, game): self.game = game print "You exit the fog with the necklace" print "Congratulations, you've finished the game.!" class Dead(Scene): # Not yet implemented def death(self, game): self.game = game print "You died."
a89ba3ea381c392845379d369981fca1a0a16d1b
roberg11/is-206-2013
/Assignment 2/ex13.py
1,150
4.4375
4
from sys import argv script, first, second, third = argv print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second print "Your third variable is:", third ## Combine raw_input with argv to make a script that gets more input ## from a user. fruit = raw_input("Name a fruit: ") vegetable = raw_input("Name a vegetable: ") print "The name of the fruit: %r. The name of the vegetable: %r." % (fruit, vegetable) #### Study drills ## Try giving fewer than three arguments to your script. ## See that error you get? See if you can explain it. ## Answer: ValueError: need more than 3 values to unpack. # Because the script assigns four values to pass the # ArgumentValue the program won't run with less or more. ## Write a script that has fewer arguments and one that has more. ## Make sure you give the unpacked variables good names. # Answer: 'python ex13.py apple orange' gives the error: # ValueError: need more than 3 values to unpack ## Remember that modules give you features. Modules. Modules. ## Remember this because we'll need it later.
c232410e848da610102a0a08b4077aa2295847b0
roberg11/is-206-2013
/Assignment 2/ex20.py
1,803
4.53125
5
from sys import argv script, input_file = argv # Definition that reads a file given to the parameter def print_all(f): print f.read() # Definition that 'seeks' to the start of the file (in bytes) given to parameter # The method seek() sets the file's current position at the # offset. The whence argument is optional and defaults to 0, # which means absolute file positioning, other values are 1 # which means seek relative to the current position and 2 means # seek relative to the file's end. def rewind(f): f.seek(0) # Definition taking two parameters that counts the lines in the file # and reads each line and prints them. def print_a_line(line_count, f): print line_count, f.readline() # Variable assigned to the method of opening the file given to argument variable current_file = open(input_file) print "First let's print the whole file:\n" print_all(current_file) print "Now let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines:" ## Each time print_a_line is run, you are passing in a variable ## current_line. Write out what current_line is equal to on ## each function call, and trace how it becomes line_count in ## print_a_line. current_line = 1 # Current line is 1 in this function call print_a_line(current_line, current_file) # Current line is 1 + 1 = 2 in this function call current_line = current_line + 1 print "This is line nr: %r\n" % current_line print_a_line(current_line, current_file) # Current line is 2 + 1 = 3 in this function call current_line = current_line + 1 print "This is line nr: %r\n" % current_line print_a_line(current_line, current_file) ## Research the shorthand notation += and rewrite the script to use that. ## current_line += 1 is the equivalent of saying current_line = current_line + 1
f7bb2a3679f2f4c8d7d10ee151b68b802a1db3a2
roberg11/is-206-2013
/Assignment 2/ex4.py
2,001
4
4
# Number of cars available cars = 100 #Space available in each car space_in_car = 4.0 # Number of drivers for the cars drivers = 30 # Number of passengers in need to be transferred passengers = 90 # Number of cars which doesn't have any drivers cars_not_driven = cars - drivers # number of cars that has a driver cars_driven = drivers # Number of people who can be transported carpool_capacity = cars_driven * space_in_car # Average of passengers that can be put in each car average_passengers_per_car = passengers / cars_driven print "There are ", cars, " cars available." print "There are only ", drivers, " drivers available." print "There will be ", cars_not_driven, " empty cars today." print "We can transport ", carpool_capacity, " people today." print "We have ", passengers, " to carpool today." print "We need to put about ", average_passengers_per_car, " in each car." ### Study drills ### # 1: I used 4.0 for space_in_a_car, but is that necessary? # What happens if it's just 4? # Answer: The result returns 120.0 and 120 with just '4'. # It is not necessary for that specific calculation # 2: Remember that 4.0 is a "floating point" number. Find out what that means. # Answer: In computing, floating point describes a # method of representing an approximation of a real number # I.E.: 4.0 instead of just 4. # 3: Write comments above each of the variable assignments. # See above # 4: Make sure you know what = is called (equals) and # that it's making names for things. # Answer: '=' Assigns a value to the right to the variable name to the left. # 5: Remember that _ is an underscore character. # Answer: And not a 'space', got it! # 6: Try running python as a calculator like you did before and # use variable names to do your calculations. # Popular variable names are also i, x, and j. i = 4 x = 5 j = 6 # z = 4 * 5 = 20 z = i * x print z # y = (6 + 4) / 5 = 2 y = (j + i) / x print y
24f28e133e1af2d1490751fbae7a0065babcac13
roberg11/is-206-2013
/Assignment 2/ex10.py
1,453
3.96875
4
tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." backslash_cat = "I'm \\ a \\ cat." fat_cat = """ I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """ look = "Look over \"here\"." print tabby_cat print persian_cat print backslash_cat print fat_cat print look ##while True: ## for i in ["/", "-", "|", "\\", "|"]: ## print "%s\r" % i, skinny_cat = """ '''asdf''' asdf asdf asdf """ print skinny_cat #### Study drills # Memorize all the escape sequences by putting them on flash cards. # Answer: Ok. # Use ''' (triple-single-quote) instead. # Can you see why you might use that instead of """? # Answer: The only reason to use triple single-quotation marks # is if the sentence contains triple double-quotation marks. text1 = '''This string contains """ so use triple-single-quotes.''' text2 = """This string contains ''' so use triple-double-quotes.""" # Combine escape sequences and format strings to create a more # complex format. # Answer: # Remember the %r format? Combine %r with double-quote and # single-quote escapes and print them out. Compare %r with %s. # Notice how %r prints it the way you'd write it in your file, # but %s prints it the way you'd like to see it? # Answer: text3 = "I said: %r, and also a %r." % (tabby_cat, persian_cat) text4 = "I said: %s, and also %s." % (tabby_cat, persian_cat) print text3 print text4
3a0c72e28348bf2aa4d2c79038acb2ae0b95378f
bo-wambui/AssignmentOne
/reverseNames.py
161
4.21875
4
first_name = input("Please input your first name: ") last_name = input("Please input your last name: ") print("Hello "+last_name+" "+first_name+ ".How are you?")
91a675b7a124ef6eaae2c5fb17b4020c21371151
HoodCat/python_practice02
/prob05.py
688
3.59375
4
import random # 난수 생성. random 모듈에 random()함수 [0, 1) while(True): print("수를 결정하였습니다. 맞추어 보세요") correct = round(random.random()*99 + 1) higher = 1 lower = 100 answer = -1 count = 1 while(answer != correct): print(higher, '-', lower, sep='') answer = int(input(str(count)+'>>')) if answer > correct: print('더 낮게') lower = answer elif answer < correct: print('더 높게') higher = answer count += 1 print('맞았습니다') retry = input('다시하시겠습니까(y/n)>>') if retry=='n': break
571cee9a294a0a6ebed12944b4375728a16faf53
stephenstraymond/MEM611-Project
/read_table.py
6,941
4.15625
4
import argparse table_var_types = ['T','h','Pr','u','vr','s0'] def tableA17(search_var,known_var,known_value,units=True): """ tableA17(search_var,known_var,known_value,units=0): Function accepts 3 required inputs and 1 optional input and uses it to return data from the "Ideal-gas properties of air" table (table A17) in "Thermodynamics: An Engineering Approach 8th Ed" 4 Inputs: search_var - Must be in the set of ['T','h','Pr','u','vr','s0']. It is the variable searched for in the table. The corresonding value of this variable is returned at the end of the function. Ex. search_var = 'T' -> function returns Temp found based on remaining inputs known_var - Must be in the set of ['T','h','Pr','u','vr','s0']. It is the type of the value which will be searched for later (let me know if you think of a better way to say that). Ex. known_var = 'T' -> known_val is equal to the temperature at the point the user is trying to find known_value - Must be a real number. It is the known value which will be searched for in the table. It can be any value, if it is in the middle of two points it will interpolate. Ex. known_val = 200 -> If known_var = 'T' then it will look for values in the first row of table A17 units - Is a boolean true or false for if units are in SI or English. True if units are SI, and False if units are English. Default is set to True, because SI units are better. Ex. tableA17('h','T',200) -> Defaults to unit=True and SI units Ex. tableA17('h','T',200,True) -> Defines unit=True and uses SI Ex. tableA17('h','T',200,False) -> Defines unit=False and uses dumb units Stephen St. Raymond November 15, 2017 """ while search_var not in table_var_types: #in case anybody didn't bother to read the above instructions search_var = input('Unknown search_var, try again in [ T , h , Pr , u , vr , s0 ]: ') while known_var not in table_var_types: #you know it's gonna happen at some point known_var = input('Unknown known_var, try again in [ T , h , Pr , u , vr , s0 ]: ') if units: #Default is True, but also any integer that isn't zero will be read as 'True' by Python, so it's hard to mess up A17_text = open('thermo_A17.txt','r') #Opens text file and stores it else: #User can say False if they feel like using English units A17_text = open('thermo_A17E.txt','r') #Different file first_line = A17_text.readline() #Python stores the first line as a string in first_line A17_table = A17_text.readlines() #Python "reads" the rest of the lines, storing each one as a new element in the A17_table array for i in range(0,len(A17_table)): #i itterates from 0 to the last index of A17_table line_string = A17_table[i] #stores the string of line i of A17_table line_value_strings = line_string.split() #line_string is split from 1 string to 6 strings, one for each value in the row (T, h, Pr, u, vr, and s0) line_values = [] #initializes line_values as an empty array for value_string in line_value_strings: #value_string itterates through line_value_strings line_values.append(float(value_string)) #float() converts the values given to a float number type, then that value is appended to the line_value array A17_table[i] = line_values #Line number i of A17_table gets changed from one string of the values to an array of numbers error = [] #initiallize empty array reference_index = first_line.split().index(known_var) #establishing which unit we are looking for, to find the line value_index = first_line.split().index(search_var) for line in A17_table: #line itterates through each array in A17_table error_value = known_value - line[reference_index] #finds the difference between the known_value and each element number reference_index error.append(error_value) #appends that difference value to the error array abs_error = [] for val in error: abs_error.append(abs(val)) value_row_index = abs_error.index(min(abs_error)) value_row = A17_table[value_row_index] vr_plus_1 = A17_table[value_row_index+1] vr_minus_1 = A17_table[value_row_index-1] error_value = error[value_row_index] catch = 0 if error_value > 0 and value_row_index is not 0: y_a = value_row[value_index] y_b = vr_plus_1[value_index] x_a = value_row[reference_index] x_b = vr_plus_1[reference_index] elif error_value < 0 or value_row_index is 0: y_b = value_row[value_index] y_a = vr_minus_1[value_index] x_b = value_row[reference_index] x_a = vr_minus_1[reference_index] else: catch = 1 value = value_row[value_index] if not catch: value = y_a + (y_b - y_a) * ((known_value - x_a) / (x_b - x_a)) return value def get_commandline_options(): """ All credit to Dr. Shackleford for this function. It takes the variables given in the command line and turns them into data """ parser = argparse.ArgumentParser() parser.add_argument('-s','--search_var', help = 'give the search_var, defined in the tableA17 function doc', action='store', type=str, dest='search_var') parser.add_argument('-k','--known_var', help = 'give the known_var, defined in the tableA17 function doc', action='store', type=str, dest='known_var') parser.add_argument('-v','--known_value', help = 'give the known_value, defined in the tableA17 function doc', action='store', type=float, dest='known_value') parser.add_argument('-u','--unit', help = 'set the units, defined in the tableA17 function doc', action='store', type=int, dest='units', default=1) opts = parser.parse_args() return opts def main(): opts = get_commandline_options() x = tableA17(opts.search_var,opts.known_var,opts.known_value,opts.units) print x if __name__ == '__main__': main()
c6926ba2b5c71b69c3811f3074d42fa4b81b8dae
IanCarreras/hash-tables-sprint
/hashtables/ex1/ex1.py
898
3.703125
4
def get_indices_of_item_weights(weights, length, limit): """ YOUR CODE HERE """ # Your code here # iterate over the given weights # for each weight as key store value limit - weight # iterate through hashtable # if key + value = limit && value is in hashtable # return indeces of the key and value h = {} packages = None for n in weights: h[n] = limit - n if len(weights) == 2 and weights[0] + weights[1] == limit: packages = (1, 0) return packages for k in h: if k + h[k] == limit and h[k] in h: if weights.index(k) > weights.index(h[k]): packages = (weights.index(k), weights.index(h[k])) else: packages = (weights.index(h[k]), weights.index(k)) return packages # answer = get_indices_of_item_weights([4, 4], 2, 8) # print(answer)
b19ad1363c219ef770d43730dc7e1a0ab228ee0f
eeTeam2015/MovieRecommendationSystem
/spider/Step1_GetMovieList/getMovieList.py
4,839
3.578125
4
# 从每个分类的每个评分段的页面保存为 html 文件,存放在 ./html import time from selenium import webdriver def Categorys(category: [], links): # 生成要爬取的链接列表 for ca in category: a = 100 b = 90 while b >= 0: links.append(ca + str(a) + ':' + str(b) + '&action=') a = a - 10 b = b - 10 def scroll(driver): # 页面滚动函数 driver.execute_script(""" (function () { var y = document.body.scrollTop; var step = 100; window.scroll(0, y); function f() { if (y < document.body.scrollHeight) { y += step; window.scroll(0, y); setTimeout(f, 200); } else { window.scroll(0, y); document.title += "scroll-done"; } } setTimeout(f, 2000); })(); """) def getMovieList(driver, index, link): # 爬取某个分类函数 driver.get(link) scroll(driver) time.sleep(30) f = open('./html/' + str(index) + '.html', 'w', encoding='utf-8') f.write(driver.page_source) f.close() def main(): # 初始化浏览器驱动 chromedriver = r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe" driver = webdriver.Chrome(chromedriver) # 主程序 category = [] # 创建五个分类的基本链接 category.append( 'https://movie.douban.com/typerank?type_name=剧情&type=11&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=喜剧&type=24&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=动作&type=5&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=爱情&type=13&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=科幻&type=17&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=动画&type=25&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=悬疑&type=10&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=惊悚&type=19&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=恐怖&type=20&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=纪录片&type=1&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=短片&type=23&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=情色&type=6&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=同性&type=26&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=音乐&type=14&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=歌舞&type=7&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=家庭&type=28&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=儿童&type=8&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=传记&type=2&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=历史&type=4&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=战争&type=22&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=犯罪&type=3&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=西部&type=27&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=奇幻&type=16&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=冒险&type=15&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=灾难&type=12&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=武侠&type=29&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=古装&type=30&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=运动&type=18&interval_id=') category.append( 'https://movie.douban.com/typerank?type_name=黑色电影&type=31&interval_id=' ) links = [] # 创建链接表 Categorys(category, links) # 调用函数为每个分类生成十条链接 for index, link in enumerate(links): print(str(index) + ":" + link) getMovieList(driver, index, link) driver.close() driver.quit() if __name__ == '__main__': main()
f2632cac7b73b66147e19d6d91b03e1f4981e001
alunsong/learngit
/text.py
607
3.5625
4
import time def f(n): #time.clock() if n == 1: return 1 if n ==2: return 2 if n > 2: return f(n - 1) + f(n - 2) s1 = f(100) print("s1=",s1) def f(n): res = [0 for i in range(n+1)] res[1] = 1 res[2] = 2 for i in range(3, n+1): res[i] = res[i - 1] + res[i -2] return res[n] s2 = f(100) print("s2=",s2) cache = {} def fib(n): if n not in cache.keys(): cache[n] = _fib(n) return cache[n] def _fib(n): if n == 1 or n == 2: return n else: return fib(n-1) + fib(n-2) s3 = fib(100) print("s3=",s3)
bac15d0dff5ead8ffef7b9d21699a31fc9ee8040
Botany-Downs-Secondary-College/mathsquiz-KevenNguyen
/mathsquiz6.5.py
6,576
3.765625
4
from tkinter import* from random import* class MathsQuiz: def __init__(self,parent): self.HomeFrame = Frame(parent) self.HomeFrame.grid(row=0, column=0) #Title of Home Frame. self.TitleLable = Label(self.HomeFrame, text = "Welcome to Maths Quiz", bg = "black", fg = "white", width = 20, padx = 30, pady = 10, font = ("Time", "14", "bold italic")) self.TitleLable.grid(columnspan = 2) #Name label and entry. self.NameLabel = Label(self.HomeFrame, text = "Name: ", anchor = W, fg = "black", width = 10, padx = 30, pady = 10, font = ("Time", "12", "bold italic")) self.NameLabel.grid(row = 2, column = 0) self.NameInput = Entry(self.HomeFrame, width = 20) self.NameInput.grid(row = 2, column = 1) #Age label and entry. self.AgeLabel = Label(self.HomeFrame, text = "Age: ", anchor = W, fg = "black", width = 10, padx = 30, pady = 10, font = ("Time", "12", "bold italic")) self.AgeLabel.grid(row = 3, column = 0) self.AgeInput = Entry(self.HomeFrame, width = 20) self.AgeInput.grid(row = 3, column = 1) #Difficulty label and buttons. self.DifficultyLabel = Label(self.HomeFrame, text = "Choose Difficulty: ", fg = "black", width = 10, padx = 30, pady = 10, font = ("Time", "12", "bold italic")) self.DifficultyLabel.grid(row = 4, column = 0) self.Difficulties = ["Easy", "Medium", "Hard", "Extreme"] self.ChosenDifficulty = StringVar() self.ChosenDifficulty.set(0) self.DifficultyButtons = [] for i in range(len(self.Difficulties)): button = Radiobutton(self.HomeFrame, variable = self.ChosenDifficulty, value = i, text = self.Difficulties[i], anchor = W, padx = 50, width = "5", height = "2") self.DifficultyButtons.append(button) button.grid(row = i+5, column = 0, sticky = W) self.WarningText = Label(self.HomeFrame, text = "", anchor=W, fg = "red", width = 20, padx = 30, pady = 10) self.WarningText.grid(row=4, column=1) #Next button. self.NextButton = Button(self.HomeFrame, text = 'Next', command = self.show_QuestionsFrame) self.NextButton.grid(row = 8, column = 1) #Question page. self.QuestionsFrame = Frame(parent) self.HomeFrame.grid(row=0, column=1) self.QuestionsLabel = Label(self.QuestionsFrame, text = "Questions", bg = "black", fg = "white", width = 20, padx = 30, pady = 10, font = ("Time", "14", "bold italic")) self.QuestionsLabel.grid(columnspan = 2) self.Problems = Label(self.QuestionsFrame, text = "") self.Problems.grid(row = 1, column = 0) self.AnswerInput = Entry(self.QuestionsFrame, width = 20) self.AnswerInput.grid(row = 1, column = 1) self.feedback = Label(self.QuestionsFrame, text = "") self.feedback.grid(row = 2, column = 0) self.HomeButton = Button(self.QuestionsFrame, text = "Home", command = self.show_HomeFrame) self.HomeButton.grid(row = 8, column = 0) self.NextButton = Button(self.QuestionsFrame, text = "Next Question", command = self.NextQuestion) self.NextButton.grid(row = 8, column = 2) self.CheckButton = Button(self.QuestionsFrame, text = "Check Answer", command = self.check_answer) self.CheckButton.grid(row = 8, column = 1) def show_HomeFrame(self): self.QuestionsFrame.grid_remove() self.HomeFrame.grid() def show_QuestionsFrame(self): try: if self.NameInput.get() == "": self.WarningText.configure(text = "Please enter a name: ") self.NameInput.focus() elif self.NameInput.get().isalpha() == False: self.WarningText.configure(text = "Please enter text, not numbers") self.NameInput.delete(0, END) self.NameInput.focus() elif self.AgeInput.get() == "": self.WarningText.configure(text = "Enter an age.") self.AgeInput.delete(0, END) self.AgeInput.focus() elif int(self.AgeInput.get()) > 14: self.WarningText.configure(text = "This quiz is designed for people under 14") self.AgeInput.delete(0,END) self.AgeInput.focus() elif int(self.AgeInput.get()) < 0: self.WarningText.configure(text = "You are too old!") self.AgeInput.delete(0,END) self.AgeInput.focus() elif int(self.AgeInput.get()) < 7: self.WarningText.configure(text = "You are too young!") self.AgeInput.delete(0,END) self.AgeInput.focus() else: self.HomeFrame.grid_remove() self.QuestionsFrame.grid() except ValueError: self.WarningText.configure(text = "Please enter a number") self.AgeInput.delete(0, END) self.AgeInput.focus() def NextQuestion(self): x = randrange (10) y = randrange (10) self.answer = x + y questiontext = str(x) + " + " + str(y) + " = " self.Problems.configure(text = questiontext) def check_answer(self): try: ans = int(self.AnswerInput.get()) if ans == self.answer: self.feedback.configure(text = "Correct Answer") self.AnswerInput.delete(0, END) self.AnswerInput.focus() else: self.feedback.configure(text = "Wrong Answer") self.AnswerInput.delete(0, END) self.AnswerInput.focus() except ValueError: self.feedback.configure(text = "Please enter an answer") self.AnswerInput.delete(0, END) self.AnswerInput.focus() if __name__ == "__main__": root = Tk() frames = MathsQuiz(root) root.title("Quiz") root.mainloop()
8fc8f999fb37d659d75dea6710c4bd128d5218af
heejukim-developer/python-workspace
/2.py
714
3.984375
4
try: print("나누기 전용 계산기 입니다.") num1=int(input("첫번째 숫자를 입력하세요 : ")) num2=int(input("두번째 숫자를 입력하세요 : ")) print("{0}/{1}={2}".format(num1,num2, int(num1/num2))) except ValueError: print("에러입니다. 잘못된 값을 입력하였습니다.") try: print("한자리 숫자 나누기 전용 계산기입니다.") num1=int(input("첫번째 숫자를 입력하시오 : ")) num2=int(input("두번째 숫자를 입력하시오 : ")) if num1>=10 or num2>=10: raise ValueError print("{0}/{1}={2}".format(num1,num2,int(num1/num2))) except ValueError: print("잘못된 값을 입력하였습니다. ")
01856fd211ccab5c354258010641a00dc658c759
heejukim-developer/python-workspace
/ 함수어려워.py
793
4
4
print("<나야나>") def std_weight(height,gender,std_weight): print("키 {0}cm {1}의 표준체중은 {2}kg입니다.".format(height,gender,std_weight)) std_weight(175,"남자",round(175*175*0.0022)) def std_weight(height,gender,std_weight): print("키 {0}cm {1}의 표준체중은 {2}kg입니다.".format(height,gender,std_weight)) std_weight(170,"여자",round(170*170*0.0021)) print("<유튜브>") def std_weight(height,gender): if gender =="남자": return height*height*22 else: return height*height*21 height=175 gender="남자" weight=round(std_weight(height/100,gender),2) print("키 {0}cm {1}의 표준체중은 {2}kg입니다.".format(height,gender,weight)) print("희주","희주닉",sep="vs", end=" ?") print("무엇이 더 재밌을까요 ?")
676817b23e15e5368746b750f48e518427c937ae
onerbs/w2
/structures/w2.py
1,914
4.28125
4
from abc import ABC, abstractmethod from typing import Iterable from structures.linked_list_extra import LinkedList class _Linear(ABC): """Abstract linear data structure.""" def __init__(self, items: Iterable = None): self._items = LinkedList(items) def push(self, item): """Adds one item.""" self._items.push(item) @abstractmethod def pop(self): """Removes one item. :returns: The removed item. """ pass def is_empty(self): return self._items.is_empty() def __contains__(self, item): return item in self._items def __iter__(self) -> iter: return iter(self._items) def __len__(self) -> int: return len(self._items) def __str__(self) -> str: return str(self._items) class Stack(_Linear): def push(self, item): # O(1) """Adds one item to the stack.""" super().push(item) def pop(self): # O(n) """Removes the oldest item from the stack.""" return self._items.pop() # LIFO class Queue(_Linear): def push(self, item): # O(1) """Adds one item to the queue.""" super().push(item) def pop(self): # O(1) """Removes the most resent item from the queue.""" return self._items.shift() # FIFO class Deque(_Linear): def push(self, item): # O(1) """Adds one item to the end of the deque.""" super().push(item) def pop(self): # O(n) """ Removes the last item from the deque. :returns: The removed item. """ return self._items.pop() def unshift(self, value): # O(1) """Adds one item to the beginning of the deque.""" self._items.unshift(value) def shift(self): # O(1) """Removes the first item from the deque. :returns: The removed item. """ return self._items.shift()
caa378a73cb04f342d31f9ba4dcf5e4f79d99b05
akiharapeco/ALGO
/trie_tree.py
1,639
3.71875
4
import sys input = sys.stdin.readline class Node: child = {} def __init__(self): self.child = {"" : None} def setChild(node, c): node.child[c] = Node() class TrieTree: node = Node def __init__(self): self.node = Node() def insert(self, key): node = self.node # 先頭のNodeのオブジェクト for c in key: if node.child.get(c) == None: setChild(node, c) node = node.child[c] # 子ノードに移動 if node.child.get("\0") == None: # 末尾チェック用に"\0"をセット setChild(node, "\0") return True def find(self, key): node = self.node # 先頭のNodeのオブジェクト if not key: # keyが空文字列の場合 print("文字列が空です。") return False else: # ループケース for c in key: if node.child.get(c) == None: # 文字がキーとなる print("Not Found") return False node = node.child[c] # 子ノードに移動 if node.child.get("\0"): print("Found") return True else: print("Not Found") return False def main(): N = int(input()) tree = TrieTree() for i in range(N): line = input().strip().split() if line[0] == "insert": tree.insert(line[1]) elif line[0] == "find": tree.find(line[1]) if __name__ == "__main__": main()
35316e103f8a17573e683063cc8d8c8f88349c02
akiharapeco/ALGO
/dictorder.py
163
3.6875
4
A = input() ans = [] for char in A: ans.append('a') if ans[:-1]: print(''.join(ans[:-1])) elif A[0] > 'a': print(ans[0]) else: print(-1)
1eec5250193255117f0b9fa0524c3a4b2c5cbfb1
akiharapeco/ALGO
/binary_search.py
482
3.578125
4
import sys input = sys.stdin.readline def binarySearch(S, N, t): N = N // 2 if S[N] == None: return 0 else: return binarySearch(S[:N], N, t) + binarySearch(S[N+1:], N, t) return N = int(input()) S = input().strip().split() # Sの始端と終端に番兵を追加 S.prepend(None) S.append(None) Q = int(input()) T = input().strip().split() count = 0 for i in range(Q): count += binarySearch(S, N, T[i]) print(count)
fe313f72bfe399bdcdfdb20ddcfbf2ac2066530c
akiharapeco/ALGO
/LEETCODE/Python/binary_tree_level_order_traversal.py
856
3.78125
4
from typing import List # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None def appendOnSameLevel(t, level, depth): if t == None: return if len(level) < depth: level.append([]) level[depth-1].append(t.val) appendOnSameLevel(t.left, level, depth+1) appendOnSameLevel(t.right, level, depth+1) return class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if root == None: return [] level_list = [[root.val]] if root.left == None and root.right == None: return level_list appendOnSameLevel(root.left, level_list, 2) appendOnSameLevel(root.right, level_list, 2) return level_list
1f61e69415255fe326fa30914706d09009b47940
nishaagrawal16/Datastructure
/Problems/check_ith_bit_is_set_or_not.py
10,441
4.40625
4
############################################################################ # BITWISE OPERATORS ############################################################################ # youtube.com/watch?v=PXlzn60mRKI&list=PLfQN-EvRGF39Vz4UO18BtA1ocnUhGkvk5&index=7 # Lecture 02 - Check a number is even or odd without using modulus(%) # operator def evenOdd(n): if n & 1 == 1: print('%s is odd' % n) else: print('%s is even' % n) evenOdd(6) ############################################################################ # Lecture 03 - How many ways you can convert a to b by applying bitwise OR # on a | Bit Manipulation # a = 2 ==> 0 1 0 # | | | # V V V # b = 3 ==> 0 1 1 # 1*2*1 (times) # 1|1 = 1 # 1|0 = 1 # 0|1 = 1 # 0|0 = 0 def convertAToB(a, b): res = 1 while a and b: if a & 1 == 1: if b & 1 == 1: res = res*2 else: return 0 a = a >> 1 b = b >> 1 return res print(convertAToB(2, 3)) ############################################################################ # Lecture 04 - Find the smallest number greater than ‘n’ with exactly 1 bit # different in binary form. # Approach: We need to add 1 in that number and 'OR' with the number. def smallestNumber(n): return n | (n + 1) print(smallestNumber(13)) ############################################################################ # Lecture 05 - Check the ith bit is set or not | Bit Manipulation def ithBitISSet(n, i): if n & (1 << (i-1)): print('%s bit is set in number %s' % (i, n)) else: print('%s bit is not set in number %s' %(i, n)) ithBitISSet(11, 3) ############################################################################ # Lecture 06 - Number of bits to represent a number 'n' | Bit Manipulation # binary: floor(log2(n) + 1) # decimal: floor(log10(n) + 1) def numberOfBits(n): i = 0; a = 0 while a < n: a = a + 2**i i = i + 1 return i print(numberOfBits(10)) ############################################################################ # Lecture 07 - Count the set bits in number | Bit Manipulation # Approach 1: def countSetBit(n): count = 0 while n: if n & 1: count += 1 n = n >> 1 return count # Approach 2: # a = 2 ==> 0 1 0 # & 0 0 1 # ---------- # 0 0 0 # Ans = 1 iteration # # b = 3 ==> 0 1 1 # & 0 1 0 # ----------- # 0 1 0 # & 0 0 1 # ---------- # 0 0 0 # Ans = 2 iteration # Optimal Solution O(setbits) def countSetBit(n): count = 0 while n: n = n & n-1 count += 1 return count print(countSetBit(3)) ############################################################################# # Lecture 08 - Determine a number is power of 2 or not | Bit Manipulation | Leetcode # 2 ==> 0 0 1 0 # 4 ==> 0 1 0 0 # 8 ==> 1 0 0 0 # Only 1 bit is set for making the power of 2 def powerOfTwo(n): if n < 2 : print('no') return if n & n-1 == 0: print('yes') else: print('no') powerOfTwo(99) ######################################################################## # Lecture 09 - Determine a number is power of 4 or not | Bit Manipulation | Leetcode import math def powerOfFour(n): count = 0 if n < 4 : return False # It means number is of power of 2. if n & n-1 == 0: # find number of bits in binary. i = math.floor(math.log2(n) + 1) # Checks 1's bit is on which location(odd for power of 4) if i%2 != 0: return True return False print(powerOfFour(16)) ########################################################################## # Lecture 10 - XOR Properties | Bit Manipulation # XOR properties: # 1^0 = 1 # 0^1 = 1 # 1^1 = 0 # 0^0 = 0 # 1. A^0 = A # 2. A^A = 0 # 3. A^B = B^A # 4. A+B = A^B + 2*(A&B) ######################################################################## # Lecture 11 - XORSN (codechef) | Bit Manipulation # Find XOR[1, n]: 1^2^3^4^5^...n # Approach: # --------- # 1 = 1 # 1^2 = 3 # 1^2^3 = 0 # 1^2^3^4 = 4 # 1^2^3^4^5 = 1 # 1^2^3^4^5^6 = 7 # 1^2^3^4^5^6^7 = 0 # 1^2^3^4^5^6^7^8 = 8 def XORTillN(n): rem = n % 4 if rem == 0: return n elif rem == 1: return 1 elif rem == 2: return n+1 elif rem == 3: return 0 print(XORTillN(5)) ########################################################################## # Lecture 12 - Lonely Integer (Hackerrank) | Bit Manipulation def findTheUniqueNumber(arr): i = 0 output = 0 while i < len(arr): output = output^arr[i] i += 1 return output print(findTheUniqueNumber([1, 2, 3, 4, 3, 2, 1])) ######################################################################## # Lecture 13 - Missing Number | Interview Question | Bit Manipulation # Find the missing number not in the series of N. def missingNumber(arr, n): i = 1 output = 0 while i <= n: output = output^i i += 1 i = 0 while i < len(arr): output = output^arr[i] i += 1 return output print(missingNumber([1, 2, 3, 5], 5)) ######################################################################## # Lecture 14 - Determining Numbers (Hackerearth) | Bit Manipulation | Amazon Interview Question # Find the two unique elements in the array. import math def twoUniqueNumbers(arr): i = 0 output = 0 # XOR of all the numbers, so that we can get the sum of unique numbers. while i < len(arr): output = output^arr[i] i += 1 # In how many bits number can represent. bit = math.floor(math.log2(output) + 1) unique1 = 0 unique2 = 0 i = 0 while i < len(arr): # Check the bit position is set on which number of array, # if element set XOR the elements seprately. if arr[i] & (1 << (bit-1)): unique1 ^= arr[i] else: unique2 ^= arr[i] i += 1 if unique1 < unique2: return unique1, unique2 else: return unique2, unique1 print(twoUniqueNumbers([1, 5, 1, 2, 5, 3])) ########################################################################### # Lecture 15 - Flip the all bits of a Positive Number | Bit Manipulation # XOR will give the following result. # 1 -> 0 # 0 -> 1 # This thing we can achieve by using XOR. # 1 ^ 1 -> 0 # 0 ^ 1 -> 1 # If with XOR the given number with 1111(all position should be set) import math def flipAllBits(n): # In how many bits number can represent. bit = math.floor(math.log2(n) + 1) a = 1 << (bit - 1) # 1000 b = a - 1 # 0111 c = a | b # 1111 return n ^ c # 10 ==> 1010 # 5 ==> 0101 print(flipAllBits(10)) ########################################################################## # Lecture 16 - Print all the subsets of an array | Bit Manipulation # Tutorial # [1, 2, 3] # 1 0 0 --> 4 # 0 1 0 --> 2 # 1 1 0 --> 6 # 0 0 1 --> 1 # 1 0 1 --> 5 # 0 1 1 --> 3 # 1 1 1 --> 7 # total = 2**n - 1 def subsetsOfArray(n, arr): total = 2**n - 1 # This is for each binary number. for k in range(1, total + 1): i = 0 # This is for each element of array is set or not. for i in range(n): if k & (1 << i): print(arr[i], end=' '), print('') subsetsOfArray(3, [1, 2, 3]) # Output: # ------ # 1 # 2 # 1 2 # 3 # 1 3 # 2 3 # 1 2 3 ########################################################################## # Lecture 17 - Paying Up ( codechef ) | Bit Manipulation Tutorial # You have n notes and mobster demand for some moneny, if your notes subset # is equal to the money than you can give him money otherwise no need to # pay off. def payingUp(n, arr, money): total = 2**n -1 # This is for each binary number. for k in range(1, total + 1): i = 0 # This is for each element of array is set or not. sum = 0 for i in range(n): if k & (1 << i): print(arr[i], end=' '), sum += arr[i] print('sum: ', sum) if sum == money: return 'Yes' return 'No' print(payingUp(3, [1, 2, 3], 3)) ########################################################################## # Lecture 18 - Print all subsets of an array of k length | Bit Manipulation # Tutorial # Approach-1: # ----------- def subsetOfKLength(n, arr, lengthOfSubset): total = 2**n -1 # This is for each binary number. for k in range(1, total + 1): i = 0 count = 0 subset = [] # This is for each element of array is set or not. for i in range(n): if k & (1 << i): count += 1 subset.append(arr[i]) if count == lengthOfSubset: print(subset) subsetOfKLength(4, [1, 2, 3, 4], 2) # Approach-2: # ----------- def subsetOfKLength(n, arr, lengthOfSubset): total = 2**n -1 # This is for each binary number. for k in range(1, total + 1): i = 0 k1 = k count = 0 # Check the total set bit. while k1: k1 = k1 & (k1 - 1) count += 1 if count == lengthOfSubset: # This is for each element of array is set or not. for i in range(n): if k & (1 << i): print(arr[i], end=' ') print('') subsetOfKLength(4, [1, 2, 3, 4], 2) # Output: # ------ # 1 2 # 1 3 # 2 3 # 1 4 # 2 4 # 3 4 ########################################################################## # Lecture 19 - Sum vs XOR ( Hackerrank ) | Bit Manipulation Tutorial # a+b = a^b + 2(a&b) # for making a+b = a^b, we need to make a&b = 0 # 0 & 1 = 0 # 0 & 0 = 0 # 1 & 0 = 0 # 1 & 1 = 1 # for making it 0 we have two things 0 --> 0(2 ways) and 1 --> 0(1 ways) # n = 4: 1 0 0 # & 0 0/1 0/1 # ----------- # 1* 2* 2 = 4 answer (2**totalUnsetBit) import math def sumVsXOR(n): totalBitRepresent = math.floor(math.log2(n) + 1) totalSetBit = 0 # Check the total set bit. while n: n = n & (n - 1) totalSetBit += 1 totalUnsetBit = totalBitRepresent - totalSetBit return 2**totalUnsetBit # 1 << totalUnsetBit print(sumVsXOR(4))
7f7b411883c7f6985a354f163a11da1a879b0cac
nishaagrawal16/Datastructure
/Python/decorator_for_even_odd.py
1,363
4.21875
4
# Write a decorator for a function which returns a number between 1 to 100 # check whether the returned number is even or odd in decorator function. import random def decoCheckNumber(func): print ('Inside the decorator') def xyz(): print('*************** Inside xyz *********************') num = func() print(num) if num %2 != 0: # Odd print('number is odd') else: print('number is Even') return xyz @decoCheckNumber def random_number(): return random.randrange(1, 100) for i in range(10): random_number() # Output: # ------ # # Inside the decorator # *************** Inside xyz ********************* # 17 # number is odd # *************** Inside xyz ********************* # 3 # number is odd # *************** Inside xyz ********************* # 6 # number is Even # *************** Inside xyz ********************* # 32 # number is Even # *************** Inside xyz ********************* # 66 # number is Even # *************** Inside xyz ********************* # 84 # number is Even # *************** Inside xyz ********************* # 96 # number is Even # *************** Inside xyz ********************* # 45 # number is odd # *************** Inside xyz ********************* # 14 # number is Even # *************** Inside xyz ********************* # 64 # number is Even
aa5bc400ed332b046f45db6233975294afa48494
nishaagrawal16/Datastructure
/Linklist/partition_a_link_list_by_a_given_number.py
2,555
4.125
4
#!/usr/bin/python # Date: 2018-09-17 # # Description: # There is a linked list given and a value x, partition a linked list such that # all element less x appear before all elements greater than x. # X should be on right partition. # # Like, if linked list is: # 3->5->8->5->10->2->1 and x = 5 # # Resultant linked list should be: # 3->2->1->5->8->5->10 # # Approach: # Maintain 2 linked list 'BEFORE' and 'AFTER'. Traverse given linked list, if # value at current node is less than x insert this node at end of 'BEFORE' # linked list otherwise at end of 'AFTER' linked list. # At the end, merge both linked lists. # # Complexity: # O(n) class Node: def __init__(self, value): self.info = value self.next = None class LinkList: def __init__(self): self.start = None def create_list(self, li): if self.start is None: self.start = Node(li[0]) p = self.start for i in range(1,len(li)): temp = Node(li[i]) p.next = temp p = p.next def traverse(self): p = self.start while p is not None: print('%d ->' % p.info, end='') p = p.next print ('None') def partitionList(self, x): before_start = None before_end = None after_start = None after_end = None p = self.start present = 0 while p is not None: if p.info == x: present = 1 if p.info < x: if before_start is None: before_start = p before_end = p else: before_end.next = p before_end = before_end.next else: if after_start is None: after_start = p after_end = p else: after_end.next = p after_end = after_end.next p = p.next if not present: print('Element %d is not present in the list.' % x) return False # May be possible that before list is empty as no numebr is less than x. # so check the before end is not None otherwise make the after_start as # starting point of the list. after_end.next = None if before_end is None: self.start = after_start return True # merge both link lists before_end.next = after_start self.start = before_start return True def main(): print ('*************** LIST ***********************') link_list_1 = LinkList() link_list_1.create_list([3, 5, 8, 5, 10, 2, 1]) link_list_1.traverse() print ('\n***** LIST AFTER PARTITIONS BY A NUMBER *****') if link_list_1.partitionList(5): link_list_1.traverse() if __name__ == '__main__': main()
e24a154400dca8e0dc9b7cd24280e2aec5dc1464
nishaagrawal16/Datastructure
/leetcode/medium/153_find_minimum_in_rotated_sorted_array.py
639
3.671875
4
""" https://leetcode.com/problems/find-minimum-in-rotated-sorted-array Complexity ---------- O(logn) """ class Solution: def findMin(self, nums): l = 0 h = len(nums) - 1 while l < h: m = (l + h)//2 if nums[m] <= nums[h]: h = m else: # nums[m] > nums[h] l = m + 1 return nums[l] def main(): s = Solution() print('*********** LIST *****************') nums = [3,4,5,1,2] print(nums) minVal = s.findMin(nums) print('Minimum Value: ', minVal) if __name__ == '__main__': main() # Output: #--------- # *********** LIST ***************** # [3, 4, 5, 1, 2] # Minimum Value: 1
e26b77c4af32814a2608c3663b7a88dc400a6c46
nishaagrawal16/Datastructure
/Python/mro.py
2,019
3.953125
4
# Method Resolution Order(MRO) # https://makina-corpus.com/python/python-tutorial-understanding-python-mro-class-search-path # 1) Old style: when object is not the parent class as we are using python2. # We follow the DLR or depth-first left to right In which we first go # to the parent and grand parent if available than left to right. # # 2) New Style Python(3.x & 2.3) : Where object is the parent class or either # in python2 or python3. We follow the depth first left to right with good # head concept as well as C3 linearization algorithm for getting the right # mro concept. # Old Style: class X: def who_am_i(self): print("I am a X") class Y: def who_am_i(self): print("I am a Y") class A(X, Y): def who_am_i(self): print("I am a A") class B(Y, X): def who_am_i(self): print("I am a B") class F (A, B): def who_am_i(self): print("I am a F") f = F() print('************ OLD STYLE *****************') f.who_am_i() # Output: # ------ # ************ OLD STYLE ***************** # I am a F # New Style: class X(object): def who_am_i(self): print("I am a X") class Y(object): def who_am_i(self): print("I am a Y") class A(X, Y): def who_am_i(self): print("I am a A") class B(Y, X): def who_am_i(self): print("I am a B") class F (A, B): def who_am_i(self): print("I am a F") f = F() print('************ NEW STYLE *****************') f.who_am_i() # Output: # ------- # Traceback (most recent call last): # File "mro.py", line 55, in <module> # class F (A, B): # TypeError: Error when calling the metaclass bases # Cannot create a consistent method resolution # order (MRO) for bases X, Y # Explaination: Using C3 Linearization # F(A,B) = F + merge(L[A]+L[B] , A, B) # = F + merge((A, X, Y) + (B, Y, X), A, B) # = FA + merge((X, Y) + (B, Y, X), B) # = FAB + merge((X, Y)+ (Y, X)) # = Cann't create the mro()
bf13df5bf072797b535624bca57f87f5f5c7b39c
nishaagrawal16/Datastructure
/sorting/bubble_sort.py
1,314
4.6875
5
# Date: 20-Jan-2020 # https://www.geeksforgeeks.org/python-program-for-bubble-sort/ # Bubble Sort is the simplest sorting algorithm that works by # repeatedly swapping the adjacent elements if they are in wrong order. # Once the first pass completed last element will be sorted. # On next pass, we need to compare till last-1 elements and in next pass # last-2,...so on # Example: # list: [8, 5, 6, 9, 1, 4, 10, 3, 2, 7] # Pass1: [5, 6, 8, 1, 4, 9, 3, 2, 7, 10] # ---- Sorted # Pass2: [5, 6, 1, 4, 8, 3, 2, 7, 9, 10] # -------- Sorted # .... So on # Time Complexity: O(n2) # Space Complexity: O(1) def bubble_sort(un_list): n = len(un_list) for i in range(n): for j in range(n-1-i): if un_list[j] > un_list[j+1]: un_list[j+1], un_list[j] = un_list[j], un_list[j+1] def main(): unsorted_list = [8, 5, 6, 9, 1, 4, 10, 3, 2, 7] print('************ UNSORTED LIST **************') print(unsorted_list) bubble_sort(unsorted_list) print('************** SORTED LIST **************') print(unsorted_list) if __name__ == '__main__': main() # Output: # ------- # ************ UNSORTED LIST ************** # [8, 5, 6, 9, 1, 4, 10, 3, 2, 7] # ************** SORTED LIST ************** # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
8f1113231b2ad1f5c15bad8b5b704cee8c3f6514
nishaagrawal16/Datastructure
/Problems/reverse_a_number.py
1,014
3.609375
4
# **************************************************** # Reverse a number either positive or negative # O(n) # **************************************************** class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if x > 2**31 - 1 or x <= -2**31: return 0 num1 = x sum = 0 if x < 0: x = x *-1 while(x): sum = sum * 10 rem = x % 10 x = x // 10 # python2 x/10 sum = sum + rem if num1 < 0: sum = sum *-1 if sum > 2**31 - 1 or sum <= -2**31: return 0 return sum def main(): s = Solution() print(s.reverse(-123)) print(s.reverse(1463847412)) print(s.reverse(1534236469)) print(s.reverse(-2147483648)) if __name__ == '__main__': main() # Input: 1463847412 # Expected: 2147483641 # # Input: 1534236469 # Expected: 0 # # Input: -2147483648 # Expected: 0
da785b4c17fbed0a35787f7db82ee578ffaf07bf
nishaagrawal16/Datastructure
/Python/overriding.py
2,643
4.46875
4
# Python program to demonstrate error if we # forget to invoke __init__() of parent. class A(object): a = 1 def __init__(self, n = 'Rahul'): print('A') self.name = n class B(A): def __init__(self, roll): print('B') self.roll = roll # If you forget to invoke the __init__() # of the parent class then its instance variables would not be # available to the child class. # The self parameter within super function acts as the object of # the parent class super(B, self).__init__() # OR # A.__init__(self) b = B(23) print(b.roll) print(b.name) print(b.a) # Output: # ------- # B # A # 23 # Rahul # 1 # Python program to demonstrate private members of the parent class class C(object): def __init__(self): self.c = 21 # d is private instance variable self.__d = 42 class D(C): def __init__(self): self.e = 84 self.__f = 99 C.__init__(self) object1 = D() print(dir(object1)) # This is the way to call the private variables print(object1._C__d) print(object1._D__f) # produces an error as d is private instance variable # print D.d # Output: # ------ # ['_C__d', '_D__f', '__class__', '__delattr__', '__dict__', '__doc__', # '__format__', '__getattribute__', '__hash__', '__init__', '__module__', # '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', # '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'c', 'e'] # 42 # 99 # Python code to demonstrate multiple inheritance # we cannot override a private method of a superclass, which is the one having # double underscores before its name. # Base Class class A(object): def __init__(self): constant1 = 1 def __method1(self): print('method1 of class A') class B(A): def __init__(self): constant2 = 2 A. __init__(self) def __method1(self): print('method1 of class B') def calling1(self): self.__method1() self._A__method1() b = B() # AttributeError: 'B' object has no attribute '__method1' # b.__method1() # How to call the private methods of a class. b._B__method1() b._A__method1() print('******* Calling1 **************') b.calling1() # Output: # ------ # method1 of class B # method1 of class A # ******* Calling1 ************** # method1 of class B # method1 of class A
d651dd92ee3af966ab5321977ea4aa14f51ba543
nishaagrawal16/Datastructure
/leetcode/medium/2_add_two_numbers.py
1,822
3.8125
4
""" https://leetcode.com/problems/add-two-numbers/ Complexity ---------- O(max(m, n)) time and space """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class LinkList: def __init__(self): self.start = None def create_list(self, li): if self.start is None: self.start = ListNode(li[0]) p = self.start for i in range(1,len(li)): temp = ListNode(li[i]) p.next = temp p = p.next def traverse(self): p = self.start while p is not None: print('%d -> ' % p.val, end='') p = p.next print('None') class Solution: def addTwoNumbers(self, l1, l2): l3 = ListNode(-1) p = l3 carry = 0 while l1 or l2 or carry: val = 0 if l1: val += l1.val l1 = l1.next if l2: val += l2.val l2 = l2.next if carry: val += carry p.next = ListNode(val % 10) p = p.next carry = val // 10 return l3.next def main(): print('********** LIST-1 ***************') link_list_1 = LinkList() link_list_1.create_list([7, 1, 6]) link_list_1.traverse() print('********** LIST-2 ***************') link_list_2 = LinkList() link_list_2.create_list([5, 9, 2]) link_list_2.traverse() s = Solution() print('********** SUM OF LINKLIST IN REVERSE ***************') start3 = s.addTwoNumbers(link_list_1.start, link_list_2.start) list3 = start3 while list3 is not None: print('%d -> ' % list3.val, end='') list3 = list3.next print('None') if __name__ == '__main__': main() # Output: #--------- # ********** LIST-1 *************** # 7 -> 1 -> 6 -> None # ********** LIST-2 *************** # 5 -> 9 -> 2 -> None # ********** SUM OF LINKLIST IN REVERSE *************** # 2 -> 1 -> 9 -> None
3d12f27d6af0de12094419503b0009622250f7ac
nishaagrawal16/Datastructure
/Linklist/is_palindrome_using_stack.py
1,490
3.71875
4
# We solve this problem by using stack in which slow and fast two pointer point # to the start of the node. Then move slow pointer once and store slow.info in # the stack and fast pointer 2 times. class Node: def __init__(self, value): self.info = value self.next = None class SingleLinkList: def __init__(self): self.start = None def create_list(self, li): if self.start is None: self.start = Node(li[0]) p = self.start for i in range(1,len(li)): temp = Node(li[i]) p.next = temp p = p.next def traverse(self): p = self.start while p is not None: print('%c -> ' % p.info, end='') p = p.next print('None') def isPalindrom(self): slow = self.start fast = self.start stack = [] while fast and fast.next: stack.append(slow.info) slow = slow.next fast = fast.next.next # For odd number of element in list we have to ignore # the middle element. So need to move to the slow by next. if fast is not None: slow = slow.next while stack: if stack.pop() != slow.info: print('Not Palindrome') return slow = slow.next print('palindrome') def main(): link_list = SingleLinkList() print('*********** CREATING LIST ***************') link_list.create_list(['R', 'A', 'D', 'A', 'R']) print('*********** TRAVERSE LIST ***************') link_list.traverse() link_list.isPalindrom() if __name__ == '__main__': main()
3778577e21146124a2fa652c248b92d987ffe074
nishaagrawal16/Datastructure
/Linklist/kth_node_from_last_in_one_traversal.py
1,749
3.8125
4
#!/usr/bin/python # Date: 2019-06-22 # # Description: # Find kth element from last in a singly linked list. # # Approach: # Take 2 pointers p1 and p2, move p1 to kth node from beginning and p2 at head. # Now iterate over linked list until p1 reaches end. When p1 reaches end p2 # will be k nodes behind which is kth from last. # # Complexity: # O(n) Time class Node: def __init__(self, value): self.info = value self.next = None class LinkList: def __init__(self): self.start = None def create_list(self, li): if self.start is None: self.start = Node(li[0]) p = self.start for i in range(1,len(li)): temp = Node(li[i]) p.next = temp p = p.next def traverse(self): p = self.start while p is not None: print('%d ->' % p.info, end='') p = p.next print ('None') def kthElementFromLast(self, k): p1 = self.start p2 = self.start i = 1 while p1 is not None and i <= k: p1 = p1.next i = i + 1 # Now p1 is at kth position from head and p2 is at starting/head. # Iterate over linked list until p1 reaches end, when p1 will reach end, p2 # will be at (n - k) position, which is kth from last. while p1 is not None: p1 = p1.next p2 = p2.next print('%d element from the last: %d' % (k, p2.info)) def main(): print ('*************** LIST-1 ***********************') link_list_1 = LinkList() link_list_1.create_list([1, 3, 5, 10, 50, 30, 4, 6, 9, 22]) link_list_1.traverse() link_list_1.kthElementFromLast(3) if __name__ == '__main__': main() # Output # ------- # *************** LIST-1 *********************** # 1 -> 3 -> 5 -> 10 -> 50 -> 30 -> 4 -> 6 -> 9 -> 22 -> None # 3 element from the last: 6
9fb1a9a1a2619d67091e7e9a446dfbe7aad2271b
nishaagrawal16/Datastructure
/Python/decorator.py
1,722
3.59375
4
def decoWrapper1(func): def xyz(): print('start') func() return xyz @decoWrapper1 def print_hello1(): print('Hello') print('***************** decorator with function only ********************') print_hello1() # Output: # ------ # ***************** decorator with function only ******************** # start # Hello # With function arguments def decoWrapper2(func): def xyz(arg): print('start', arg) func(arg) return xyz @decoWrapper2 def print_hello2(name): print('Hello', name) print('***** decorator with function and one argument to the function *******') print_hello2('nisha') # Output: # ------- # ***** decorator with function and one argument to the function ******* # ('start', 'nisha') # ('Hello', 'nisha') # With two arguments by using * def decoWrapper3(func): def xyz(*arg): print('start', arg) func(*arg) return xyz @decoWrapper3 def print_hello3(*name): print('Hello', name) print('***** decorator with function and two argument to the function *******') print_hello3('nisha', 'agrawal') # Output: # ------- # ***** decorator with function and two argument to the function ******* # ('start', ('nisha', 'agrawal')) # ('Hello', ('nisha', 'agrawal')) def decoWrapper4(a, b): def xyz(func): def abc(name): print('start', a, b) func(name) return abc return xyz @decoWrapper4(10, 20) def print_hello4(name): print('Hello', name) print('***** decorator with arguments and function with one argument *******') print_hello4('nisha') # Output: # ------ # ***** decorator with arguments and function with one argument ******* # ('start', 10, 20) # ('Hello', 'nisha')
e537579c394d862f7cb109983580cc4ea7055674
nishaagrawal16/Datastructure
/Problems/roman_to_integer.py
953
3.546875
4
class Solution: def romanToInt(self, s: str) -> int: if not s: return 0 switcher = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } switcherSubs = { 'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900 } i = 0 result = 0 while i < len(s): values = switcherSubs.get(s[i:i+2], None) if values: result += values i += 2 else: result += switcher.get(s[i]) i += 1 return result s = Solution() print('*************** ROMAN TO INTEGER ***************') print('MCMXCIV') print(s.romanToInt('MCMXCIV')) # Output: # ------- # *************** ROMAN TO INTEGER *************** # MCMXCIV # 1994
e9258219764c0c6f0ce2dfc09285004a26c7effe
nishaagrawal16/Datastructure
/Python/partial_function.py
229
3.640625
4
from functools import partial def power(base, expo): print('{} base to the power of {}'.format(base, expo)) return base ** expo square = partial(power, expo=2) cube = partial(power, expo=3) print(square(3)) print(cube(3))
a49d1aba49b4e36f13e4eb077ddc5c569777df83
nishaagrawal16/Datastructure
/Python/shallow_and_deep_copy.py
1,422
4.0625
4
import copy # Shallow copy # https://docs.python.org/2/library/copy.html # A shallow copy constructs a new compound object and then (to the extent # possible) inserts references into it to the objects found in the original. # Means insert refernces of the inner objects also. l1 = [[1,2], 3, 4, [5, 6, 7]] l2 = copy.copy(l1) l2[0][0] = 8 print('************** SHALLOW COPY **************') print(l1) print(l2) l2[1] = 12 print(l1) print(l2) # A deep copy constructs a new compound object and then, recursively, inserts # copies into it of the objects found in the original. # Means only copy the inner objects. l3 = [[1,2], 3, 4, [5, 6, 7]] l4 = copy.deepcopy(l1) l4[0][0] = 8 print('**************** DEEP COPY ***************') print(l3) print(l4) l5 = [1, 2, 3, 4, 5, 6, 7] l6 = copy.copy(l5) l6[0] = 8 print('******** NO COMPOUND SHALLOW COPY ********') print(l5) print(l6) l7 = [1, 2, 3, 4, 5, 6, 7] l8 = copy.deepcopy(l7) l8[0] = 8 print('********** NO COMPOUND DEEP COPY *********') print(l7) print(l8) # Output: # ------- # ************** SHALLOW COPY ************** # [[8, 2], 3, 4, [5, 6, 7]] # [[8, 2], 3, 4, [5, 6, 7]] # **************** DEEP COPY *************** # [[1, 2], 3, 4, [5, 6, 7]] # [[8, 2], 3, 4, [5, 6, 7]] # ******** NO COMPOUND SHALLOW COPY ******** # [1, 2, 3, 4, 5, 6, 7] # [8, 2, 3, 4, 5, 6, 7] # ********** NO COMPOUND DEEP COPY ********* # [1, 2, 3, 4, 5, 6, 7] # [8, 2, 3, 4, 5, 6, 7]
fee51facfda5df96e5aa73eaf6f7d3962df39c2c
cherkesky/urbanplanner
/city.py
762
4.59375
5
''' In the previous Urban Planner exercise, you practices defining custom types to represent buildings. Now you need to create a type to represent your city. Here are the requirements for the class. You define the properties and methods. Name of the city. The mayor of the city. Year the city was established. A collection of all of the buildings in the city. A method to add a building to the city. Remember, each class should be in its own file. Define the City class in the city.py file. ''' class City: def __init__ (self, name, mayor, year_established): self.name = name self.mayor = mayor self.year_established = year_established self.city_buildings = list() def addBuildings(self, building): self.city_buildings.append(building)
bfd67d8551dff5d216bd92b1eeaacc42877860f6
coachmarino/web-caesar
/caesar.py
1,016
3.8125
4
def alphabet_position(letter): alphabet = 'abcdefghijklmnopqrstuvwxyz' alphabet2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if letter.isupper(): position = alphabet2.index(letter) else: position = alphabet.index(letter) return(position) def rotate_char(char, rot): alphabet = 'abcdefghijklmnopqrstuvwxyz' alphabet2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if char.isalpha() == False: return char elif char in alphabet: rotated_index = alphabet_position(char) + rot if rotated_index < 26: return alphabet[rotated_index] else: return alphabet[rotated_index % 26] elif char in alphabet2: rotated_index = alphabet_position(char) + rot if rotated_index < 26: return alphabet2[rotated_index] else: return alphabet2[rotated_index % 26] def encrypt(message, rot): encrypted = '' for i in message: encrypted = encrypted + rotate_char(i, rot) return encrypted
be3e04c41570b44477a192c89071a42feb295c8d
SEIR-7-06/python-oop-demo-code
/main.py
2,448
3.890625
4
my_dictionary = { "some_key": "some value" } my_dictionary['some_key'] class User: def __init__(self, name): self.name = name def greet(self): print(f'Hi my name is {self.name}') me = User('Michael') bob = User('Bob') sally = User('Sally') me.greet() print(me) print(me.name) #################################################### # Exercise # Create a BankAccount class that takes in a type class BankAccount: def __init__(self, type): self.type = type self.balance = 0 def deposit(self, amount): print('depositing money!') self.balance = self.balance + amount def withdraw(self, amount): if self.balance - amount < 0: print('You dont have enough funds! Please add some money') else: self.balance = self.balance - amount my_checking = BankAccount('checking') my_savings = BankAccount('savings') my_checking.deposit(200) ######################################################### # Exercise # Create a Phone class and give 2 methods # - make_call # - send_text class Phone: def __init__(self, phone_number): self.phone_number = phone_number def make_call(self, recipient): print(f'Calling {recipient} from {self.phone_number}!') def send_text(self, recipient): print(f'Sending text to {recipient}!') my_phone = Phone('555-5555') my_friends_phone = Phone('333-3333') friends_number = my_friends_phone.phone_number my_phone_number = my_phone.phone_number my_phone.make_call(friends_number) my_friends_phone.make_call(my_phone_number) ########################################################## class SmartPhone(Phone): def __init__(self, phone_number): # Allows us to inheret from the parent class super().__init__(phone_number) self.apps = ['email', 'calculator', 'clock'] def add_app(self, new_app): self.apps.append(new_app) def get_apps(self): print(self.apps) # Remove an app def remove_app(self, chosen_app): self.apps.remove(chosen_app) # Remove all apps def remove_all_apps(self): self.apps.clear() my_iphone = SmartPhone('222-2222') # print(my_iphone.phone_number) # print(my_iphone.apps) my_iphone.add_app('news') my_iphone.add_app('calendar') my_iphone.remove_app('news') my_iphone.remove_all_apps() # print(my_iphone.apps) my_iphone.get_apps() # my_iphone.make_call('123-4567')
2c5266d8513a64d2d4639d0bac5e1c0f1aff8cd9
kohyt/cpy5p1
/q6_find_ascii_char.py
683
4
4
# q6_find_ascii_char.py # get input ASCII = input("Please enter ASCII value: ") # check if ASCII.isnumeric(): if int(ASCII) > 0 and int(ASCII) < 127: input_ASCII = int(ASCII) print("The character is", chr(input_ASCII), ".") # output result else: print("Invalid option!") ASCII = input("Please enter ASCII value:") if ASCII.isnumeric(): input_ASCII = int(ASCII) print("The character is", chr(input_ASCII), ".") else: print("Invalid option!") ASCII = input("Please enter ASCII value:") if ASCII.isnumeric(): input_ASCII = int(ASCII) print("The character is", chr(input_ASCII), ".")
c1f6b1f89881acf3db059195eaa52868156d2188
kr255/IS601_Project_One
/Operations/Mean.py
1,295
3.953125
4
import Addition # # def addemup(s1, s2, s3=[]): # print("s1 ", s1) # print("s2 ", s2) # s3.append(Addition.addition(s1[0], s2[0])) # return s3 # # def meanCalulation(listofnum): # n = len(listofnum) # #print("length of list", len(listofnum)) # if n < 2: # return # else: # mid = n // 2 # leftlist = listofnum[0:mid] # print("left ", leftlist) # rightList = listofnum[mid:n] # print("right ", rightList) # meanCalulation(leftlist) # meanCalulation(rightList) # #addthemup() # # # if(len(listofnum) == 0): # # return 0 # # if(len(listofnum) < 2): # # return listofnum[0] # # if (len(listofnum) == 2): # # print("len == 2", Addition.addition(listofnum[0], listofnum[1])) # # return Addition.addition(listofnum[0], listofnum[1]) # # else: # # print(listofnum, " ", len(listofnum), "end ") # # ans= ((meanCalulation(listofnum[low:mid], low, mid) +\ # # meanCalulation(listofnum[mid:high], mid, high))) # # print(ans) def meanCalculation(listofnum): ans = 0.0 for elem in listofnum: ans += elem return ans/len(listofnum) def mean(listofnumbers): return (meanCalculation(listofnumbers))
f15fa27d83f849e344e4c1e91672ed6debf43901
burunduknina/HW
/lec_3/hw2.py
319
3.53125
4
def is_armstrong(number): return sum(list(map(lambda i: i ** len(str(number)), [ int(elem) for elem in str(number)]))) == number if __name__ == '__main__': assert is_armstrong(153) is True, 'Число Армстронга' assert is_armstrong(10) is False, 'Не число Армстронга'
0361c59522f505f1b3555077ab4696d4dd95a655
darthkenobi5319/ICP-HW
/HW2/hw5.py
3,144
4.625
5
# Homework #5 # In all the exercises that follow, insert your code directly in this file # and immediately after each question. # # IMPORTANT NOTES: # # 1) THIS IS A PROGRAMMING COURSE. :-) THIS MEANS THAT THE ANSWERS TO THESE QUESTIONS # ARE MEANT TO BE DONE IN CODE AS MUCH AS POSSIBLE. E.G., WHEN A QUESTION SAYS "COUNT # THE NUMBER OF TIMES THAT [...]" YOU SHOULD INTERPRET THIS AS "WRITE CODE THAT COUNTS # THE NUMBER OF TIMES THAT [...]". USE YOUR BEST JUDGMENT AND YOU WILL DO FINE. :-) # # 2) WHEN A QUESTION PROVIDES A VALUE FOR YOU TO USE IN COMPUTATIONS, FIRST STORE IT IN # A VARIABLE AND WRITE CODE THAT MAKES USE OF THAT VARIABLE. """ Question 1 1.1) Create a list called 'friends' containing the first names of 5 friends of yours, ranked in ascending chronological order based on when you met them. (The oldest friend goes first; the most recent one goes last.) Print that list. 1.2) Suppose you realize that you have recently made a new friend, most likely another hardcore Python geek taking our course. Use a function to add their name to the end of the list and print the updated list. 1.3) Print the name of the second oldest friend on your list, using the % operator or .template(). Supposing Maria is your second oldest friend on the list, then your code should print: Maria is the second oldest friend on my friends list. 1.4) Using a *single statement* (ie, just one line of code), replace the third and fourth friends on your list with two new names of your choice. The rest of your list should remain unchanged. Print the list 'friends' again. 1.5) Unfortunately, it turned out that Python geeks cannot be trusted and you are no longer friends with the person you added in Question 1.2. Remove them from the list 'friends' and print the list again. 1.6) Print the names of the friends on your list ordered alphabetically, while leaving the original list 'friends' unchanged. (To avoid complications due to capitalization, you can simply ensure all names are capitalized in the same way when you insert them. *Optional*: if you want practice with a common real-world task, write your code so that it can correctly sort the names regardless of how the user enters them.) """ # Answer to Question 1.1 # Answer to Question 1.2 # Answer to Question 1.3 # Answer to Question 1.4 # Answer to Question 1.5 # Answer to Question 1.6 """ Question 2 Below you will find a list of product prices in USD below (prices_usd). 2.1) Create a new empty list called prices_brl. 2.2) Use a for loop to populate the newly created list prices_brl with the same prices, but converted into Brazilian real. (As of Feb 28th, the exchange rate is approximately 1 USD = 3.74 BRL.) 2.3) Modify the original list prices_usd so that it contains the *rounded* prices. (The prices can be stored either as int or float, but must not have decimal values.) 2.4) Modify the list prices_usd so that the prices are sorted from the highest to the lowest. """ prices_usd = [48.8, 28.9, 58.4, 51.0, 98.0, 75.7, 14.8] # Answer to Question 2.1 # Answer to Question 2.2 # Answer to Question 2.3 # Answer to Question 2.4
8d17c04cda49436b3398588791a27acddb2c4acb
darthkenobi5319/ICP-HW
/Phonebook.py
7,544
4.15625
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 22 15:39:02 2019 @author: Harry Zhenghan Zhang """ class phoneBook: def __init__(self): self.phonebook = dict() # This function adds a contact with one name a one number # @param: contactName: A String specifying the contact name # contactNumber: A number # @return: returns no value. def addContact(self,contactName,contactNumber): if contactName not in self.phonebook.keys(): self.phonebook[contactName] = contactNumber else: print("User already exists") return # This fuction allows the user to change the phone number (add,delete,change) # @param: none # @return: returns no value. def updateContact(self): print("1).Add number") print("2).Delete number") print("3).Change number") print("4).Change contact name") updateType = input("How would you like to update your information?:") if updateType == "1": contactName = input("Enter the contact name: ") contactNumber = input("Enter the contact number: ") self.addNumber(contactName,contactNumber) elif updateType == "2": contactName = input("Enter the contact name: ") contactNumber = input("Enter the contact number: ") self.deleteNumber(contactName,contactNumber) elif updateType == "3": contactName = input("Enter the contact name: ") contactNumber1 = input("Enter the contact number you want to change: ") contactNumber2 = input("Enter the contact number you want to change into: ") self.changeNumber(contactName,contactNumber1,contactNumber2) elif updateType == "4": contactName1 = input("Enter the contact name you want to change: ") contactName2 = input("Enter the contact name you want to change into: ") self.changeName(contactName1,contactName2) else: print("Invalid input:") return # This function add a number to a given user # @param: contactName: A String specifying the contact name # contactNumber: A number # @return: returns no value. def addNumber(self,contactName,contactNumber): if contactName in self.phonebook.keys(): if contactNumber not in self.phonebook[contactName]: self.phonebook[contactName].append(contactNumber) else: print("User not found.") return # This function deletes a number to a given user # if there is only one number, the deletion of that would delete the contact entirely # @param: contactName: A String specifying the contact name # contactNumber: A number # @return: returns no value. def deleteNumber(self,contactName,contactNumber): if contactName in self.phonebook.keys(): if len(self.phonebook[contactName]) == 1: del self.phonebook[contactName] else: self.phonebook[contactName].remove(contactNumber) else: print("User not found.") return # This function changes a number to a given user # @param: contactName: A String specifying the contact name # contactNumber1: A number to change # contactNumber2: A number to change into # @return: returns no value. def changeNumber(self,contactName,contactNumber1,contactNumber2): if contactName in self.phonebook.keys(): self.phonebook[contactName].remove(contactNumber1) self.phonebook[contactName].append(contactNumber2) else: print("User not found.") return # This function changes a name to a given user # @param: # contactName1: A Name to change # contactName2: A Name to change into # @return: returns no value. def changeName(self,contactName1,contactName2): if contactName1 in self.phonebook.keys(): if contactName2 in self.phonebook.keys(): self.phonebook[contactName2].extend(self.phonebook[contactName1]) del self.phonebook[contactName1] else: self.phonebook[contactName2] = self.phonebook[contactName1] else: print("User not found.") return # This function deletes a contact by name, along with all the numbers. # @param: contactName: A String specifying the contact name # @return: returns no value. def deleteContact(self,contactName): if contactName in self.phonebook.keys(): del self.phonebook[contactName] else: print("User not found.") return # This functions finds all the numbers by a given contact name # @param: contactName: A String specifying the contact name # @return: returns the numbers or send an error message. def findContact(self,contactName): if contactName in self.phonebook.keys(): self.phonebook[contactName].sort() return self.phonebook[contactName] else: return "User not found." # This function displays the entire book. # Ordered by the names of contacts. # @param: none # @return: returns no value. def __str__(self): orderedKeys = list(self.phonebook.keys()) if len(orderedKeys) == 0: return "The phonebook is empty!" orderedKeys.sort() result = '' for i in orderedKeys: self.phonebook[i].sort() subresult = '' for j in self.phonebook[i]: subresult += str(j) result += ("Contact: " + i + " | Numbers: " + subresult + '\n') return result if __name__ == "__main__": cont = True phonebook = phoneBook() while cont == True: print("------------------------------------") print("What do you want to do?") print("1).Add a contact") print("2).Update a contact") print("3).Delete a contact") print("4).Lookup number for a person") print("5).Display the phonebook") print("6).Quit") print("-----------------------------") command = input("Please make your selection: ") if command == '1': contactName = input("Please Enter user name:") contactNumbers = [] temp = True while temp: contactNumbers.append(input("Please input a phone number:")) if (input("Add another number?(Y/N)").upper() != "Y"): temp = False phonebook.addContact(contactName,contactNumbers) continue elif command == '2': phonebook.updateContact() continue elif command == '3': contactName = input("Please enter the contact name you want to delete:") phonebook.deleteContact(contactName) continue elif command == '4': contactName = input("Please enter the contact name you want to look up:") print(phonebook.findContact(contactName)) continue elif command == '5': print(phonebook) continue elif command == '6': cont = False break else: print("Invalid input.")
04170fea196f8c50f94e38a65335d08e51461ea7
jhlin2337/T-Rex-Runner-AI
/neural_network.py
4,146
3.703125
4
import numpy as np import tensorflow as tf import constants from tensorflow.python.framework import ops # Uses a xavier initializer to create the starting weights for the neural network and initialize # all biases to zero. Return the weights and biases in a dictionary def initialize_parameters(): # Initialize weights and biases l1_weights = tf.get_variable("l1_weights", [constants.HIDDEN_LAYER_1_SIZE, constants.NN_INPUT_SIZE], initializer = tf.contrib.layers.xavier_initializer()) l1_biases = tf.get_variable("l1_biases", [constants.HIDDEN_LAYER_1_SIZE, 1], initializer = tf.zeros_initializer()) l2_weights = tf.get_variable("l2_weights", [constants.OUTPUT_LAYER_SIZE, constants.HIDDEN_LAYER_1_SIZE], initializer = tf.contrib.layers.xavier_initializer()) l2_biases = tf.get_variable("l2_biases", [constants.OUTPUT_LAYER_SIZE, 1], initializer = tf.zeros_initializer()) # Save weights and biases onto a dictionary parameters = {"l1_weights": l1_weights, "l1_biases": l1_biases, "l2_weights": l2_weights, "l2_biases": l2_biases} return parameters # Given a dataset containing the input for the neural network <X> and the parameters for the # neural network <parameters>, returns the value of the output node for the neural network after # forward propagation. Note that the sigmoid function has not yet been applied to the output node def forward_propagation(X, parameters): hidden_layer = tf.add(tf.matmul(parameters['l1_weights'], X), parameters['l1_biases']) hidden_layer = tf.nn.relu(hidden_layer) output_layer = tf.add(tf.matmul(parameters['l2_weights'], hidden_layer), parameters['l2_biases']) return output_layer # Given two sets of data, one for training and the other for testing, implements a # shallow, two-layer neural network. This function returns a dictionary containing the # weights and biases that the model learned from the training set. def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001, num_epochs = 2000, batch_size = 50): ops.reset_default_graph() # Initialize relevant variables num_train_examples = X_train.shape[1] input_size = X_train.shape[0] output_size = Y_train.shape[0] X = tf.placeholder(tf.float32, shape=(input_size, None)) Y = tf.placeholder(tf.float32, shape=(output_size, None)) # Initialize parameters parameters = initialize_parameters() # Tensorflow graph for forward propagation prediction = forward_propagation(X, parameters) # Tensorflow graph for the cost function cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=tf.transpose(prediction), labels=tf.transpose(Y))) # Back propagation using Adam Optimizer optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost) # Initialize variables init = tf.global_variables_initializer() # Start session with tf.Session() as sess: # Run initialization sess.run(init) # Train the network for epoch in range(num_epochs): epoch_cost = 0. batch_index = 0 while batch_index < num_train_examples: start = batch_index end = batch_index+batch_size X_batch = np.array(X_train[0:None, start:end]) Y_batch = np.array(Y_train[0:None, start:end]) _, c = sess.run([optimizer, cost], feed_dict={X: X_batch, Y: Y_batch}) epoch_cost += c batch_index += batch_size if epoch % 100 == 0: print ("Cost after epoch %i: %f" % (epoch, epoch_cost)) # Save parameters parameters = sess.run(parameters) # Calculate accuracy correct = tf.equal(tf.round(tf.sigmoid(prediction)), Y) accuracy = tf.reduce_mean(tf.cast(correct, "float")) # Print accuracy on training set and testing set print ("Train Accuracy:", accuracy.eval({X: X_train, Y: Y_train})) print ("Test Accuracy:", accuracy.eval({X: X_test, Y: Y_test})) return parameters
8d708e849f0ab71dd8d5d6940faf9d63eea84e3a
JuliaMowrey/AI-CSC481-Spring21
/astar-8puzzle-JuliaMowrey/eightpuzzle.py
4,168
3.984375
4
import copy import time from collections import deque class Puzzle: """A sliding-block puzzle.""" def __init__(self, grid): """Instances differ by their number configurations.""" self.grid = copy.deepcopy(grid) # No aliasing! def display(self): """Print the puzzle.""" for row in self.grid: for number in row: print(number, end="") print() print() def moves(self): """Return a list of possible moves given the current configuration.""" # YOU FILL THIS IN length = len(self.grid) move = [] for row in range(length): for number in range(len(self.grid[row])): if self.grid[row][number] == " ": r,c = row, number break if(r-1 < length and r-1 >= 0): move.append("N") if (r+1 < length): move.append("S") if (c+1 < len(self.grid[r])): move.append("E") if (c-1 < len(self.grid[r]) and c-1 >= 0): move.append("W") return move def neighbor(self, move): """Return a Puzzle instance like this one but with one move made.""" # YOU FILL THIS IN for row in range(len(self.grid)): for number in range(len(self.grid[row])): if self.grid[row][number] == " ": r, c = row, number break copied = copy.deepcopy(self.grid) if (move == "N"): temp = copied[r-1][c] copied[r-1][c] = " " copied[r][c] = temp if (move == "S"): temp = copied[r + 1][c] copied[r + 1][c] = " " copied[r][c] = temp if (move == "W"): temp = copied[r][c-1] copied[r][c-1] = " " copied[r][c] = temp if (move == "E"): temp = copied[r][c+1] copied[r][c+1] = " " copied[r][c] = temp return Puzzle(copied) def h(self, goal): """Compute the distance heuristic from this instance to the goal.""" # YOU FILL THIS IN misplaced = 0 for row in range(len(self.grid)): for col in range(len(self.grid[row])): if (self.grid[row][col] != goal.grid[row][col]): misplaced += 1 return misplaced class Agent: """Knows how to solve a sliding-block puzzle with A* search.""" def astar(self, puzzle, goal): """Return a list of moves to get the puzzle to match the goal.""" # YOU FILL THIS IN frontier = [] finished = [] frontier.append((puzzle.h(goal), puzzle, [])) while(frontier): frontier.sort(key=lambda i: i[0]) parent = frontier.pop(0) ph, ppuzzle, ppath = parent if (ppuzzle.grid == goal.grid): return ppath finished.append(ppuzzle.grid) move = ppuzzle.moves() for x in move: neighbor = ppuzzle.neighbor(x) if neighbor.grid in finished: continue ch = neighbor.h(goal) child = (ch + len(ppath), neighbor, ppath + [x]) for n in range(len(frontier)): if child[1].grid in frontier[n]: if(child[0] < frontier[n][0]): frontier[n] = child break else: frontier.append(child) return ppath def main(): """Create a puzzle, solve it with A*, and console-animate.""" puzzle = Puzzle([[1, 2, 5], [4, 8, 7], [3, 6,' ']]) puzzle.display() agent = Agent() goal = Puzzle([[' ',1,2], [3, 4, 5], [6, 7, 8]]) path = agent.astar(puzzle, goal) while path: move = path.pop(0) puzzle = puzzle.neighbor(move) time.sleep(1) puzzle.display() if __name__ == '__main__': main()
374d14cd58da240f5b779102ae6f1fdf41f1cd23
mousecpn/MMYZ_score_analysis
/Score_Analysis/Sort_by_id.py
563
3.765625
4
""" @ author:片片 @ 功能: 按照学号排序 @ 输入:DataFrame类型的大考数据,格式为【'班别','座号','语文','数学','英语','生物','化学','物理','总分'】 @ 输出:DataFrame类型,综合了四次大考的成绩,格式为【'班别','座号','语文','数学','英语','生物','化学','物理','id'】 """ import pandas as pd def Sort_by_id(dat): id = dat[['班别']].values*100 + dat[['座号']].values dat[['id']] = pd.DataFrame(id,columns=['id']) return dat.sort_values(by='id',ascending= True)
a958216fed11a0d41aaf7d974ddbef8d0dccee09
Serrones/tutorial_fastapi
/enums.py
220
3.515625
4
""" Module for storage enum classes """ from enum import Enum class ItemOption(str, Enum): """ This class represents all options available """ office = 'office' home = 'home' travel = 'travel'
8da1b3e55c7d3c0f941d28d2395c1e1d353be217
spikeyball/MITx---6.00.1x
/Week 1 - Problem 3.py
1,002
4.125
4
# Problem 3 # 15.0/15.0 points (graded) # Assume s is a string of lower case characters. # # Write a program that prints the longest substring of s in which the letters # occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your # program should print # # Longest substring in alphabetical order is: beggh # In the case of ties, print the first substring. For example, if s = 'abcbcd', # then your program should print # # Longest substring in alphabetical order is: abc # Note: This problem may be challenging. We encourage you to work smart. If # you've spent more than a few hours on this problem, we suggest that you move on # to a different part of the course. If you have time, come back to this problem # after you've had a break and cleared your head. lstring = s[0] cstring = s[0] for char in s[1::]: if char >= cstring[-1]: cstring += char if len(cstring) > len(lstring): lstring = cstring else: cstring = char print(lstring)
7af6cfd6cca4d6d94e40da38f9fb7898e9570f0d
spikeyball/MITx---6.00.1x
/Week 2 - Exercise - Polysum.py
585
4.03125
4
# Grader # 10.0/10.0 points (ungraded) # A regular polygon has n number of sides. Each side has length s. # # The area of a regular polygon is: # The perimeter of a polygon is: length of the boundary of the polygon # Write a function called polysum that takes 2 arguments, n and s. This # function should sum the area and square of the perimeter of the regular # polygon. The function returns the sum, rounded to 4 decimal places. import math def polysum(n, s): area = (.25 * n * s**2) / (math.tan(math.pi / n)) perimeter = n * s return round((area + perimeter ** 2), 4)
776a2822e9a89368babe21c0289fa93e4f1b6e55
CaptainMich/Python_Project
/StartWithPython/StartWithPython/Theory/OOP/Class.py
2,994
4.25
4
# ------------------------------------------------------------------------------------------------- # CLASS # ------------------------------------------------------------------------------------------------- print('\n\t\tCLASS\n') class Enemy: # define a class; # group similiar variables and function togheter life = 3 # ... def attack(self): # ... print('\tOuch -> life -1') # ... self.life -= 1 # ... def checkLife(self): # ... if self.life <= 0: # ... print('\tI am dead') # ... else: # ... print('\t' + str(self.life) + ' life left') # ... firstEnemy = Enemy() # how to access to the class print('Enemy_One:') # ... firstEnemy.checkLife() # ... firstEnemy.attack() # ... firstEnemy.checkLife() # ... print('') secondEnemy = Enemy() # access again to the class and discover that print('Enemy_Two:') # each object is indipendent of one another secondEnemy.checkLife() # ... secondEnemy.attack() # ... secondEnemy.attack() # ... secondEnemy.attack() # ... secondEnemy.checkLife() # ... # ------------------------------------------------------------------------------------------------- # CLASS __INIT__ # ------------------------------------------------------------------------------------------------- print('\n\n\t\tCLASS __INIT__\n') class Character: def __init__(self, x): # __init__ = initialize --> pass a value to them and use self.energy = x # it in a different way for the object that we'll create def get_energy(self): # ... return self.energy # ... Pippo = Character(5) # initialize Pippo's energy to 5 Pluto = Character(18) # initialize Pluto's energy to 18 print('Pippo energy is ' + str(Pippo.get_energy())) print('Pluto energy is ' + str(Pluto.get_energy()) + '\n')
02b83cdcc2728b8fc27447483c069526f4766cd7
dcreekp/learn-C-the-hard-way
/ex17/ex17stack.py
574
3.875
4
#! /usr/bin/env python class Stack(list): def push(self, item): self.append(item) print(self) def pop(self): try: super().pop() print(self) except IndexError: print("stack is empty") def peek(self): try: print(self[-1]) except IndexError: print("stack is empty") if __name__ == "__main__": stack = Stack() stack.push(10) stack.push(23) stack.push(88) stack.peek() stack.pop() stack.pop() stack.pop()
dd67e11094912546608dcf08689781b1ccb9fc80
lhwisdom07/ball_Filler
/ball_filler.py
391
3.796875
4
import math numberofB =int(input ("How many bowling balls will be manufactured? ")) ballD = float(input ("What is the diameter of each ball in inches? ")) ballR = float(ballD / 2) coreV = int(input("What is the core volume in inches cubed? ")) fillerA = (4/3) * (math.pi * (ballR ** 3))- coreV print("You will need",fillerA * numberofB,"inches in cubed filler") # import the math library
10ada69b7cf038032a55f0d71d1afce1054bd98a
blprottoy9/Hangman-game
/hangman.py
2,713
3.875
4
import random with open('d.txt','r') as f: store=f.read() store=store.split(" ") #print(store) word_store=('choose','convert','glory','MIGHTY','NATION') choose_word=random.choice(word_store) choose_word=choose_word.lower() length_choose=len(choose_word) show_word={} index={} for i in range(length_choose): show_word[i]="_" print(show_word) print(choose_word) i=0 g=0 get_input=" " show_word1=" " m=0 #get_input=raw_input("WHAT IS THE CHARACTER:") print(get_input) while i<length_choose: print("YOU HAVE ",length_choose-i," CHANCE") get_input=input("WHAT IS THE CHARACTER:") get_input=get_input.lower() if get_input not in show_word1 and len(get_input)==1: if get_input in choose_word: for j in range(length_choose): if get_input==choose_word[j]: show_word[j]=choose_word[j] show_word1+=choose_word[j] index[g]=j g+=1 m+=1 print("YOU CHOOSE RIGHT LETTER AND HAVE NOT LOOSE A CHANCE") else: i+=1 print("WRONG YOU LOSE A CHANCE") hint=input("If you want hint press y") if hint in ('y','Y') and g!=0: i+=1 flg1=0 while flg1!=1: store1=random.choice(store) #print(store1) flg=0 while flg!=1: choose_index=random.randrange(length_choose) if (choose_index not in index): flg=1 break if choose_word[choose_index] in store1: print("hint is:",store1) flg1=1 break elif hint in ('y','Y') and g==0: i+=1 flg=0 while flg!=1: store1=random.choice(store) choose_index=random.randrange(length_choose) if choose_word[choose_index] in store1: print("hint is:",store1) flg=1 break else: if len(get_input)>1: print("please give one character at a time.") else: print("YOU have already CHOOSE the letter") print(show_word) if m==length_choose: break if(m<length_choose): print("Game over","you are dead") else: print("victory")
8b0b50e4d55d1f3258fb3f62d4f451254805f28e
pikez/Data-Structures
/tree/binary.py
2,420
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- nodes = [6, 4, 2, 3, '#', '#', '#', '#', 5, 1, '#', '#', 7, '#', '#'] avlnodes = [6, 4, 2, '#', '#', '#', 5, 1, '#', '#', 7, '#', '#'] class Node(object): def __init__(self, data, left=None, right=None): self.root = data self.left = left self.right = right def pre_create(root): value = avlnodes.pop(0) if value == "#": root = None else: root = Node(value) root.left = pre_create(root.left) root.right = pre_create(root.right) return root def pre_order(root): if root is None: return else: print root.root, pre_order(root.left) pre_order(root.right) def in_order(root): if root is None: return else: in_order(root.left) print root.root, in_order(root.right) def post_order(root): if root is None: return else: post_order(root.left) post_order(root.right) print root.root, def get_leaf_num(root): if root is None: return 0 if root.right is None and root.left is None: return 1 return get_leaf_num(root.right) + get_leaf_num(root.left) def get_depth(root): if root is None: return 0 left_depth = get_depth(root.left) right_depth = get_depth(root.right) return left_depth + 1 if left_depth > right_depth else right_depth + 1 def get_node_num_kth_level(root, k): if root is None or k < 1: return 0 elif k == 1: return 1 left_num = get_node_num_kth_level(root.left, k-1) right_num = get_node_num_kth_level(root.right, k-1) return left_num + right_num def structure_cmp(root1, root2): if root1 is None and root2 is None: return True elif root1 is None or root2 is None: return False def is_avl(root): if root is None: return True distance = get_depth(root.left) - get_depth(root.right) if abs(distance) > 1: return False else: return is_avl(root.left) and is_avl(root.right) if __name__ == "__main__": root = None root = pre_create(root) pre_order(root) print in_order(root) print post_order(root) print print "leaf num: ", get_leaf_num(root) print "depth: ", get_depth(root) print "3th node num: ", get_node_num_kth_level(root, 3) print "is avl: ", is_avl(root)
fc3da55af0a89264a92cbd952792c952512a5d2a
pikez/Data-Structures
/sorting/selection.py
471
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def selection(array): length = len(array) for i in xrange(length): min_index = i for j in xrange(i+1, length): if array[j] < array[min_index]: min_index = j array[i], array[min_index] = array[min_index], array[i] return array if __name__ == "__main__": test_data = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48] print selection(test_data)
ac7b07c69a07c42f03162712abfc6e3e4a422002
781-Algorithm/JangSeHyun
/week6/[BOJ] 1197 최소 스패닝 트리.py
647
3.671875
4
# 1197 - 최소 스패닝 트리 import sys input = sys.stdin.readline def find_parent(x): if parent[x] != x: parent[x] = find_parent(parent[x]) return parent[x] def union_parent(x,y): x = find_parent(x) y = find_parent(y) if x < y: parent[y] = x else: parent[x] = y v, e = map(int, input().split()) parent = [i for i in range(v+1)] graph, total = [], 0 for _ in range(e): graph.append(tuple(map(int, input().split()))) graph.sort(key=lambda x: x[-1]) for road in graph: a,b,cost = road if find_parent(a)!=find_parent(b): union_parent(a,b) total+=cost print(total)
438eef065677d2a5907e66249d5c57b7b3870623
781-Algorithm/JangSeHyun
/week8/[BOJ] 11758 CCW.py
445
3.578125
4
# 11758 CCW 벡터의 외적 이용 points = [] for _ in range(3): points.append(list(map(int,input().split()))) def size(vector): return (vector[0]**2+vector[1]**2)**(1/2) vec1 = [points[1][0]-points[0][0],points[1][1]-points[0][1]] vec2 = [points[2][0]-points[1][0],points[2][1]-points[1][1]] func = (vec1[0]*vec2[1]-vec1[1]*vec2[0])/(size(vec2)*size(vec1)) if func > 0: print(1) elif func == 0: print(0) else: print(-1)
c4f448421cc18ec05b4cbb13e1a0dee5d8a38340
781-Algorithm/JangSeHyun
/week1/[PGS] 위장.py
279
3.703125
4
from collections import defaultdict as ddict def solution(clothes): answer = 1 look = ddict(list) for cloth in clothes: look[cloth[1]].append(cloth[0]) for category in look.keys(): answer *= (1+len(look[category])) return answer-1
cd93e32cb678128dc23f3d0fca0733f4ff0b50dd
yancostrishevsky/ASD
/Sorting algorithms/linked list structure.py
1,377
3.734375
4
#1. Zdefiniować klasę w Pythonie realizującą listę jednokierunkową. class Node: def __init__(self): self.value = None self.next = None def display(head): if head is not None: print(head.value, end=' ') display(head.next) #2. Zaimplementować wstawianie do posortowanej listy. def insertNode(head, element): while head.next is not None and head.next.value < element.value: head = head.next element.next = head.next head.next = element #3. Zaimplementować usuwanie maksimum z listy. def delMax(List): p = List.next p_prev = prev = List List = List.next while prev.next is not None: if prev.next.value > p.value: p_prev = prev p = prev.next prev = prev.next p_prev.next = p.next return List #Proszę zaimplementować funkcję odwracającą listę jednokierunkową def reverse(List): if List is None: return prev = None nxt = List.next while List: List.next = prev prev = List List = nxt if nxt != None: nxt = nxt.next return prev """wartownik = Node() node1 = Node() node1.value = 2 node2 = Node() node2.value = 5 wartownik.next = node1 insertNode(wartownik,node2) display(wartownik) delMax(wartownik) display(wartownik)"""
9a7024054f899d3e920735a797468c4d82f45634
beetisushruth/Python-projects
/AiRit/Passenger.py
889
3.703125
4
""" file: Passenger.py description: class to represent passenger language: python3 author: Abhijay Nair, an1147@rit.edu author: Sushruth Beeti, sb3112@rit.edu """ class Passenger: __slots__ = "name", "ticket_number", "has_carry_on" def __init__(self, name, ticket_number, has_carry_on): """ Constructor method for passenger class :param name: name of passenger :param ticket_number: ticket number of the passenger :param has_carry_on: has carry on """ self.name = name self.ticket_number = ticket_number self.has_carry_on = has_carry_on def __str__(self): """ To string method for passenger :return: to string method of passenger """ return str(self.name + ', ticket: ' + self.ticket_number + ', carry_on: ' + str(self.has_carry_on))
f61e1501b64bb58aac7b0f10a83e2a74a025aee2
beetisushruth/Python-projects
/AiRit/Aircraft.py
2,937
3.6875
4
from Gate import Gate from MyStack import MyStack from Passenger import Passenger """ file: Aircraft.py description: Class to represent aircraft language: python3 author: Abhijay Nair, an1147@rit.edu author: Sushruth Beeti, sb3112@rit.edu """ class Aircraft: __slots__ = "passengers_with_carry_on", "passengers_without_carry_on", \ "max_passengers_limit" def __init__(self, max_passengers_limit): """ Constructor aircraft class :param max_passengers_limit: maximum passengers limit """ self.passengers_with_carry_on = MyStack() self.passengers_without_carry_on = MyStack() self.max_passengers_limit = max_passengers_limit def board_passenger(self, passenger: Passenger): """ Board passenger into aircraft :param passenger: passenger :return: boolean """ if self.passengers_with_carry_on.size() + \ self.passengers_without_carry_on.size() >= self.max_passengers_limit: return False if passenger.has_carry_on: self.passengers_with_carry_on.push(passenger) else: self.passengers_without_carry_on.push(passenger) return True def board_passengers(self, gate: Gate): """ Board all passengers into aircraft :param gate: gate :return: None """ is_aircraft_full = False if gate.current_gate_count > 0: print("Passengers are boarding the aircraft...") for i, queue in enumerate(gate.boarding_queues[::-1]): while queue.size() != 0: passenger = queue.peek().value has_passenger_boarded = self.board_passenger(passenger) if has_passenger_boarded: print("\t" + str(passenger)) gate.dequeue_passenger(len(gate.boarding_queues) - i - 1) else: print("The aircraft is full.") is_aircraft_full = True break if is_aircraft_full: break if not is_aircraft_full: print("There are no more passengers at the gate.") print("Ready for taking off ...") def disembark_passengers(self): """ Disembark passengers from the aircraft :return: None """ if self.passengers_with_carry_on.size() + self.passengers_without_carry_on.size() > 0: print("The aircraft has landed.") print("Passengers are disembarking...") while self.passengers_without_carry_on.size() != 0: print("\t" + str(self.passengers_without_carry_on.peek())) self.passengers_without_carry_on.pop() while self.passengers_with_carry_on.size() != 0: print("\t" + str(self.passengers_with_carry_on.peek())) self.passengers_with_carry_on.pop()
bdef580de8d6b07376fca1738eb61cf2ed7323c6
tobin/contest
/codejam/2013/round1b/diamonds.py
5,490
3.703125
4
#!/usr/bin/python # Google Code Jam # Round 1B # # 2013-05-04 # # This program is an insane overkill approach to the problem. As one # might expect, the result of piling up a bunch of diamonds all # dropped from the same X position is a big triangular heap of # diamonds. The only uncertainty is how many diamonds are on the right # and left uncompleted sides of the heap. This we can figure out with # simple probability using the binomial formula. # Because I was dumb, I didn't actually think about the above, and # instead implemented the straight-forward diamond-dropping simulator. # The solution is kind of cool, because it maintains an "ensemble" # which maps all possible configurations after N diamond drops to the # probability of those configurations occurring, and it operates on # those ensembles. # # This is totally unnecessary and it's too slow to operate on anything # but small inputs. import sys import matplotlib.pyplot as plt import numpy as numpy def combine_ensembles(a, b): for x in b: if x in a: a[x] += b[x] else: a[x] = b[x] return a def occupied(conf, x, y): return (x,y) in conf memo = dict() # An ensemble is a mapping from configurations to probabilities def add_diamond(conf, x, y): problem = (conf, x, y) if problem in memo: sys.stdout.write('+') return memo[problem] sys.stdout.write('x') #print "Adding a diamond to " + str(conf) + " at (%d, %d) " % (x,y) # Add a diamond at position x, y. Return resulting ensemble # Fall until blocked directly below, or have hit the ground while (y>0): if occupied(conf, x-1, y-1) and occupied(conf, x+1, y-1): break # we're stuck elif occupied(conf, x-1, y-1) and not occupied(conf, x+1, y-1): # slide to the right x += 1 y -= 1 elif not occupied(conf, x-1, y-1) and occupied(conf, x+1, y-1): # slide to the left x -= 1 y -= 1 elif occupied(conf, x, y-2): # Now we're free -- maybe -- to hop down two spaces # Here we have to do a non-deterministic branch. We already know that both of # these spots are free - otherwise we would have had to slide. a = add_diamond(conf, x-1, y-1) b = add_diamond(conf, x+1, y-1) for x in a: a[x] *= 0.5 for x in b: b[x] *= 0.5 result = combine_ensembles(a, b) memo[problem] = result return result else: # we're free to fall directly downwards y -= 2 # Now we're either stuck or in the ground. This is a definite result. assert (x,y) not in conf conf = set(conf) | {(x,y)} result = { frozenset(conf) : 1.0 } memo[problem] = result return result def calculate_probability(ensemble, x, y): # Find the probability that there's a diamond at (x,y) given # ensemble of configurations p = 0 for conf in ensemble: if (x,y) in conf: p += ensemble[conf] return p def simulate(X, Y, N): # The initial state definitely contains nothing: ensemble = { frozenset([]) : 1.0 } # Now add diamonds one-by-one: for n in xrange(0, N): sys.stdout.write(".") sys.stdout.flush() new_ensemble = dict() for conf in ensemble: max_height = max([y for (x,y) in conf]) if conf else 0 max_height += (max_height % 2) # must be even! e = add_diamond(conf, 0, max_height + 2) for c in e: e[c] *= ensemble[conf] # multiply by the prior if c in new_ensemble: new_ensemble[c] += e[c] else: new_ensemble[c] = e[c] # new_ensemble = combine_ensembles(new_ensemble, e) # add to our collection ensemble = new_ensemble if False: print "Currently tracking %d configurations: " % len(ensemble) print "Most probable has prob = %f" % max(ensemble.values()) print "Least probable has prob = %g" % min(ensemble.values()) print "Ratio = %g" % (max(ensemble.values()) / min(ensemble.values())) print "Sum of probabilities = %f" % sum(ensemble.values()) c = ensemble.keys()[0] x = map(lambda coord : coord[0], c) y = map(lambda coord : coord[1], c) plt.plot(x, y, 'd') plt.grid('on') plt.xlim([-20, 20]) plt.ylim([-1, 20]) plt.show() # Cull ensemble, removing configurations that are very improbable cull = filter(lambda c : ensemble[c] < 1e-5, ensemble) for unwanted_key in cull: del ensemble[unwanted_key] #print ensemble # If a block already is known to land at the chosen spot, we # can quit now: p = calculate_probability(ensemble, X, Y) if p > (1.0 - 1e-6): return p return p def main(): numbers = map(int, raw_input().split()) T = numbers.pop(0) for t in xrange(0, T): numbers = map(int, raw_input().split()) N = numbers.pop(0) X = numbers.pop(0) Y = numbers.pop(0) print "Case #%d: " # print "N = %d, X = %d, Y = %d" % (N, X, Y) result = simulate(X, Y, N) print result main()
9f4ba3a66e8c23af39c7a1bc291232bc5ac25a2a
zdravkob98/Programming-Basics-with-Python-March-2020
/Programing Basics March2020/Conditional Statements - Exercise/Metric Converter.py
270
3.65625
4
num =float(input()) metric = str(input()) output_metric =str(input()) if metric == 'mm': num = num / 1000 elif metric == 'cm' : num = num /100 if output_metric == 'mm': num = num * 1000 elif output_metric == 'cm': num = num * 100 print(f'{num:.3f}')
f53bafc7419db675a259ba47d7d1e6d242f77c14
zdravkob98/Programming-Basics-with-Python-March-2020
/Programing Basics March2020/demo/demo.py
396
3.546875
4
import math count_people = int(input()) tax = float(input()) price_chaise_lounge = float(input()) price_for_umbrella = float(input()) total_taxes = count_people * tax using_umbrella = math.ceil(count_people / 2) * price_for_umbrella using_chaise_lounge = math.ceil(count_people * 0.75) * price_chaise_lounge total = total_taxes + using_umbrella + using_chaise_lounge print(f'{total:.2f} lv.')
59218d18af7cd37b208211db3c1e68b3fe38319e
zdravkob98/Programming-Basics-with-Python-March-2020
/Programing Basics March2020/Loops - Exercise/Divide Without Remainder.py
447
3.546875
4
n = int(input()) p1_count = 0 p2_count = 0 p3_count = 0 for i in range(n): maimuna=int(input()) if maimuna % 2 == 0 : p1_count += 1 if maimuna % 3 == 0 : p2_count += 1 if maimuna % 4 == 0 : p3_count += 1 percentage_p1 = p1_count / n * 100 percentage_p2 = p2_count / n * 100 percentage_p3 = p3_count / n * 100 print(f'{percentage_p1:.2f}%') print(f'{percentage_p2:.2f}%') print(f'{percentage_p3:.2f}%')
41c3cf50e396d276788761b849e6b76b6b7a49b2
zdravkob98/Programming-Basics-with-Python-March-2020
/Programing Basics March2020/1/04. Cruise Games.py
1,002
3.75
4
import math name = input() games = int(input()) sum_points = 0 volleyball_point = 0 v_games = 0 tennis_point = 0 t_games = 0 bardminton = 0 b_games = 0 for i in range(games): game_name = input() points = int(input()) if game_name == "volleyball": points *= 1.07 sum_points += points volleyball_point += points v_games += 1 elif game_name == "tennis": points *= 1.05 sum_points += points tennis_point += points t_games += 1 elif game_name == 'badminton': points *= 1.02 sum_points += points bardminton += points b_games += 1 a = math.floor(volleyball_point / v_games) b = math.floor(tennis_point / t_games) c = math.floor(bardminton / b_games) if a >= 75 and b >= 75 and c >= 75: print(f"Congratulations, {name}! You won the cruise games with {math.floor(sum_points)} points.") else: print(f"Sorry, {name}, you lost. Your points are only {math.floor(sum_points)}.")
de353ae4c821d56d3a6c6ed274c1e9e0b433cdb4
zdravkob98/Programming-Basics-with-Python-March-2020
/Programing Basics March2020/Conditional Statements - Exercise/Time + 15 Minutes.py
375
3.859375
4
start_hour = int(input()) start_minutes = int(input()) time_in_minutes = start_hour * 60 + start_minutes time_plus_15_min = time_in_minutes + 15 final_hour = time_plus_15_min // 60 final_min = time_plus_15_min % 60 if final_hour > 23: final_hour = final_hour - 24 if final_min < 10: print(f'{final_hour}:0{final_min}') else: print(f'{final_hour}:{final_min}')
f54b1babee9082eef704f11cbbc8898d89ad7fc3
zdravkob98/Programming-Basics-with-Python-March-2020
/Programing Basics March2020/Simple-Operations-and-Calculations/Yard Greening.py
246
3.859375
4
meters = float(input()) total_price = meters * 7.61 discount = total_price * 0.18 total_price_with_discount = total_price - discount print(f'The final price is: {total_price_with_discount:.2f} lv.') print(f'The discount is: {discount:.2f} lv.')
6e453fc9e069e1039540bef271b37ce8b1b46a8b
zdravkob98/Programming-Basics-with-Python-March-2020
/Programing Basics March2020/Loops - Part 2 - Lab/10. Moving.py
394
3.875
4
width = int(input()) length = int(input()) height = int(input()) packet = 0 space = width * length * height new = input() while new != 'Done': pack = int(new) packet += pack if space < packet: break new = input() if space < packet: print(f'No more free space! You need {packet - space} Cubic meters more.') else: print(f'{space - packet} Cubic meters left.')
0a27a27ce4b4d243298eb238153dbd041b2c1d30
zdravkob98/Programming-Basics-with-Python-March-2020
/Programing Basics March2020/Nested Loops - Exercise2/02. Equal Sums Even Odd Position.py
376
3.875
4
start = int(input()) end = int(input()) for num in range(start, end + 1): num_as_string = str(num) even_sum = 0 odd_sum = 0 for i in range(len(num_as_string)): digit = int(num_as_string[i]) if (i + 1) % 2 == 0: even_sum += digit else: odd_sum += digit if even_sum == odd_sum: print(num , end= ' ')
635c54c51dffa81d2db4c35f4be86924b1afb3c0
zdravkob98/Programming-Basics-with-Python-March-2020
/Programing Basics March2020/Loops - Part 2 - Exercise/demoo.py
369
3.78125
4
import sys goal = 10000 goal_for_day = False while goal > 0: steps = input() if steps != 'Going home': goal -= int(steps) else: goal -= int(input()) if goal> 0 : goal_for_day = False sys.exit() if goal_for_day == False: print(f'{(goal)} more steps to reach goal.') else: print('Goal reached! Good job!')
225068ae9d4fb3c932fce4b360361df5dfa2fed1
zdravkob98/Programming-Basics-with-Python-March-2020
/Programing Basics March2020/Simple-Operations-and-Calculations/Pet Shop.py
288
3.609375
4
dogs_count = int(input()) other_animals_count = int(input()) price_per_dog = 2.5 price_per_animal = 4 dogs_total_price =dogs_count * price_per_dog animal_total_price =other_animals_count*price_per_animal total_price= dogs_total_price + animal_total_price print(f'{total_price:.2f} lv.')
ea3e1ef85941dedae2c43079e5e59cac31e1c645
zdravkob98/Programming-Basics-with-Python-March-2020
/Programing Basics March2020/Loops - Lab/06. Vowels Sum.py
312
3.796875
4
word = input() word_len = len(word) sum = 0 for i in range(0, word_len): letter = word[i] if letter == 'a': sum += 1 elif letter == 'e': sum += 2 elif letter == 'i': sum += 3 elif letter == 'o': sum += 4 elif letter == 'u': sum += 5 print(sum)
19f8719fcb135da11f9745c324a6da5683761126
zdravkob98/Programming-Basics-with-Python-March-2020
/Programing Basics March2020/1/Exam Preparation.py
265
3.625
4
income = float(input()) count_mouth = int(input()) costs = float(input()) another_costs = income * 0.3 saving = income - costs - another_costs total_saving = count_mouth * saving print(f"She can save {(saving / income) * 100:.2f}%") print(f"{total_saving:.2f}")
4514ae4a7ca56012a5bf5e8a645d44249b0ffb21
zdravkob98/Programming-Basics-with-Python-March-2020
/Programing Basics March2020/Programming Basics Online Exam - 28 and 29 March 2020/04. Food for Pets.py
576
3.984375
4
count_days = int(input()) count_food = float(input()) cookies = 0 total_food = 0 dog_food = 0 cat_food = 0 for i in range(1, count_days +1): dog = int(input()) cat = int(input()) if i % 3 == 0: cookies += (dog + cat) * 0.10 total_food += dog + cat dog_food += dog cat_food += cat print(f'Total eaten biscuits: {round(cookies)}gr.') print(f'{(total_food / count_food) * 100:.2f}% of the food has been eaten.') print(f'{dog_food / total_food * 100:.2f}% eaten from the dog.') print(f'{cat_food / total_food * 100:.2f}% eaten from the cat.')
0dcd71b94bc6644c99522c34a0f3e2ba539aa055
msdansie/phys2300_labs
/lab5/michael_dansie_hw5_task1234.py
6,852
3.5625
4
#from vpython import * from math import cos, sin, radians import argparse from matplotlib import pyplot as plt def set_scene(data): """ Set Vpython Scene :param:data-dictionary of collected data """ scene.title = "Assignment 5: Projectile motion" scene.width = 800 scene.heigth = 600 scene.caption = """Right button drag or Ctrl-drag to rotate "camera" to view scene. To zoom, drag with middle button or Alt/Option depressed, or use scroll wheel. On a two-button mouse, middle is left + right. Touch screen: pinch/extend to zoom, swipe or two-finger rotate.""" scene.forward = vector(0, -.3, -1) scene.x = -1 # Set background: floor, table, etc ground = box(pos=vector(0, 0, 0), size=vector(data['distance'] + 15, .05, 15), color=color.green) fence = box(pos=vector(0, (data['max_height']+5)/2, -7.5), size=vector(data['distance'] + 15, data['max_height'] + 5, .05), color=color.white) pillar = cylinder(pos=vector(-(ground.size.x/2)+3,0,0), axis=vector(0, data['init_height'], 0), radius =.5) def motion_no_drag(data): """ Create animation for projectile motion with no dragging force :param:data-dictionary of collected data """ #calculate velocity components velocity_x = cos(radians(data['theta'])) * data['init_velocity'] velocity_y = sin(radians(data['theta'])) * data['init_velocity'] time = 0 #set up the ball ball_nd = sphere(pos=vector((-(data['distance']+15)/2)+3, data['init_height'], 0), radius=data['ball_radius'], color=color.cyan, make_trail=True) # Follow the movement of the ball scene.camera.follow(ball_nd) # Set initial velocity ball_nd.velocity = vector(velocity_x, velocity_y, 0) data['posy_no_drag'] = [data['init_height']] data['posx_no_drag'] = [0] data['time_no_drag'] = [time] # Animate while ball_nd.pos.y > 0: rate(60) ball_nd.pos.x = ball_nd.pos.x + ball_nd.velocity.x * data['deltat'] ball_nd.pos.y = ball_nd.pos.y + ball_nd.velocity.y * data['deltat'] ball_nd.velocity.y = ball_nd.velocity.y + data['gravity'] * data['deltat'] #store the data time = time + data['deltat'] data['posy_no_drag'].append(ball_nd.pos.y) data['posx_no_drag'].append(ball_nd.pos.x + (data['distance']/2) + 5) data['time_no_drag'].append(time) def motion_drag(data): """ Create animation for projectile motion with no dragging force :param:data-dictionary for collected data """ #calculate velocity components velocity_x = cos(radians(data['theta'])) * data['init_velocity'] velocity_y = sin(radians(data['theta'])) * data['init_velocity'] time = 0 #set up the ball ball_nd = sphere(pos=vector((-(data['distance'] + 15)/2)+3, data['init_height'], 0), radius=data['ball_radius'], color=color.orange, make_trail=True) # Follow the movement of the ball scene.camera.follow(ball_nd) # Set initial velocity & position ball_nd.velocity = vector(velocity_x, velocity_y, 0) data['posy_drag'] = [data['init_height']] data['posx_drag'] = [0] data['time_drag'] = [time] # Animate while ball_nd.pos.y > 0: rate(60) #calculate air resistance air_res_x = -.5 * data['rho'] * ball_nd.velocity.x**2 * data['Cd'] * data['ball_area'] air_res_y = -.5 * data['rho'] * ball_nd.velocity.y**2 * data['Cd'] * data['ball_area'] #update position and velocity ball_nd.pos.x = ball_nd.pos.x + ball_nd.velocity.x * data['deltat'] ball_nd.pos.y = ball_nd.pos.y + ball_nd.velocity.y * data['deltat'] ball_nd.velocity.y = ball_nd.velocity.y + (data['gravity'] + air_res_y / data['ball_mass']) * data['deltat'] ball_nd.velocity.x = ball_nd.velocity.x + (air_res_x / data['ball_mass']) * data['deltat'] #store data time = time + data['deltat'] data['posy_drag'].append(ball_nd.pos.y) data['posx_drag'].append(ball_nd.pos.x + (data['distance']/2) + 5) data['time_drag'].append(time) def plot_data(data): """ Plots the collected flight data :param:data-dictionary of collected data """ plt.subplot(2, 1, 1)#First Plot: Height vs. Time plt.plot(data['time_no_drag'], data['posy_no_drag'], label="No Air Resistance") plt.plot(data['time_drag'], data['posy_drag'], label="With Air Resistance") plt.ylabel("Height in meters") plt.title("Flight Position of a Projectile") plt.legend() plt.subplot(2, 1, 2)#Second Plot: Distance vs. Time plt.plot(data['time_no_drag'], data['posx_no_drag'], label="No Air Resistance") plt.plot(data['time_drag'], data['posx_drag'], label="With Air Resistance") plt.ylabel("Distance in meters") plt.xlabel("Time in seconds") plt.legend() plt.show() def main(): """ Parses the input, plots the projectile motion, and display data """ # 1) Parse the arguments parser = argparse.ArgumentParser(description="Projectile Motion Demo") parser.add_argument("--velocity", action = "store", dest = "velocity", type = float, required=True, help = "--velocity 20 (in m)") parser.add_argument("--angle", action = "store", dest = "angle", type = float, required=True, help = "--angle 45 (in degrees)") parser.add_argument("--height", action = "store", dest = "height", type = float, default = 1.2, help = "--height 1.2 (in m)") args = parser.parse_args() # Set Variables data = {} # empty dictionary for all data and variables data['init_height'] = args.height # y-axis data['init_velocity'] = args.velocity # m/s data['theta'] = args.angle # degrees # Constants data['rho'] = 1.225 # kg/m^3 data['Cd'] = 0.5 # coefficient friction data['deltat'] = 0.005 data['gravity'] = -9.8 # m/s^2 data['ball_mass'] = 0.145 # kg data['ball_radius'] = 0.075 # meters data['ball_area'] = pi * data['ball_radius']**2 data['alpha'] = data['rho'] * data['Cd'] * data['ball_area'] / 2.0 data['beta'] = data['alpha'] / data['ball_mass'] data['distance'] = (data['init_velocity']**2 * sin(radians(2*data['theta']))) / (-1*data['gravity'])#calculate the flight distance data['max_height'] = (data['init_velocity']**2 * sin(radians(data['theta'])**2))/(-2*data['gravity'])#calculate max height # Set Scene set_scene(data) # 2) No Drag Animation motion_no_drag(data) # 3) Drag Animation motion_drag(data) # 4) Plot Information: extra credit plot_data(data) if __name__ == "__main__": main() exit(0)
fbd69540d6ecb9b6d4c3cc1e472d6e09f2053fbb
henaege/class-rpg
/skeleton.py
1,015
3.609375
4
from random import randint class Skeleton(object): def __init__(self): self.health = 13 self.power = 6 self.armor_class = 13 self.name = "Skeleton" self.xp_value = 8 def __repr__(self): return self.name def is_alive(self): if self.health > 0: return True else: return False def attack_hero(self, hero): self.attack = randint(1, 19) self.temp_power = (randint(1, 7) + 2) print ("The Skeleton is attacking!\n") if self.attack >= hero.armor_class: hero.health -= self.temp_power print ("The %s hit %s and did %d damage!\n" % (self.name, hero.name, self.temp_power)) print ("%s now has %d health.\n" % (hero.name, hero.health)) if hero.health <= 0: print ("""%s has been killed by a %s.\nthe quest has failed.""" % (hero.name, self.name)) else: print ("The %s missed its attack!\n" % (self.name))
702bcebc5eaab5cf93b141e802d4ce2679c39b7d
ks93/ComputationalPhysicsProjects
/Project1/src/utils/gauss_elim.py
1,934
3.90625
4
""" Implementations of Gaussian elimination. """ import numpy as np def gaussian_elimination(A, b): """General Gaussian elimination. Solve Av = b, for `v`. `A` is a square matrix with dimensions (n,n) and `b` has dim (n,) Parameters ---------- A : np.ndarray (n,n) matrix b : np.ndarray (n,) RHS of linear equation set. Returns ------- np.ndarray The solution `v` for Av = b. """ n = len(b) # Join A and b ab = np.c_[A,b] # Gaussian Elimination for i in range(n-1): if ab[i,i] == 0: raise ZeroDivisionError('Zero value in matrix..') for j in range(i+1, n): ratio = ab[j,i] / ab[i,i] for k in range(i, n+1): ab[j,k] = ab[j,k] - ratio * ab[i,k] # Backward Substitution X = np.zeros((n,1)) X[n-1,0] = ab[n-1,n] / ab[n-1,n-1] for i in range(n-2,-1,-1): knowns = ab[i, n] for j in range(i+1, n): knowns -= ab[i,j] * X[j,0] X[i,0] = knowns / ab[i,i] return X def gaussian_elimination_special_case(b): """Gaussian elimination specialised for solving Av = b, where `A` is a tridiagonal matrix where all elements on the diagonal are 2, and the elements on the adjacent "diagonal" are -1. Parameters ---------- b : np.ndarray The response Returns ------- np.ndarray The solution `v` for Av = b. """ n = len(b) # init new (prime) arrays beta_prime = np.empty(n) beta_prime[0] = 2 b_prime = np.empty(n) b_prime[0] = b[0] v = np.empty(n) i_array = np.arange(n) beta_prime = (i_array+2) / (i_array+1) for i in range(1,n): b_prime[i] = b[i] + (b_prime[i-1] / beta_prime[i-1]) v[-1] = b_prime[-1] / beta_prime[-1] for i in range(n-2, -1, -1): v[i] = (b_prime[i] + v[i+1])/ beta_prime[i] return v
ba7c65a7484d8eb81ba071864c60651ca6b97af2
christianparizeau/DailyCodeProblems
/daily3.py
467
3.890625
4
# Given an array of integers, find the missing positive integer in constant space. In other words, find the lowest positive integer that does not exist in the array. # The array can contain duplicates and negative numbers as well. #Should return 3. Question asks to do this in linear time, but that is beyond me array = [0,1,43,-4,2] def finder(array): setOfArray = set(array) i=1 while i in setOfArray: i += 1 return i print(finder(array))
94e48d810d2d77f72580bcefd39776cfe16d0ca2
Rupali0311/CNN
/CNN_adjusted.py
1,924
3.6875
4
import multiprocessing as mp from multiprocessing import Process import sys from CNN import CNN class CNN_adjusted: """ This class can be substituted by the CNN class in the code whenever the used GPU card has enough memory to save multiple instances of the data. If not (in our case for example a GPU card with 2gb) a process needs to be simulated to be able to terminate it after every iteration as tensorflow will not wipe the GPU memory automatically until the full code is done running. """ def model(self, model_params, return_dict, train_data, validation_data): """ This functions builds the CNN based on the provided parameters :param model_params: The parameters that have to be used for the model :param return_dict: A dictionary in which the results should be saved :return: results in a dictionary """ model = CNN(**model_params) output = model.train_neural_network(train_data, validation_data,output_folder= 'data/temp/', return_output = True) return_dict['data'] = output def run_model(self, model_params, train_data, validation_data): """ This function start a process and terminates its afterwards to clean the GPU memory for the next iteration. :param model_params: The parameters that have to be used for the model :return: The data returned by the CNN model """ manager = mp.Manager() return_dict = manager.dict() p = Process(target=self.model, args=(model_params, return_dict, train_data, validation_data)) jobs = [p] p.start() for job in jobs: job.join() p.terminate() if return_dict: return return_dict['data'] else: print('[ERROR] Could not finish the process') sys.exit(1)
014dfab260bca2ad832bffed3def9f4d6504eca8
TheRealDarkWolf/Amazoff
/readTables.py
851
3.59375
4
import sqlite3 conn = sqlite3.connect("Online_Shopping.db") cur = conn.cursor() ''' prodID = "PID0000003" cur.execute("SELECT category FROM product where prodID = ? ", (prodID,)) print(cur.fetchall()[0][0]) # cur.execute("SELECT prodID FROM product WHERE sellID = {}".format(sellID)) ''' cur.execute("SELECT name FROM sqlite_master WHERE type='table';") tables = cur.fetchall() for i in tables: print(i[0]) cur.execute("PRAGMA table_info({})".format(i[0])) for j in cur.fetchall(): print(j[1], end = "\t") print() cur.execute("SELECT * FROM {}".format(i[0])) for k in cur.fetchall(): for l in k: print(l, end = "\t") print() print() print() ''' cur.execute("SELECT * FROM product WHERE category='Electronics and Tech'") print(cur.fetchall()) '''
8a62c17fa130f29883a0e16d113711c7531e436a
JaxWLee/CodingDojoAssignments
/Python/Python_1/Intro/coin_tosses.py
508
3.640625
4
def coin_tosses(): import random heads = 0 tails = 0 for i in range(0,5000): x = random.random() x = round(x) if x == 1: heads += 1 print "Attempt #"+str(i+1)+" Coin is tossed.... Its a heads.... Got "+str(heads)+" heads and "+str(tails)+" tails so far" if x == 0: tails += 1 print "Attempt #"+str(i+1)+" Coin is tossed.... Its a tails.... Got "+str(heads)+" heads and "+str(tails)+" tails so far" coin_tosses()
d8f4104a62515dea59d865ccc527764df35054b6
JaxWLee/CodingDojoAssignments
/Python/Python_1/Intro/scores_grades.py
487
3.875
4
def scores_grades(num): print "Scores and Grades:" import random for i in range(0,num): x = random.random()*40+60 x = round(x,0) if x < 70: print "Score: "+str(x)+"; Your grade is D" elif x < 80: print "Score: "+str(x)+"; Your grade is C" elif x < 90: print "Score: "+str(x)+"; Your grade is B" elif x <= 100: print "Score: "+str(x)+"; Your grade is A" scores_grades(10)
cb95a6ac5fdb278dfafbddad2d363fe72ff932a3
JaxWLee/CodingDojoAssignments
/Python/Python_1/Intro/finding_characters.py
442
3.84375
4
def find_characters(str_list,char): x = len(str_list) new_list = [] for count in range(0,x): y = str_list[count] z = len(y) zz = count for count in range(0,z): if y[count] == char: new_list.append(str_list[zz]) break print new_list word_list = ['hello','world','my','name','is','Anna','onomonpia'] char = 'o' find_characters(word_list,char)
10df4aff647a659adfd4adcee91974a0967771cd
JaxWLee/CodingDojoAssignments
/Python/Python_1/Intro/compairing_lists.py
1,018
3.875
4
def compare_List(list_one,list_two): x = len(list_one) y = len(list_two) z = 0 if x != y: print "The lists are not the same" elif x==y: for count in range (0,x): if list_one[count] == list_two[count]: z = z + 1 elif list_one[count]!= list_two[count]: z = z + 0 if z == x: print "The lists are the same" elif z != x: print "The lists are not the same" list_one = [1,2,5,6,2] list_two = [1,2,5,6,2] compare_List(list_one,list_two) list_one = [1,2,5,6,5] list_two = [1,2,5,6,5,3] compare_List(list_one,list_two) list_one = [1,2,5,6,5,16] list_two = [1,2,5,6,5] compare_List(list_one,list_two) list_one = ['celery','carrots','bread','milk'] list_two = ['celery','carrots','bread','cream'] compare_List(list_one,list_two) list_one = ['celery','carrots','bread','milk'] list_two = ['celery','carrots','bread','milk'] compare_List(list_one,list_two)
9c00dde9e8736299e0579063547ff7e4d956e75b
s15011/algorythm_design_pattern
/algorythm/sort.py
4,104
3.609375
4
#!/usr/bin/python3 LIST_COUNT = 1000 LOOP_COUNT = 1000 MAX_NUM = 10000 def data_generate(): import random return [random.randint(1, MAX_NUM) for _ in range(LIST_COUNT)] def selection_sort(data): for i in range(len(data) - 1): minimum = i for t in range(i + 1, len(data)): if data[minimum] > data[t]: minimum = t data[i], data[minimum] = data[minimum], data[i] def bubble_sort(data): for i in range(len(data)): for t in range(1, len(data) - 1): if data[t] < data[t - 1]: data[t], data[t - 1] = data[t - 1], data[t] def insertion_sort(data): for i in range(1, len(data)): tmp = data[i] if data[i - 1] > tmp: j = i while j > 0 and data[j - 1] > tmp: data[j] = data[j - 1] j -= 1 def shell_sort(data): gap = len(data) // 2 while gap > 0: for i in range(gap, len(data)): tmp = data[i] j = i - gap while j >= 0 and tmp < data[j]: data[j + gap] = data[j] j -= gap data[j + gap] = tmp gap //= 2 def merge_sort(data): mid = len(data) if mid == 1: return data left = merge_sort(data[:(mid//2)]) right = merge_sort(data[(mid//2):]) left = merge_sort(left) right = merge_sort(right) array = [] while len(left) != 0 and len(right) != 0: if left[0] < right[0]: array.append(left.pop(0)) else: array.append(right.pop(0)) if len(left) !=0: array.extend(left) elif len(right) !=0: array.extend(right) return array def quick_sort(data): if len(data) < 1: return data pivot = data [0] if len( data) > 2: pivot = data[ 0] if data[ 0] < data[ 1] else data[ 1] left = [] right = [] for x in range(1, len(data)): if data[x] <= pivot: left.append(data[x]) else: right.append(data[x]) left = quick_sort(left) right = quick_sort(right) return left + [pivot] + right if __name__=='__main__': import time import sys """ start = time.time() for _ in range(LOOP_COUNT): data = data_generate() selection_sort(data) print('.', end='') sys.stdout.flush() end = time.time() print() print('経過時間:', (end-start)) print('平均時間:', ((end-start) / LOOP_COUNT)) """ """ start = time.time() for _ in range(LOOP_COUNT): data = data_generate() bubble_sort(data) [print('.', end='') if _ % 100 != 99 else print(int(_ / 100 + 1))] sys.stdout.flush() end = time.time() print() print('経過時間:', (end-start)) """ """ start = time.time() for _ in range(LOOP_COUNT): data = data_generate() insertion_sort(data) [print('.', end='') if _ % 100 != 99 else print(int(_ / 100 + 1))] sys.stdout.flush() end = time.time() print() print('経過時間:', (end-start)) """ """ start = time.time() for _ in range(LOOP_COUNT): data = data_generate() shell_sort(data) [print('.', end='') if _ % 100 != 99 else print(int(_ / 100 + 1))] sys.stdout.flush() end = time.time() print() print('経過時間:', (end-start)) """ """ start = time.time() for _ in range(LOOP_COUNT): data = data_generate() merge_sort(data) [print('.', end='') if _ % 100 != 99 else print(int(_ / 100 + 1))] sys.stdout.flush() end = time.time() print() print('経過時間:', (end-start)) """ start = time.time() for _ in range(LOOP_COUNT): data = data_generate() quick_sort(data) [print('.', end='') if _ % 100 != 99 else print(int(_ / 100 + 1))] sys.stdout.flush() end = time.time() print() print('経過時間:', (end-start)) print('平均時間:', ((end-start) / LOOP_COUNT))