blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
d5a5865ba7093b98233327b3f159751422511629
frollo/AdvancedProgramming
/Lab-4/es2.py
1,097
3.6875
4
class SocialNode(object): def __init__(self, name): self.name = name self.connections = list() def addConnection(self, tag, other): self.connections.append((tag, other)) other.connections.append((tag, self)) def __visit__(self, visited=None): if visited is None: visited = set() visited.add(self) toVisit = [x[1] for x in self.connections if x[1] not in visited] for friend in toVisit: if friend not in visited: visited = visited.union(friend.__visit__(visited)) return visited def __str__(self): visited = self.__visit__() string = "" for v in visited: friends = ["\t{0} with {1}\n".format(x[0], x[1].name) for x in v.connections] string = string + v.name + ":\n" + "".join(friends) return string if __name__ == '__main__': lollo = SocialNode("Lorenzo Rossi") marco = SocialNode("Marco Odore") luca = SocialNode("Luca Rossi") lollo.addConnection("works", marco) lollo.addConnection("friend", luca) print(lollo)
67fcb010226731a071c51b6b0e59f254eaf7a106
frollo/AdvancedProgramming
/exams/2015-06-16/quickrecursion.py
903
3.875
4
def memoization(fun): past_values = dict() def wrapper (*args): if args in past_values: print ("### cached value for {0} --> {1}".format(args, past_values[args])) else: past_values[args] = fun(*args) return past_values[args] return wrapper @memoization def fibo(n): if n < 3: return 1 return fibo(n - 1) + fibo(n-2) @memoization def fact(n): if n < 2: return 1 return n * fact(n-1) @memoization def sum(n,m): if n == 0: return m return sum(n - 1, m + 1) if __name__ == '__main__': print("fibo({0}) --> {1}".format(25, fibo(25))) for x in range(1,25): print("fact({0}) --> {1}".format(x, fact(x))) print("sum({0}, {1}) --> {2}".format(5, 9, sum(5,9))) print("sum({0}, {1}) --> {2}".format(4, 10, sum(4,10))) print("sum({0}, {1}) --> {2}".format(13,1, sum(13,1)))
97fbde95357d10d54ef0533a0a2ea5b8ac4086e7
ninnin92/Pyworks
/auto_analysis/days to age.py
3,286
3.78125
4
#!/usr/bin/env # -*- coding: utf-8 -*- import pandas as pd from datetime import date, timedelta, datetime ################################################ # 宣言 ################################################ s_data = pd.read_csv("subject_age.csv") ################################################ # 処理関数 ################################################ # 年齢の計算(閏日補正含む) :今何歳何ヶ月なのか? def count_years(b, s): try: this_year = b.replace(year=s.year) except ValueError: b += timedelta(days=1) this_year = b.replace(year=s.year) age = s.year - b.year if s < this_year: age -= 1 # 何歳”何ヶ月”を計算 if (s.day - b.day) >= 0: year_months = (s.year - b.year) * 12 - age * 12 + (s.month - b.month) else: year_months = (s.year - b.year) * 12 - age * 12 + (s.month - b.month) - 1 # 誕生日が来るまでは月齢も-1 return age, year_months # 月齢の計算 def count_months(b, s): if (s.day - b.day) >= 0: months = (s.year - b.year) * 12 + (s.month - b.month) else: months = (s.year - b.year) * 12 + (s.month - b.month) - 1 # 誕生日が来るまでは月齢も-1 return months # 月齢および何歳何ヶ月の余り日数(何歳何ヶ月”何日”) def count_days(b, s): if (s.day - b.day) >= 0: days = s.day - b.day else: try: before = s.replace(month=s.month - 1, day=b.day) days = (s - before).days except ValueError: days = s.day # 2月は1ヶ月バックするとエラーになる時がある(誕生日が29-31日の時) # なのでそうなった場合は、すでに前月の誕生日を迎えたことにする(setされた日が日数とイコールになる) return days ################################################ # メイン処理 ################################################ if __name__ == '__main__': a_months = [] a_days = [] a_details = [] for i in range(0, len(s_data)): try: base = s_data.iloc[i, :]["days"] base = datetime.strptime(str(base), "%Y/%m/%d") base_day = date(base.year, base.month, base.day) birth = s_data.iloc[i, :]["birthday"] birth = datetime.strptime(str(birth), "%Y/%m/%d") bir_day = date(birth.year, birth.month, birth.day) print(base_day, bir_day) age = str(count_years(bir_day, base_day)[0]) age_year_months = str(count_years(bir_day, base_day)[1]) age_days = str(count_days(bir_day, base_day)) age_months = str(count_months(bir_day, base_day)) age_in_days = str((base_day - bir_day).days) age_details = age + "y " + age_year_months + "m " + age_days + "d" except: age_months = "NA" age_in_days = "NA" age_details = "NA" a_months.append(age_months) a_days.append(age_in_days) a_details.append(age_details) s_data = s_data.assign(age_days=a_days, age_months=a_months, age_details=a_details) s_data.to_csv("result_subjects_age.csv", index=False)
6d16dd48bab98affcb0df5e64cd1158e846b1e57
foundjem/COMP551-Applied-Machine-Learning
/Project 3/Code/train_test_LR_SVM_NN_raw_pixels.py
1,872
3.53125
4
# -*- coding: utf-8 -*- ''' Perform Logistic Regression, SVM and feed-forward neural network using raw pixel values on the test data ''' import sklearn import numpy as np import scipy.misc # to visualize only from scipy import stats from sklearn.decomposition import PCA as sklearnPCA from sklearn.feature_selection import SelectKBest from sklearn.neural_network import MLPClassifier from sklearn.feature_selection import chi2 from sklearn import svm, linear_model, naive_bayes from sklearn import metrics import math x = np.fromfile('train_x.bin', dtype='uint8') x = x.reshape((100000,60,60)) y = np.genfromtxt("train_y.csv", delimiter=",", dtype= np.float64) y = y[1:100001,1] unfolded_data = x.reshape(100000,3600) test = np.fromfile('test_x.bin', dtype='uint8') test = test.reshape((20000,60,60)) x_flat = x.reshape(100000,3600) test_flat = test.reshape(20000,3600) x_train = unfolded_data y_train = y x_test = test_flat """ Logistic Regression """ logreg = linear_model.LogisticRegression(C=1e5) print "Training Logistic Regression" logreg.fit(x_train,y_train) print "Testing Logistic Regression" predicted_logreg = logreg.predict(x_test) np.savetxt("predicted_logreg_raw_pixels.csv",predicted_logreg, delimiter =",") """ SVM """ sv = svm.SVC() print "Training SVM" sv.fit(x_train,y_train) print "Testing SVM" predicted_svm = sv.predict(x_test) np.savetxt("predicted_svm_raw_pixels.csv",predicted_svm, delimiter =",") """ Neural Network """ print "Training Neural Network" clf = MLPClassifier(solver='adam', alpha=1e-5, hidden_layer_sizes=(10,10), random_state=1, tol=0.0000000001, max_iter=100000) clf.fit(x_train,y_train) print "Testing Neural Network" predicted_nn = clf.predict(x_test) np.savetxt("predicted_nn_raw_pixels.csv",predicted_nn, delimiter =",")
e0a5afb486454fc6def28ed6c5bb593528bcd246
foundjem/COMP551-Applied-Machine-Learning
/Project 3/Code/train_test_LR_SVM_NN_Daisy.py
2,580
3.5
4
# -*- coding: utf-8 -*- ''' Perform Logistic Regression, SVM and feed-forward neural network using Daisy features on the test data ''' import sklearn import numpy as np import scipy.misc # to visualize only from scipy import stats from sklearn.decomposition import PCA as sklearnPCA from sklearn.feature_selection import SelectKBest from sklearn.neural_network import MLPClassifier from sklearn.feature_selection import chi2 from sklearn import svm, linear_model, naive_bayes from sklearn import metrics import math import matplotlib.pyplot as plt import skimage from skimage.feature import hog from skimage import data, color, exposure from skimage.feature import daisy x = np.fromfile('train_x.bin', dtype='uint8') x = x.reshape((100000,60,60)) y = np.genfromtxt("train_y.csv", delimiter=",", dtype= np.float64) y = y[1:100001,1] test = np.fromfile('test_x.bin', dtype='uint8') test = test.reshape((20000,60,60)) print "Daisy: Saving features' loop for train" daisy_features_train_set = np.zeros((len(x),104)) for i in range(len(x)): descs, descs_img = daisy(x[i], step=180, radius=20, rings=2, histograms=6, orientations=8, visualize=True) daisy_features_train_set[i] = descs.reshape((1,104)) print "Daisy: Saving features' loop for test" daisy_features_test_set = np.zeros((len(test),104)) for i in range(len(test)): descs, descs_img = daisy(test[i], step=180, radius=20, rings=2, histograms=6, orientations=8, visualize=True) daisy_features_test_set[i] = descs.reshape((1,104)) x_train = daisy_features_train_set y_train = y x_test = daisy_features_test_set """ Logistic Regression """ logreg = linear_model.LogisticRegression(C=1e5) print "Training Logistic Regression" logreg.fit(x_train,y_train) print "Testing Logistic Regression" predicted_logreg = logreg.predict(x_test) np.savetxt("predicted_logreg_daisy.csv",predicted_logreg, delimiter =",") """ SVM """ sv = svm.SVC() print "Training SVM" sv.fit(x_train,y_train) print "Testing SVM" predicted_svm = sv.predict(x_test) savetxt("predicted_logreg_daisy.csv",predicted_svm, delimiter =",") """ Neural Network """ print "Training Neural Network" clf = MLPClassifier(solver='adam', alpha=1e-5, hidden_layer_sizes=(10,10), random_state=1, tol=0.0000000001, max_iter=10000) clf.fit(x_train,y_train) print "Testing Neural Network" predicted_nn = clf.predict(x_test) savetxt("predicted_logreg_daisy.csv",predicted_nn, delimiter =",")
2c4ac0b414a5644612b8c956b253d40c6329b94b
PeterPZhang/CrossRiver
/CrossRiver.py
6,117
3.53125
4
edgeFlag1=True #河岸标识符现在在A岸 edgeFlag2=False#河岸标识符 与上面一样 用这两个就可以表示船 sheep1=[1,1,1]#河岸A的羊 sheep2=[]#河岸B的狼 wolf1=[1,1,1]#河岸A的狼 wolf2=[]#河岸B的狼 GameFlag=True#游戏开始标志 edge1="A"#用来识别A岸 edge2="B"#用来识别B岸 step=0 winner_list=[] winner={} def oprate(SheepA, SheepB, WolfA, WolfB,EdgeFlag1,EdgeFlag2):#键入操作进行游戏 global edgeFlag1,edgeFlag2,step for i in range(2): op=input("请输入你的操作:") push(op,SheepA,SheepB,WolfA,WolfB)#对当前操作进行操作 # judge(EdgeFlag1,SheepA,SheepB,WolfA,WolfB)#判断对岸状态 # EdgeFlag1=False #判断完置反 表示船走了 # EdgeFlag2=True edgeFlag1 = not EdgeFlag1 edgeFlag2 = not EdgeFlag2 step += 1 return def push (Op,SheepA,SheepB,WolfA,WolfB): if Op =="S": #输入S进行操作 SheepA.pop() #当前河岸S-1 SheepB.append(1)#对岸+1 return elif Op=="W": WolfA.pop() WolfB.append(1) return elif Op=="N":#可以不上元素返回 return def judge(SheepA,WolfA,SheepB,WolfB): global GameFlag if (len(SheepA)<len(WolfA) or len(SheepB)<len(WolfB)) and len(SheepA)!=0 and len(SheepB)!=0 : print("你输了") GameFlag=False elif len(SheepA)==0 and len(WolfA)==0: print("你赢了") fo = open("winners.txt", "a", encoding="UTF-8") winner["姓名:"]=input("请输入你的姓名:") winner["步数"]=step fo.write(winner) fo.close() fo = open("winners.txt","r+",encoding="UTF-8") winner_list=fo.readlines() winner_list.sort(key="步数") for onewinner in winner_list: fo.write(onewinner) fo.close() GameFlag=False else: print("请继续") return # def iscontinue(edge,list): # if edege # if list.length==0: # print("此岸已没有可操作的了") # else: # return def show(EdgeFlag1,EdgeFlag2,Edge1,Edge2,Sheep1,Sheep2,Wolf1,Wolf2): print("当前状态是:") for wolf in wolf1: print(""" * * * * ** * ** * ** *********** ** **************** ****************** * * * * * * * * * * * * * * * * * * """) for sheep in sheep1: print(""" * * ************ **** ******************* ** *** ********************** ** *** ************************* ********************** ****************** * * *********** * * * * * * """) print("河岸%s有%d只羊%d只狼" % (Edge1, len(Sheep1), len(Wolf1))) print("______________________________________________________") for wolf in wolf2: print(""" * * * * ** * ** * ** *********** ** **************** ****************** * * * * * * * * * * * * * * * * * * """) for sheep in sheep2: print(""" * * ************ **** ******************* ** *** ********************** ** *** ************************* ********************** ****************** * * *********** * * * * * * """) print("河岸%s有%d只羊%d只狼" % (Edge2, len(Sheep2), len(Wolf2))) if(EdgeFlag1==True): print("""现在船在 A岸""") elif (EdgeFlag2==True): print("""现在船在 B岸""") def main(): print("""欢迎进入狼羊过河游戏 游戏规则:现在在河岸A有3只羊和3只狼要都过河,但是河岸边只有一艘小船,小船自多只能承载两个单位,且必须至少有一个单位在船上时小船才会开动。 当船两岸任意一岸的羊的数量小于狼的数量时,羊就会被吃掉游戏失败。怎样做才能让所有的羊和狼都过河呢? 操作提示: S:让此岸的羊上船 W:让此岸的狼上船 N:不上船""") fo = open("winners.txt", "ab+") fo.close() show(edgeFlag1, edgeFlag2, edge1, edge2, sheep1, sheep2, wolf1, wolf2) while GameFlag == True: print("步数:%d"%step) if edgeFlag1==True: oprate(sheep1, sheep2, wolf1, wolf2,edgeFlag1,edgeFlag2) judge(sheep1,wolf1,sheep2,wolf2) elif edgeFlag2==True: oprate(sheep2, sheep1, wolf2, wolf1,edgeFlag1,edgeFlag2) judge(sheep1,wolf1,sheep2,wolf2) show(edgeFlag1,edgeFlag2,edge1, edge2, sheep1, sheep2, wolf1, wolf2) main() print(edgeFlag1)
b32fa0aa5cf1525a58af1887b5616554f97b767f
atanasbozhinov/simple_2d_array_operations
/core/matrix_operations.py
480
3.546875
4
import numpy as np def append(input_x, input_y): try: output = np.append(input_x, input_y, axis=0) except ValueError: return None return output def combine(input_x, input_y): try: output = np.append(input_x, input_y, axis=1) except ValueError: return None return output def sum(input_x, input_y): if not (input_x.shape == input_y.shape): return None output = np.add(input_x, input_y) return output
dec49accb05722be663a3b935e948db291948826
lerrigatto/algo2
/src/lesson7/bfs.py
1,014
3.6875
4
# Implement DFS algorithm import networkx as nx import random def bfs(G,u): """ Breath First Search """ visited = [] visited_edges = [] walk = [] visited.append(u) walk.insert(0,u) while len(walk) > 0: v = walk.pop() adj = G.successors(v) print(f"v:{v}, adj:{list(G.successors(v))}") if adj: for w in adj: if w not in visited: visited.append(w) visited_edges.append((v,w)) walk.insert(0,w) else: print(f"else") walk.pop() return visited_edges def main(): nodes = [0, 1, 2, 3] edges = [(0, 1), (1, 0), (0, 2), (2, 1), (3, 0), (3, 1)] #G = nx.DiGraph(edges) # Generate random complete graph G = nx.gn_graph(100) root = random.randint(0,100) my_visit = bfs(G, root) good_visit = list(nx.bfs_edges(G,source=root)) print(f"My visit: {my_visit}") print(f"Good visit: {good_visit}") main()
77b80551538eb2521a2244e396b166336b6bff7d
lerrigatto/algo2
/src/es07-bt/es0708.py
1,277
3.75
4
# Dato n, si stampino tutte le matrici di interi n x n tali che # le righe e le colonne della matrice siano in ordine crescente def print_matr(M): for line in M: print(''.join(str(line))) print("---") def stampa_bt(n, M, i=0, j=0, c=0): if i == n: print_matr(M) return else: if c>0: M[i][j] = c # Controllo se sono a fine riga if j < n -1: stampa_bt(n,M,i,j+1) else: stampa_bt(n,M,i+1,0) else: for x in range(1,n+2): # Nella posizione 0,0 non ho vicini da controllare if i==0 and j==0: stampa_bt(n,M,i,j,x) order = True # Controllo prima riga, ogni colonna if i == 0 and j>0: order &= M[i][j-1] <= x # Controllo riga e colonna centrali if i>0 and j>0: order &= M[i-1][j] <= x and M[i][j-1] <= x # Controllo prima colonna if i>0 and j==0: order &= M[i-1][j] <= x and M[i][j+1] <= x if order: stampa_bt(n,M,i,j,x) n=2 M = [[0] * n for _ in range(n)] stampa_bt(n, M)
9ce0934bfba140a3fef6e1f11dba2817a7d120f0
SwapnaSubbagari/python-challenge
/PyBank/main.py
1,793
3.625
4
import os import csv import pandas as pd datapath = os.path.join('Resources','budget_data.csv') #Opening the file with open(datapath) as budget_data_file: df = pd.read_csv(datapath, usecols = ['Date','Profit/Losses']) #Calculating unique list of Months and count of Months unique_TotalMonths = df['Date'].unique() Number_Total_Months= pd.value_counts(unique_TotalMonths).count() #Calculating Total Amount of Profits/Losses Net_Total_Amount= df['Profit/Losses'].sum() PL_Amount = df['Profit/Losses'] #Calculating the difference in Profit and Loss Amount Change = df['Profit/Losses'].diff() result={"Date":unique_TotalMonths,"Profit/Losses":PL_Amount, "Difference/Change":Change} result_df=pd.DataFrame(result) result_df = result_df.set_index("Difference/Change") #Calculating values using functions Max,Min,Mean and retreiving the dates using loc. Max_Change=Change.max().__round__() Min_Change=Change.min().__round__() Average_Change=Change.mean().__round__(2) Greatest_Increase_Month=result_df.loc[Max_Change,"Date"] Greatest_Decrease_Month=result_df.loc[Min_Change,"Date"] #Writing Output to text file and terminal with open("Analysis\PyBank_Output_textfile.txt", 'x') as f: f.write("Financial Analysis"+'\n') f.write("----------------------------------"+'\n') f.write("Total Months: " +str(Number_Total_Months)+'\n') f.write("Total: $" +str(Net_Total_Amount)+'\n') f.write("Average Change: $" +str(Average_Change)+'\n') f.write("Greatest Increase in Profits: " +Greatest_Increase_Month+ " ($"+str(Max_Change)+")"'\n') f.write("Greatest Decrease in Profits: " +Greatest_Decrease_Month+ " ($"+str(Min_Change)+")"'\n') f.close() #Reading Output from text file with open("Analysis\PyBank_Output_textfile.txt", "r") as f: print(f.read())
fa3cf86e4519a406c8de6544c9acac1c0e6a3813
tahabroachwala/lists
/DigitsReturn.py
256
4.03125
4
# Write a function that takes a number and returns a list of its digits. # So for 2342 it should return [2,3,4,2]. def returnDigits(num): num_string = str(num) num_list = [int(i) for i in num_string] return num_list print(returnDigits(2432))
f4890460ff11e22734a6fbd86de168a5c28f5ba9
tahabroachwala/lists
/BubbleSort.py
314
4.03125
4
def bubbleSort(list1): for passnum in range(len(list1) - 1, 0, -1): for i in range(passnum): if list1[i] > list1[i+1]: list1[i], list1[i+1] = list1[i+1], list1[i] else: continue list1 = [54,26,93,17,77,31,44,55,20] bubbleSort(list1) print(list1)
e7c0cc03577d1dee49c6618f998312af4d18aa84
abbeychrystal/CodingDojo_PythonRepo
/pythonFeb2021/python_fundamentals/for_loop_basic1.py
1,159
4.09375
4
# Basic - Print all integers of 5 from 5-1000 for i in range(0, 151, 1): print(i) # Multiples of Five - Print all the multiples of 5 from 5 to 1,000 for i in range(5, 1001, 5): print(i) # Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If divisible by 10, print "Coding Dojo". for i in range( 1, 101, 1): if i%5 == 0: print("Coding") else: print(i) # Whoa. That Sucker's Huge - Add odd integers from 0 to 500,000, and print the final sum. count = 0 for i in range(1, 500001): if i%2 != 0: count = count + i print(count) # Countdown by Fours - Print positive numbers starting at 2018, counting down by fours. for i in range (2018, -1, -4): print(i) # Flexible Counter - Set three variables: lowNum, highNum, mult. Starting at lowNum and going through highNum, print only the integers that are a multiple of mult. For example, if lowNum=2, highNum=9, and mult=3, the loop should print 3, 6, 9 (on successive lines) def flexCount(lowNum, highNum, mult): for i in range(lowNum, highNum+1): if i%mult ==0: print(i) flexCount(2,9,3)
4e1a29434d93da6c303babfbfb477f5cd0ac6ecf
abbeychrystal/CodingDojo_PythonRepo
/_python/OOP/INtroOOPnotes.py
5,581
4.6875
5
# As almost all applications revolve around users, almost all applications define a User class. Say we have been contracted to build a banking application. The information we need about a user for a banking application would be different than what we would need if we were building a social media application. If we allowed each user to decide what information they wanted to provide to us, you can imagine how difficult it would be to sift through and utilize that information. Instead, we design a class on the backend that will dictate what information the user is required to provide. This ensures consistent creation of User instances. # Here's the syntax for creating a class that we want to call User: class User: pass # we'll fill this in shortly # And here's how we create a new instance of our class: michael = User() anna = User() # We can flesh out the User class with: # Attributes: Characteristics shared by all instances of the class type. # Methods: Actions that an object can perform. A user, for example, should be able to make a deposit or a withdrawal, or maybe send money to another user. # Let's start building our User class by adding attributes. Again, attributes are characteristics of an object. For example, in our banking application, we may be interested in their name, email, and account balance. Attributes are defined in a "magic method" called __init__, which method is called when a new object is instantiated. class User: # declare a class and give it name User def __init__(self): #First and required parameter is always 'self' self.name = "Michael" # add in whatever attributes are required/desired self.email = "michael@codingdojo.com" self.account_balance = 0 # The first parameter of every method within a class will be self, and the class's attribute names are also indicated by self.. We'll talk more about self later, but for now just follow this pattern: self.<<attribute_name_of_your_choosing>>. # Then to instantiate a couple of new users: guido = User() monty = User() # If we want to access our instance's attributes, we can refer to them from our instances by name: print(guido.name) # output: Michael print(monty.name) # output: Michael # While we definitely want every user to have a name, email, and account balance, we don't want all of our users to have the same name and email address upon creation. How will we know what the name should be? # With the __init__ method's parameters, we indicate what needs to be provided (i.e. arguments) when the class is instantiated. (self is always passed in implicitly.) # In our example, even though we have 3 attributes, we only require input for 2 of them. When the User instance is created, we should expect to receive specific values for the name and email address. We'll assume, however, that everyone starts with $0 in their account. Let's adjust our code to allow arguments to be passed in upon instantiation: class User: def __init__(self, username, email_address):# now our method has 2 parameters! self.name = username # and we use the values passed in to set the name attribute self.email = email_address # and the email attribute self.account_balance = 0 # the account balance is set to $0, so no need for a third parameter # Now when we want to create users, we must send in the 2 required arguments: guido = User("Guido van Rossum", "guido@python.com") monty = User("Monty Python", "monty@python.com") print(guido.name) # output: Guido van Rossum print(monty.name) # output: Monty Python # Now it's time to add some functionality to our class. Methods are just functions that belong to a class. This means that we can't call them independently as we have called functions previously; rather, methods must be called from an instance of a class. For example, if a user wanted to make a deposit, we'd want to be able to call the method from the user instance; because a specific user is making a deposit, it should only affect that user's balance. Making such a call would look something like this: guido.make_deposit(100) # To be able to call on this method, it needs to exist. Let's make it! class User: # here's what we have so far def __init__(self, name, email): self.name = name self.email = email self.account_balance = 0 # adding the deposit method def make_deposit(self, amount): # takes an argument that is the amount of the deposit self.account_balance += amount # the specific user's account increases by the amount of the value received # Don't forget that the first parameter of every method within a class should be self. Notice that, in addition to whatever arguments are passed in as a traditional function, methods also have access to the class's attributes. # Now that our method is written, we can call it: guido.make_deposit(100) guido.make_deposit(200) monty.make_deposit(50) print(guido.account_balance) # output: 300 print(monty.account_balance) # output: 50 # Self # It's probably time to talk about self. The self parameter includes all the information about the individual object that has called the method. But how does it get passed in? Based on the signature for the deposit method or the __init__ method, they require 2 and 3 arguments, respectively. However, when we call on them, we pass in only 1 and 2. What's happening here? Because we are calling on the method from the instance, this is known as implicit passage of self. When we call on a method from an instance, that instance, along with all of its information (name, email, balance), is passed in as self.
afce4efaa47e3addf871f4a1df08c4f620a292da
willwburdick/Shared_Class_Work
/Assignment_05.py
3,627
4.3125
4
# ---------------------------------------------------------------------------------------------------------------------- # Title: Assignment 05 # Dev: William Burdick # Date: 04/30/2018 # Description: Read and write a text file # This project is like to the last one, but this time The To Do file will contain two columns of data (Task, Priority) # which you store in a Python dictionary. Each Dictionary will represent one row of data and these rows of data # are added to a Python List to create a table of data. # ---------------------------------------------------------------------------------------------------------------------- # When the program starts, load each row of data from the To Do.txt text file into a Python dictionary. # You can use a for loop to read a single line of text from the file and then place the data # into a new dictionary object. print("Hello, this program keeps track of the To Do items for your household") #ToDoList = open("D:\UW_Python_Class\Assignment05\ToDo.txt", "r") # Open the file To Do.txt #print (ToDoList) # for line in ToDoList: # Task1 = ToDoList.readline(0) # Task2 = ToDoList.readline(1) # print (Task1) # print (Task2) print("Here are the items in your list:") ToDoRow1 = {"ID": 1, "Task": "Clean House", "Priority": "Low"} ToDoRow2 = {"ID": 2, "Task": "Pay Bills", "Priority": "High"} ToDoDictionary = [ToDoRow1, ToDoRow2] print(ToDoDictionary) # ToDoList.close() TableHeader = ["ID", "Task", "Priority"] NewRow = "\n" # Add the new dictionary row into a Python list object TaskList = [TableHeader + ToDoDictionary] # Now the data will be managed as a table). # Allow the user to Add or Remove tasks from the list using numbered choices. # Menu of Options Menu1 = "#1 Show current data" Menu2 = "#2 Add a new item" Menu3 = "#3 Remove an existing item" Menu4 = "#4 Save Data to File" Menu5 = "#5 Exit Program" print (Menu1) print (Menu2) print (Menu3) print (Menu4) print (Menu5) ItemId = 2 UserChoice = 0 while UserChoice != 5: # If boolean is not equal to 5 loop will continue UserChoice = int(input("Please choose from the Menu:")) if UserChoice == 1: print ("Current list:") print(TaskList) elif UserChoice == 2: NewId = (ItemId + 1) ItemName = raw_input("Please enter the New Item:") ItemPriority = raw_input("Please enter the Priority:") NewRow = [NewId, ItemName, ItemPriority] TaskList.append(NewRow) ItemId = NewId print (Menu1) print (Menu2) print (Menu3) print (Menu4) print (Menu5) elif UserChoice == 3: #print(TaskList) #RowToRemove = int(input("Please enter the ID of the Task to remove:")) #for line in TaskList: #TaskList.remove([RowToRemove]) #print (TaskList) print (Menu1) print (Menu2) print (Menu3) print (Menu4) print (Menu5) continue elif UserChoice == 4: File = open("D:\UW_Python_Class\Assignment05\ToDo.txt", "w") # Open/write file named To Do.txt File.write(str(TaskList)) # Write the Dictionary to the file File.close() # Close the file print ("File saved") print (Menu1) print (Menu2) print (Menu3) print (Menu4) print (Menu5) continue elif UserChoice == 5: # User enters n to end loop break # Close loop print ("Program Closed") print("---------------------------------------------------------------------------------------------------------------")
6575a721c66f1f75f16f6662c2cca21dc3bb03c8
EricB2745/Data_Analytics_and_Visualizations
/Numpy/CreatingArrays.py
808
3.515625
4
import numpy as np # Create an array by converting a list my_list1 = [1,2,3,4] my_array1 = np.array(my_list1) print my_array1 my_list2 = [11,22,33,44] my_lists = [my_list1,my_list2] my_array2 = np.array(my_lists) print my_array2 print 'Shape of array: ' + str(my_array2.shape) print 'Type of array: ' + str(my_array2.dtype) zero_array = np.zeros(5) print zero_array print 'Shape of array: ' + str(zero_array.shape) print 'Type of array: ' + str(zero_array.dtype) ones_array = np.ones([5,25]) print ones_array print 'Shape of array: ' + str(ones_array.shape) print 'Type of array: ' + str(ones_array.dtype) identity_array = np.eye(5) print identity_array print 'Shape of array: ' + str(identity_array.shape) print 'Type of array: ' + str(identity_array.dtype) print np.arange(5) print np.arange(5,50,2)
541bd87f9ff8191ea2b7758fad6d4af7206024d2
BeginnerA234/codewars
/задача_35_7kyu.py
306
3.546875
4
# https://www.codewars.com/kata/5667e8f4e3f572a8f2000039/train/python def accum(string): res = '' for i, s in enumerate(string): if i == 0: res = res + s.capitalize() else: res = res + '-' + (s * i).capitalize() return res print(accum('ZpglnRxqenU'))
173c8cb3559bb0b12cb3b93339ab0d69df5b9d8f
BeginnerA234/codewars
/задача_30_6kyu.py
483
3.71875
4
# https://www.codewars.com/kata/54da539698b8a2ad76000228/train/python def is_valid_walk(walk): print(walk) res = 0 random_name = '' for i in walk: if i in random_name or len(random_name) == 0: random_name += i res += 1 else: res -= 1 if len(walk) == 10 and res == 0: return True else: return False print(is_valid_walk(['s', 'e', 's', 's', 'n', 's', 'e', 'n', 'n', 's']))
8c93f27cd772c1b1dc179921157c51eb5419b32a
BeginnerA234/codewars
/задача_24_6kyu.py
301
3.75
4
# https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1/train/python def duplicate_count(text): res = 0 text = text.lower() for i in text: if text.count(i)>1: res+=1 text = text.replace(i,'') return res print(duplicate_count("abcdabcd"))
83bdc36e4e00b6aa0b7afcd4dee64707c1b3faf1
mpwesthuizen/eng57_factory
/general_functions.py
868
3.90625
4
# recap function # define a function def say_hello(name): return (f'Hello {name}' ) # #BAD! # def return_formatted_name(name): # print(name.title().strip()) def return_formatted_name(name): return name.title().strip() # print the return of the function outside - NOT print inside the function. If you do all argument will return none (because return is already set to none) f_name = (return_formatted_name("marcus ")) print(say_hello((f_name))) # # Basis of a test # # def return_formatted_name(name): # return name.title().strip() # test setup print("Testingfunction return formatted name() with 'filipe '--> Filipe") know_input = 'filipe ' expected_out = 'Filipe' #test execution print("Testingfunction return formatted name() with 'filipe '--> Filipe") print(return_formatted_name() == expected_out) # testing say_hello()
f78f63eee3f5c35d2a564abb81adf7a24f5dba3f
BryCant/Intro-to-Programming-MSMS-
/FInal/finalLibrary.py
2,489
3.84375
4
import random class Student: def __init__(self, name, age, glasses, volume, nag_level): self.name = name self.age = age self.glasses = glasses self.volume = volume self.nag_level = nag_level def __str__(self): return f"Hi I am {self.name} and I am {self.age} years old {'!' * self.volume}" class Vehicle: def __init__(self, wheels, door_num, color, **car_stuffs): self.wheels = wheels self.door_num = door_num self.color = color if car_stuffs is not None: if "top_speed" in car_stuffs.keys(): self.top_speed = car_stuffs["top_speed"] else: self.top_speed = None if "passengers" in car_stuffs.keys(): self.passengers = car_stuffs["passengers"] else: self.passengers = None else: self.car_stuffs = None def get_max_pass(self): if self.wheels == 2: return 2 elif self.wheels > 2: return random.randint(4, 8) def get_driver_name(self): # first passenger is driver return self.passengers[0] def __str__(self): # car go HONK! print("HONK!!" + "!" * self.wheels) return "HONK!!" + "!" * self.wheels class SchoolBus(Vehicle): def __init__(self, wheels=4, door_num=2, color="yellow", **car_stuffs): super().__init__(wheels, door_num, color, **car_stuffs) self.bus_num = random.randint(100,999) def get_max_pass(self): return random.randint(len(self.passengers), len(self.passengers) + 12) def __add__(self, other): if type(other) == SchoolBus: self.passengers, other.passengers[:] = (self.passengers[:] + other.passengers), [] return f"Passengers on Bus #{other.bus_num} have moved to Bus #{self.bus_num}" elif type(other) == Student: self.passengers = self.passengers[:] + [other.name] return f"{other.name} (student) is now on Bus #{self.bus_num}" else: print("Operation unsuccessful. Verify compatible types.") keyan = Student("Keyan", 17, True, 7, 10) ewingBus = SchoolBus(top_speed=90, passengers=["Ewing", "Bryant", "Avery", "Blake", "Hayden"]) jordanBus = SchoolBus(top_speed=90, passengers=["Jordan", "Other Jordan", "Jayden", "Aaron", "Natalie"]) print(ewingBus + keyan) print(ewingBus.passengers) print(ewingBus + jordanBus) print(ewingBus.passengers)
53439bc9fed95069408cec769fddd8fc2fc9376d
BryCant/Intro-to-Programming-MSMS-
/Chapter13.py
2,435
4.34375
4
# Exception Handling # encapsulation take all data associated with an object and put it in one class # data hiding # inheritance # polymorphism ; function that syntactically looks same is different based on how you use it """ # basic syntax try: # Your normal code goes here. # Your code should include function calls which might raise exceptions. except: # If any exception was raised, then execute this code block # catching specific exceptions try: # Your normal code goes here. # Your code should include function calls which might raise exceptions. except ExceptionName: # If ExceptionName was raise, then execute this block # catching multiple specific exceptions try: # Your normal code goes here. # Your code should include function calls which might raise exceptions. except Exception_one: # If Exception_one was raised, then execute this block except Exception_two: # If Exception_two was raised, then execute this block else: # If there was no exception, then execute this block # clean-up after exceptions (if you have code that you want to be executed even if exceptions occur) try: # Your normal code goes here. # Your code might include functions which might raise exceptions. # If an exception is raised, some of these statements might not be executed finally: # This block of code WILL ALWAYS execute, even if there are exceptions raised """ # example with some file I/O (great place to include exception handling try: # the outer try:except: block takes care of a missing file or the fact that the file can't be opened for writing f = open("my_file.txt", "w") try: # the inner: except: block protects against output errors, such as trying to write to a device that is full f.write("Writing some data to the file") finally: # the finally code guarantees that the file is closed properly, even if there are errors during writing f.close() except IOError: print("Error: my_file.txt does not exist or it can't be opened for output.") # as long as a function that is capable of handling an exception exists above where the exception is raised in the stack # the exception can be handled def main() A() def A(): B() def B(): C() def C(): # processes try: if condition: raise MyException except MyException: # what to do if this exception occurs
ec9dc44facac9d6f6bdda9f3eb7c178c0b67ff0f
iannase/win2k17
/cycles.py
508
3.796875
4
wholeString = input() shifter = "" stringList = [] stringSize = "" stringShift = "" shift = 0 size = 0 z = 0 for x in wholeString: if z == 0: stringSize += x if z == 1: stringList.append(x) if z == 2: stringShift+= x if x == " ": z += 1 size = int(stringSize) shift = int(stringShift) stringList.pop(size) for i in range(size): for i in range(shift): shifter = stringList[0] stringList.pop(0) stringList.insert(size,shifter) result = "" for x in stringList: result += x print(result)
2679e524fb70ea8bc6a8801a3a9149ee258d9090
daviscuen/Astro-119-hw-1
/check_in_solution.py
818
4.125
4
#this imports numpy import numpy as np #this step creates a function called main def main(): i = 0 #sets a variable i equal to 0 x = 119. # sets a variable x equal to 119 and the decimal makes it a float (do you need the 0?) for i in range(120): #starting at i, add one everytime the program gets to the end of the for loop if (i%2) == 0: #if the value of i divided by 2 is exactly 0, then do the below part x += 3.0 #resets the variable x to 3 more than it was before else: # if the above condition is not true, do what is below x -= 5.0 #resets the variable x to 5 less than it was before s = "%3.2e" % x #puts it in sci notation (need help with why) print(s) #prints the above string s if __name__ == "__main__": main()
d0da8ed0d77bc22e2b4212747ecbcf6c82b9a30c
mvinovivek/BA_Python
/Class_3/1_4_ValueError.py
303
3.671875
4
#Value error will be raised when you try to change the type of an argument with improper value #most common example of the value error is while converting string to int or float number=int("number") #The above statement will throw an error as "number" as a string cannot be considered as int or float
0d4aad51ef559c9bf11cd905cf14de63a6011457
mvinovivek/BA_Python
/Class_3/8_functions_with_return.py
982
4.375
4
#Function can return a value #Defining the function def cbrt(X): """ This is called as docstring short form of Document String This is useful to give information about the function. For example, This function computes the cube root of the given number """ cuberoot=X**(1/3) return cuberoot #This is returning value to the place where function is called print(cbrt(27)) #calling using a variable number=64 print("Cube root of {} is {}".format(number,cbrt(number))) #Mentioning Type of the arguments #Defining the function def cbrt(X: float) -> float: cuberoot=X**(1/3) return cuberoot #This is returning value to the place where function is called print(cbrt(50)) #Mutiple returns def calculation(X): sqrt=X**0.5 cbrt=X**(1/3) return sqrt,cbrt # print(calculation(9)) # values=calculation(9) # print(values) # values=calculation(9) # print(values[0]) # sqrt,cbrt=calculation(9) # print(sqrt,cbrt)
53cee6f939c97b0d84be910eee64b6e7f515b12f
mvinovivek/BA_Python
/Class_3/7_functions_with_default.py
680
4.1875
4
# We can set some default values for the function arguments #Passing Multiple Arguments def greet(name, message="How are you!"): print("Hi {}".format(name)) print(message) greet("Bellatrix", "You are Awesome!") greet("Bellatrix") #NOTE Default arguments must come at the last. All arguments before default are called positional arguments def greet(message="How are you!", name): #This will Throw error print("Hi {}".format(name)) print(message) #You can mix the positional values when using their name #Passing Multiple Arguments def greet(name, message): print("Hi {}".format(name)) print(message) greet( message="You are Awesome!",name="Bellatrix")
626da3ed48d7dabc2074e13c6c6fda948a5ab34c
mvinovivek/BA_Python
/Class_3/1_7_IndexError.py
327
3.953125
4
#index errors will be raised when you try to access an index which is not present in the list or tuple or array X=[1,2,3,4,5] print(X[41]) #in case of dictionaries it will be KeyError Person={ 'Name': 'Vivek', 'Company' : 'Bellatrix' } print(Person['Name']) #it will work print(Person['Age']) #it will throw KeyError
0eb58cd27ce6822be0c7dc2d66524bbd6a207659
mvinovivek/BA_Python
/Class_4/10_comparting_projectiles_class.py
2,365
3.90625
4
import numpy as np import matplotlib.pyplot as plt class projectile(): g=9.81 def __init__(self,launch_angle,launch_velocity): self.launch_angle=launch_angle self.launch_velocity=launch_velocity def duration(self): duration=2*self.launch_velocity*np.sin(np.radians(self.launch_angle))/self.g return duration def range_dist(self): range_dist=self.launch_velocity**2*np.sin(np.radians(2*self.launch_angle))/self.g return range_dist def ceiling(self): ceiling=((self.launch_velocity**2)*((np.sin(np.radians(self.launch_angle)))**2))/(2*self.g) return ceiling def coordinates(self): duration_val = self.duration() t=np.linspace(0,duration_val,100) x=self.launch_velocity*t*np.cos(np.radians(self.launch_angle)) y=(self.launch_velocity*t*np.sin(np.radians(self.launch_angle)))-(0.5*self.g*t**2) return x,y angle=20 velocity=50 our_projectile=projectile(angle,velocity) print("Range of projectile with V={} m/s,launched at {} degrees is {} m".format(velocity,angle, our_projectile.range_dist())) print("Ceiling of projectile with V={} m/s,launched at {} degrees is {} m".format(velocity,angle, our_projectile.ceiling())) print("Duration of projectile with V={} m/s,launched at {} degrees is {} s".format(velocity,angle, our_projectile.duration())) X,Y=our_projectile.coordinates() plt.plot(X,Y) plt.xlabel("Range, m") plt.ylabel("Altitude, m") plt.title("A projectile") plt.show() # launch_angles=[10,20,30] # launch_velocities=[50,100,150] # for angle in launch_angles: # for velocity in launch_velocities: # our_projectile=projectile(angle,velocity) # # print("Range of projectile with V={} m/s,launched at {} degrees is {} m".format(velocity,angle, our_projectile.range_dist())) # # print("Ceiling of projectile with V={} m/s,launched at {} degrees is {} m".format(velocity,angle, our_projectile.ceiling())) # # print("Duration of projectile with V={} m/s,launched at {} degrees is {} s".format(velocity,angle, our_projectile.duration())) # # print('\n\n') # x,y=our_projectile.coordinates() # plt.plot(x,y,label="V= {}, T={}".format(angle,velocity)) # plt.title("Comparing Projectiles") # plt.xlabel("Range, m") # plt.ylabel("Altitude, m") # plt.legend() # plt.show()
3cb1bc2560b5771e4c9ec69d429fcfd9c0eadd2c
mvinovivek/BA_Python
/Class_2/7_for_loop_2.py
1,009
4.625
5
#In case if we want to loop over several lists in one go, or need to access corresponding #values of any list pairs, we can make use of the range method # # range is a method when called will create an array of integers upto the given value # for example range(3) will return an array with elements [0,1,2] #now we can see that this is an array which can act as control variables #Combining this with the len function, we can iterate over any number of lists #Simple range example numbers=[1,2,3,4,6,6,7,8,9,10] squares=[] cubes=[] for number in numbers: squares.append(number**2) cubes.append(number**3) for i in range(len(numbers)): print("The Square of {} is {}".format(numbers[i], squares[i])) for i in range(len(numbers)): print("The Cube of {} is {}".format(numbers[i], cubes[i])) #Finding sum of numbers upto a given number number = 5 sum_value=0 for i in range(number + 1): sum_value = sum_value + i print("The sum of numbers upto {} is {}".format(number,sum_value))
3cbfde72e5c26d2a8f498273e1e11ce7c8d65fe1
mvinovivek/BA_Python
/Class_5/7_widgets_radio_use.py
855
3.71875
4
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import RadioButtons Xvals=np.linspace(0,2*np.pi,50) Yvals=np.sin(Xvals) Zvals=np.cos(Xvals) #Creating the Plot # Plotting fig = plt.figure() ax = fig.subplots() plt.subplots_adjust(right=0.8) plt.title("Click the Radio Button to Change the Colors") ax_color = plt.axes([0.81, 0.5, 0.18, 0.25]) color_button = RadioButtons(ax_color, ['sin', 'cos'],[True, False], activecolor= 'k') # function for changing the plot color def color(curve): if curve=="sin": ax.clear() ax.plot(Xvals,Yvals) ax.set_title("Sine Curve") fig.canvas.draw() elif curve =="cos": ax.clear() ax.plot(Xvals,Zvals) ax.set_title("Cos Curve") fig.canvas.draw() else: pass color_button.on_clicked(color) plt.show()
c9a6c2f6b8f0655b3e417057f7e52015794d26d6
316126510004/ostlab04
/scramble.py
1,456
4.40625
4
def scramble(word, stop): ''' scramble(word, stop) word -> the text to be scrambled stop -> The last index it can extract word from returns a scrambled version of the word. This function takes a word as input and returns a scrambled version of it. However, the letters in the beginning and ending do not change. ''' import random pre, suf = word[0], word[stop:] word = list(word) mid_word = word[1:stop] random.shuffle(mid_word) word = pre + ''.join(mid_word) + suf return word def unpack_and_scramble(words): ''' unpack_and_scramble(words) words -> a list of words to be scrambled. returns a list of scrambled strings This function unpacks all the words and checks if len(word) < 3 If true then it scrambles the word Now, it will be appended to a new list ''' words = words.split() scrambled_words = [] for word in words: if len(word) <3: scrambled_words.append(word) continue if word.endswith((',', '?', '.', ';', '!')): stop = -2 else: stop = -3 scrambled_word = scramble(word, stop) scrambled_words.append(scrambled_word) return ' '.join(scrambled_words) file_name = input('Enter file name:') try: file = open(file_name, 'r') new_file = file.name + 'Scrambled' words = file.read() file.close() scrambed_words = unpack_and_scramble(words) file_name = open(new_file, 'w') file_name.write(scrambed_words) file_name.close() except OSError as ose: print('Please enter file name properly')
c456b13bb5316097a6856510e0e0140765216f18
Rahulllkumarrr/Simple-Program
/Cut the sticks.py
2,366
3.65625
4
''' Cut the stick ------------- You are given a number of sticks of varying lengths. You will iteratively cut the sticks into smaller sticks, discarding the shortest pieces until there are none left. At each iteration you will determine the length of the shortest stick remaining, cut that length from each of the longer sticks and then discard all the pieces of that shortest length. When all the remaining sticks are the same length, they cannot be shortened so discard them. Given the lengths of n sticks, print the number of sticks that are left before each iteration until there are none left. Note: Before each iteration you must determine the current shortest stick. ----- Input Format ------------- The first line contains a single integer n . The next line contains n space-separated integers: a0, a1,...an-1, where ai represents the length of the ith stick in array arr. Output Format -------------- For each operation, print the number of sticks that are cut, on separate lines. Sample Input 0 6 5 4 4 2 2 8 Sample Output 0 6 4 2 1 X--------X----------X--------X---------X----------X-----------------X----------X Sample Input 1 8 1 2 3 4 3 3 2 1 Sample Output 1 8 6 4 1 ''' def cutTheSticks(arr): count1 = 0 arr.sort() left = len(arr) list = [] while left > 0: mini = min(arr) if left > 0: list.append(left) count1 = arr.count(mini) for i in range(len(arr)): arr[i] = arr[i] - mini for i in range(count1): arr.pop(0) left = len(arr) return list if __name__ == "__main__": n = int(input().strip()) arr = list(map(int, input().strip().split(' '))) result = cutTheSticks(arr) print("\n".join(map(str, result)))
a7a2abaa6a70a9da4f81c1c5a9d7d231e9551434
Rahulllkumarrr/Simple-Program
/diagonal Difference.py
492
3.796875
4
def diagonalDifference(a): right,left=0,0 n=len(a) l=n-1 r=0 for i in range(n): right=right+(a[r][r]) left=left+a[r][l] r+=1 l+=-1 difference=abs(right-left) return difference if __name__ == "__main__": n = int(input().strip()) a = [] for a_i in range(n): a_t = [int(a_temp) for a_temp in input().strip().split(' ')] a.append(a_t) result = diagonalDifference(a) print(result)
476f71e3734a9ab494dd28662b5ceac58f321ffc
TundraStorm/raticus
/MyGame/on_key_press.py
555
3.671875
4
import arcade def on_key_press(self, key, modifiers): """Called whenever a key is pressed. """ # If the player presses a key, update the speed if key == arcade.key.UP: self.player_sprite.change_y = 7 #self.player_sprite.change_y = -MOVEMENT_SPEED*0.5 elif key == arcade.key.DOWN: self.player_sprite.change_y = 0#-MOVEMENT_SPEED elif key == arcade.key.LEFT: self.player_sprite.change_x = - self.movement_speed elif key == arcade.key.RIGHT: self.player_sprite.change_x = self.movement_speed
d24514f8bed4e72aaaee68ae96076ec3921f5898
ChanghaoWang/py4e
/Chapter9_Dictionaries/TwoIterationVariable.py
429
4.375
4
# Two iteration varibales # We can have multiple itertion variables in a for loop name = {'first name':'Changhao','middle name':None,'last name':'Wang'} keys = list(name.keys()) values = list(name.values()) items = list(name.items()) print("Keys of the dict:",keys) print("Values of the dict:",values) print("Items of the dict:",items) for key,value in items: # Two Itertion Values print('Keys and Values of the dict:',key)
d22d71b73ef371210d49a71f2abb69383e97cca8
ChanghaoWang/py4e
/Chapter2/assignment2_3.py
260
3.78125
4
inp_hour=float(input('Enter the hour:')) inp_rate=float(input('Enter the rate per hour:')) if inp_hour > 40: inp_rate_new=1.5*inp_rate grosspay = inp_rate_new*(inp_hour-40)+40*inp_rate else: grosspay=inp_hour*inp_rate print('Grosspay is',grosspay)
47675250b07dd0f5a0c3eae348b35ee4885a04a2
ChanghaoWang/py4e
/Chapter10_Tuples/Commonwords.py
671
3.921875
4
#Count words Chapter 10 Page 131 import string inp = input("Please enter the filename: ") if len(inp) < 1: inp = 'romeo-full.txt' try: fhand = open(inp) except: print("Cannot open the file:",inp) quit() count_dict = dict() for line in fhand: line = line.translate(str.maketrans('','',string.punctuation)) line = line.lower() words = line.split() for word in words: count_dict[word] = count_dict.get(word,0) + 1 count_list = list() for (key,value) in list(count_dict.items()): count_list.append((value,key)) count_list.sort(reverse = True) print('The most common word is',count_list[0][1],"It appears",count_list[0][0],'times')
3cae3e36c80ac6d2040d872705091194edc954af
ChanghaoWang/py4e
/Chapter8_Lists/modify.py
612
4.09375
4
# List modify #It's important to remember which methods modify the list or create a new one def delete_head(t): del t[0] def pop_head(t): t.pop(0) def add_append(t1,t2): t1.append(t2) def add(t1,t2): return t1 + t2 def delete_head_alternative(t): return t[1:] letters = ['a',1,'b',2,'c',3] delete_head(letters) print(letters) pop_head(letters) print(letters) letters_new = ['Another',1] add_append(letters,letters_new) print(letters) letters_new_1 = add(letters,letters_new) print('Another',letters_new_1) letters_delete = delete_head_alternative(letters) print('Delete head',letters_delete)
6d325039a3caa4c331ecc6fa6bb058ff431218f8
ChanghaoWang/py4e
/Chapter8_Lists/note.py
921
4.21875
4
# Chapter 8 Lists Page 97 a = ['Changhao','Wang','scores',[100,200],'points','.'] # method: append & extend a.append('Yeah!') #Note, the method returns None. it is different with str a.extend(['He','is','so','clever','!']) # method : sort (arranges the elements of the list from low to high) b= ['He','is','clever','!'] b.sort() print(b) # method : delete (pop) retrus the element we removed. c = ['a',1,'c'] x = c.pop(0) print('After remove:',c) print('What we removed is:',x) # method : del c = ['a',1,'c'] del c[0] print(c) # method : remove attention: it can only remove one element c = ['a',1,'c',1] c.remove(1) print(c) # convert string to List d = 'Changhao' e = list(d) print(e) f = 'Changhao Wang' g = f.split() print(g) # string method : split() s = 'spam-spam-spam' s_new = s.split('-') print(s_new) # convert lists to string t = ['pining','for','the','fjords'] delimiter = ' ' t_str = delimiter.join(t) print(t_str)
4be436e6a4b5aff0bcdd99dded5d1a2c3ce0763e
ChanghaoWang/py4e
/Chapter11_Expressions/Exercise1.py
329
3.921875
4
# Exercise 1 Chapter 11 Page 149 import re inp = input("Enter a regular expression: ") if len(inp) < 1: inp = '^From:' fhand = open("mbox.txt") count = 0 for line in fhand: line = line.strip() words = re.findall(inp,line) if len(words) > 0: count += 1 print("mbox.txt had",count,"lines that matched",inp)
c2b24f3f587202bdea4e6ec7895d06f70e9c3d04
celine5/GUVIrepo
/even.py
118
4.25
4
num=int(input("enter a number:")) if(num%2)==0: print("{0} is even".fomat(num)) else: print("{0} is odd".format(num))
802707f723581bda40c9d53b34d12858a58592d5
celine5/GUVIrepo
/vowelc.py
245
3.859375
4
original =input('Enter a character:') character= original.lower() first =character[0] if len(original) > 0 and original.isalpha(): if first in 'aeiou': print("Vowel") else: print("Consonant") else: print ("invalid")
1f36f982a91c6257911b91f1f5005d900fac104c
junbeomLim/Algorithm
/BOJ/backjoon 2750.py
129
3.59375
4
N = int(input()) n = [0 for i in range(N)] for i in range(N): n[i] = int(input()) n.sort() for i in range(N): print(n[i])
d21ea5dda881f239defc04d28018acc89ac99c86
ArpitaBawgi/Devops-Training
/third.py
274
3.984375
4
name='' condition=True while(condition): print('who are you') name=input() if(name!='joe'): continue else: print("Hello Joe, What is password?(it is fish)"); password=input(); if(password =='swoardfish'): #condition=False; break; print('Access Granted')
a632cf8c425a392504331ee4413aeb4727ea4318
wesyang/sudoku_solver
/misc/findIslands.py
1,606
3.625
4
class Solution(object): def printMap(self, map): for r in map: for c in r: print(f'{c} ', end='') print() print('-----------------') def checkAndMarkIsland(self, map, x, y, cc, rc): if x < 0 or y < 0: return if x >= cc or y >= rc: return if map[y][x] == 1: map[y][x] = 'x' self.markIsland(map, x, y, cc, rc) def markIsland(self, map, x, y, cc, rc): self.checkAndMarkIsland(map, x - 1, y - 1, cc, rc) self.checkAndMarkIsland(map, x - 1, y, cc, rc) self.checkAndMarkIsland(map, x - 1, y + 1, cc, rc) self.checkAndMarkIsland(map, x, y - 1, cc, rc) self.checkAndMarkIsland(map, x, y + 1, cc, rc) self.checkAndMarkIsland(map, x + 1, y - 1, cc, rc) self.checkAndMarkIsland(map, x + 1, y, cc, rc) self.checkAndMarkIsland(map, x + 1, y + 1, cc, rc) def findIslands(self, map): pass if not map: return 0 rc = len(map) cc = len(map[0]) print(rc, cc) total = 0 for y in range(rc): for x in range(cc): if map[y][x] == 1: map[y][x] = 'x' self.markIsland(map, x, y, cc, rc) self.printMap(map) total += 1 return total if __name__ == "__main__": solution = Solution() map = [ [1, 0, 0, 0, 1], [1, 0, 1, 0, 1], [1, 0, 0, 0, 0], [1, 1, 0, 1, 1], ] solution.printMap(map) print(solution.findIslands(map))
63155a1d3a461b958561d57c38adbea2c8be1e26
wesyang/sudoku_solver
/misc/getSqrt.py
1,394
3.65625
4
class Solution(object): @staticmethod def getSqrt(min, max, x): while (True): mid = int((max - min +1) / 2) + min mm = mid * mid #print (min, mid, max, mm, x) if mm == x: return mid elif mm < x: nextSqrt = (mid + 1) * (mid + 1) if nextSqrt == x: return mid + 1 elif nextSqrt > x: return mid min = mid else: prevSprt = (mid - 1) * (mid - 1) if prevSprt <= x: return mid - 1 max = mid def mySqrt(self, x): """ :type x: int :rtype: int """ return Solution.getSqrt(0, 2 ** 32, x) @staticmethod def checkSqrt(min, max, x): while (max >= min ): mid = int((max - min +1) / 2) + min mm = mid * mid print (min, mid, max, mm, x) if mm == x: return True elif mm < x: min = mid +1 else: max = mid -1 return False def isPerfectSquare(self, x): """ :type x: int :rtype: int """ return Solution.checkSqrt(0, 2 ** 32, x) if __name__ == "__main__": solution = Solution() print(solution.isPerfectSquare(25))
c76f613f2855a56d738d64439a2d857d1ca15781
jayashreemohan29/pmemkv-testing
/count_ops.py
882
3.640625
4
#!/usr/bin/env python import getopt import sys def main(): #input arg : file name if (len(sys.argv) != 2): print("Please input log file") exit(1) log_file = sys.argv[1] count = 0 count_fence = 0 count_flush = 0 count_store = 0 count_others = 0 operations = open(log_file).read().split("|") for op in operations: count+=1 op_value = op.split(";")[0] if (op_value == "FENCE"): count_fence += 1 elif (op_value == "STORE"): count_store += 1 elif (op_value == "FLUSH"): count_flush += 1 else: count_others +=1 #print(str(op)) print("\n----- OP SUMMARY --------\n") print("\n Total Ops : " + str(count)) print("\n Total store ops : " + str(count_store)) print("\n Total flush ops : " + str(count_flush)) print("\n Total fence ops : " + str(count_fence)) print("\n Other ops : " + str(count_others)) if __name__ == "__main__": main()
007064524296a592bf238f413029a41a12bafc0b
bharath144/PythonWorkshop
/sorting/bubble_sort.py
1,481
3.703125
4
import random import time input_a = [x for x in range(0, 1000)] input_b = random.sample(input_a, 10) input_c = input_b.copy() def iterative_sort(unsorted_list): print(unsorted_list) for i in range(0, len(unsorted_list)): # Improved exit condition, if there are no swaps, all numbers are sorted swapped = False for j in range(0, len(unsorted_list) - i - 1): if unsorted_list[j] > unsorted_list[j+1]: # The actual in-place swap, a semantic that's unique to Python. # This is similar to temp = x, x = y, y = temp unsorted_list[j], unsorted_list[j+1] = \ unsorted_list[j+1], unsorted_list[j] print(" " + str(unsorted_list)) # Indicates if we swapped something swapped = True print(unsorted_list) if not swapped: break def recurseive_sort(unsorted_list): print(unsorted_list) for i, num in enumerate(unsorted_list): try: if unsorted_list[i + 1] < num: # Swap unsorted_list[i] = unsorted_list[i + 1] unsorted_list[i + 1] = num print(" " + str(unsorted_list)) recurseive_sort(unsorted_list) except IndexError: print(unsorted_list) pass return unsorted_list recurseive_sort(input_b) print("") print("") print("") print("") iterative_sort(input_c)
3422c8df4de8e5e1bf18e154be725f7879f797c5
MaxMcCarthy/Recommender-System
/Scraper/web_scraper.py
6,479
3.71875
4
from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup import csv # with help from: # https://realpython.com/python-web-scraping-practical-introduction/ def simple_get(url): """ Attempts to get the content at `url` by making an HTTP GET request. If the content-type of response is some kind of HTML/XML, return the text content, otherwise return None """ try: with closing(get(url, stream=True)) as resp: if is_good_response(resp): return resp.content else: return None except RequestException as e: print('Error during requests to {0} : {1}'.format(url, str(e))) return None def is_good_response(resp): """ Returns true if the response seems to be HTML, false otherwise """ content_type = resp.headers['Content-Type'].lower() return (resp.status_code == 200 and content_type is not None and content_type.find('html') > -1) def scrape_academic(): headings = ['CS', 'STAT', 'LAS', 'ENG', 'GRAD'] urls = ['http://calendars.illinois.edu/list/504', 'https://calendars.illinois.edu/list/1439', "http://calendars.illinois.edu/list/1249", 'http://calendars.illinois.edu/list/2568', 'http://calendars.illinois.edu/list/3695'] count = 0 for url in urls: base_url = 'http://calendars.illinois.edu' html = simple_get(url) html = BeautifulSoup(html, 'html.parser') for p in html.select('ul'): for h3 in p.select('h3'): for a in h3.select('a'): print(a['href']) print(a.text) print('') event = simple_get(base_url + a['href']) event = BeautifulSoup(event, 'html.parser') for dd in event.findAll("section", {"class": "detail-content"}): for desc, info in zip(dd.select('dt'), dd.select('dd')): print("{} : {}\n".format(desc.text, info.text)) for summary in dd.findAll('dd', {"class": 'ws-description'}): print(summary.text.strip()) print('\n\n\n') print(count) count += 1 def scrape_arc(): urls = ['http://calendars.illinois.edu/list/7'] count = 0 for url in urls: base_url = 'http://calendars.illinois.edu' html = simple_get(url) html = BeautifulSoup(html, 'html.parser') for p in html.select('ul'): for h3 in p.select('h3'): for a in h3.select('a'): print(a['href']) print(a.text) print('') event = simple_get(base_url + a['href']) event = BeautifulSoup(event, 'html.parser') for dd in event.findAll("section", {"class": "detail-content"}): for desc, info in zip(dd.select('dt'), dd.select('dd')): print("{} : {}\n".format(desc.text, info.text)) for summary in dd.findAll('dd', {"class": 'ws-description'}): print(summary.text.strip()) print('\n\n\n') print(count) count += 1 def scrape_url(urls): count = 0 with open('events.csv', 'a+') as csvfile: headers = ['doc_id', 'title', 'url', 'event_type', 'sponsor', 'location', 'date', 'speaker', 'views', 'originating_calendar', 'topics', 'cost', 'contact', 'e-mail', 'phone', 'registration', 'description'] writer = csv.DictWriter(csvfile, fieldnames=headers) writer.writeheader() base_url = 'http://calendars.illinois.edu' for url in urls: html = simple_get(url) html = BeautifulSoup(html, 'html.parser') for p in html.select('ul'): for h3 in p.select('h3'): row = {'doc_id': 'NA', 'title': 'NA', 'url': 'NA', 'event_type': 'NA', 'sponsor': 'NA', 'location': 'NA', 'date': 'NA', 'speaker': 'NA', 'views': 'NA', 'originating_calendar': 'NA', 'topics': 'NA', 'cost': 'NA', 'contact': 'NA', 'e-mail': 'NA', 'phone': 'NA', 'registration': 'NA', 'description': 'NA'} for a in h3.select('a'): row['doc_id'] = count row['title'] = a.text row['url'] = base_url + a['href'] event = simple_get(base_url + a['href']) event = BeautifulSoup(event, 'html.parser') for dd in event.findAll("section", {"class": "detail-content"}): for desc, info in zip(dd.select('dt'), dd.select('dd')): # print("{} : {}\n".format(desc.text, info.text)) name = desc.text.lower().strip().replace(" ", "_") if name == 'topic': name += 's' row[name] = info.text description = '' for summary in dd.findAll('dd', {"class": 'ws-description'}): description += summary.text.strip() # print(summary.text.strip()) if description != '': row['description'] = description writer.writerow(row) # print('\n\n\n') print(count) count += 1 if __name__ == '__main__': # optional smaller calendars # scrape_academic() fitness_classes = 'https://calendars.illinois.edu/list/4046' krannert_perf = 'https://calendars.illinois.edu/list/33' campus_rec = 'http://calendars.illinois.edu/list/2628' student_affairs = 'http://calendars.illinois.edu/list/1771' master = 'http://calendars.illinois.edu/list/7' scrape_url([fitness_classes, krannert_perf, campus_rec, student_affairs, master]) # scrape_url(krannert_perf) # scrape_url(campus_rec) # scrape_url(student_affairs) # scrape_url(master)
b2e057bd9d63ba6da9a755f2c879bc58ae65086b
tomcat1969/CodingDojo_python_stack
/python/fundamentals/forloopbasic2.py
1,654
3.953125
4
# def biggie_size(list): # for i in range(len(list)): # if list[i] > 0: # list[i] = "big" # return list # print(biggie_size([-1,3,5,-5])) # def count_positives(list): # count = 0 # for i in range(len(list)): # if list[i] > 0: # count = count + 1 # list[len(list)-1] = count # return list # print(count_positives([1,6,-4,-2,-7,-2])) # def sum_total(list): # sum = 0 # for i in range(len(list)): # sum = sum + list[i] # return sum # print(sum_total([1,2,3,4])) # def average(list): # sum = 0 # for i in range(len(list)): # sum = sum + list[i] # return sum / len(list) # print(average([1,2,3,4])) # def length(list): # return len(list) # print(length([])) # def minimum(list): # if len(list) == 0: # return False # global_min = list[0] # for i in range(len(list)): # if list[i] < global_min: # global_min = list[i] # return global_min # print(minimum([37,2,1,-9])) # def maximum(list): # if len(list) == 0: # return False # global_max = list[0] # for i in range(len(list)): # if list[i] > global_max: # global_max = list[i] # return global_max # print(maximum([37,2,1,-9])) # def ultimate_analysis(list): # result = {} # result['sumTotal'] = sum_total(list) # result['average'] = average(list) # result['minimum'] = minimum(list) # result['maximum'] = maximum(list) # result['length'] = length(list) # return result # print(ultimate_analysis([37,2,1,-9])) def reverse_list(list): l = 0 r = len(list) - 1 while l < r: temp = list[l] list[l] = list[r] list[r] = temp l = l + 1 r = r - 1 return list print(reverse_list([37,2,1,-9]))
d593ffafc59015480c713c213b59f6304914d660
Ayush10/python-programs
/vowel_or_consonant.py
1,451
4.40625
4
# Program to check if the given alphabet is vowel or consonant # Taking user input alphabet = input("Enter any alphabet: ") # Function to check if the given alphabet is vowel or consonant def check_alphabets(letter): lower_case_letter = letter.lower() if lower_case_letter == 'a' or lower_case_letter == 'e' or lower_case_letter == 'i' or lower_case_letter == 'o' \ or lower_case_letter == 'u': # or lower_case_letter == 'A' or lower_case_letter == 'E' or lower_case_letter == \ # 'I' or lower_case_letter == 'U': return "vowel" else: return "consonant" # Checking if the first character is an alphabet or not: if 65 <= ord(alphabet[0]) <= 90 or 97 <= ord(alphabet[0]) <= 122: # Checking if there are more than 1 characters in the given string. if len(alphabet) > 1: print("Please enter only one character!") print("The first character {0} of the given string {1} is {2}.".format(alphabet[0], alphabet, check_alphabets(alphabet[0]))) # If only one character in the given string. else: print("The given character {0} is {1}.".format(alphabet, check_alphabets(alphabet))) # If the condition is not satisfied then returning the error to the user without calculation. else: print("Please enter a valid alphabet. The character {0} is not an alphabet.".format(alphabet[0]))
2676477d211e0702d1c44802f9295e8457df21a8
Ayush10/python-programs
/greatest_of_three_numbers.py
492
4.3125
4
# Program to find greatest among three numbers # Taking user input a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) c = int(input("Enter third number: ")) # Comparison Algorithm and displaying result if a > b > c: print("%d is the greatest number among %d, %d and %d." % (a, a, b, c)) elif b > a > c: print("%d is the greatest number among %d, %d and %d." % (b, a, b, c)) else: print("%d is the greatest number among %d, %d and %d." % (c, a, b, c))
172102809e9f1fc0ebf8516b78f7dab417f05e5e
ecarlos09/procedural-python-exercises
/name_generator/penguin_name.py
423
3.5
4
penguin_converter = { "January": "Mumble", "February": "Squeak", "March": "Skipper", "April": "Gloria", "May": "Kowalski", "June": "Rico", "July": "Private", "August": "King", "September": "Pingu", "October": "Feathers McGraw", "November": "Chocolatey", "December": "Ice Cold" } def user_penguin(birth_month): penguin_name = penguin_converter[birth_month] return penguin_name
82b3b3358fc08521b6e714a7d1b5cf2c40aee47c
MiriSilva/Avaliacao1
/Questao2.py
354
4.09375
4
n1 = int(input("informe um numero inteiro: ")) n2 = int(input("informe um numero inteiro: ")) n3 = float(input("informe um numero real: ")) print ("o produto do dobro do primeiro com metade do segundo è :", n1*2*(n2/2)) print ("a soma do triplo do primeiro com o terceiro é:", (n1*3)+n3 ) print ("o terceiro elevado ao cubo é: ", (n3**3))
a42ff81b035de48e6628dbac29315ae1e2e78bb1
MiriSilva/Avaliacao1
/Questao4.py
363
3.828125
4
x = float(input("Informe quanto ganha por hora:")) y = float(input("Informe quantas horas trabalhadas no mês:")) SB = (x*y) IR = SB * 0.11 INSS = SB* 0.08 SD = SB*0.05 SL = SB-(IR+INSS+SD) print("Salário Bruto : R$",SB) print("IR (11%) : R$",IR ) print("INSS (8%) : R$",INSS ) print("Sindicato ( 5%) : R$",SD ) print("Salário Liquido : R$",SL )
3fefcd97afaccac58e7c18e5303c44d2c11699a0
hendy3/A-beautiful-code-in-Python
/Teil_15_Sudoku_Algorithm_x.py
2,701
3.8125
4
#!/usr/bin/env python3 # Author: Ali Assaf <ali.assaf.mail@gmail.com> # Copyright: (C) 2010 Ali Assaf # License: GNU General Public License <http://www.gnu.org/licenses/> from itertools import product import time def solve_sudoku(size, grid): """ An efficient Sudoku solver using Algorithm X. """ R, C = size N = R * C X = ([("rc", rc) for rc in product(range(N), range(N))] + [("rn", rn) for rn in product(range(N), range(1, N + 1))] + [("cn", cn) for cn in product(range(N), range(1, N + 1))] + [("bn", bn) for bn in product(range(N), range(1, N + 1))]) Y = dict() for r, c, n in product(range(N), range(N), range(1, N + 1)): b = r // R * R + c // C # Box number Y[(r, c, n)] = [ ("rc", (r, c)), ("rn", (r, n)), ("cn", (c, n)), ("bn", (b, n))] X, Y = exact_cover(X, Y) for i, row in enumerate(grid): for j, n in enumerate(row): if n: select(X, Y, (i, j, n)) for solution in solve(X, Y, []): for (r, c, n) in solution: grid[r][c] = n yield grid def exact_cover(X, Y): X = {j: set() for j in X} for i, row in Y.items(): for j in row: X[j].add(i) return X, Y def solve(X, Y, solution): if not X: yield list(solution) else: c = min(X, key=lambda c: len(X[c])) for r in list(X[c]): solution.append(r) cols = select(X, Y, r) for s in solve(X, Y, solution): yield s deselect(X, Y, r, cols) solution.pop() def select(X, Y, r): cols = [] for j in Y[r]: for i in X[j]: for k in Y[i]: if k != j: X[k].remove(i) cols.append(X.pop(j)) return cols def deselect(X, Y, r, cols): for j in reversed(Y[r]): X[j] = cols.pop() for i in X[j]: for k in Y[i]: if k != j: X[k].add(i) def string2grid(aufgabe): grid, zeile = [], [] for i, char in enumerate(aufgabe): if char == '.': zahl = 0 else: zahl = int(char) zeile.append(zahl) if (i+1) % 9 == 0: grid.append(zeile) zeile = [] return grid lösungen = [] start1 = time.perf_counter() with open('Teil_15_Sudoku_2365_hard.txt') as f: for i, zeile in enumerate(f): zeile = zeile.rstrip() start = time.perf_counter() solutions = solve_sudoku((3, 3), string2grid(zeile)) for solution in solutions: pass end = time.perf_counter() lösungen.append((end-start, i+1)) summe = sum(x for x, y in lösungen) print(f'Lösung von {i+1:,} Sudokus in {summe:,.2f} Sek. (durchschn. {summe/len(lösungen)*1000:,.2f} Millisek.)\n') lösungen.sort(reverse=True) for i in range(10): zeit, nr = lösungen[i] print(f'Nr. {nr:5d} in {zeit*1000:5,.0f} Millisek.')
e50f8e37210054df2e5c54eb55e7dee381a91aff
super468/leetcode
/python/src/BestMeetingPoint.py
1,219
4.15625
4
class Solution: def minTotalDistance(self, grid): """ the point is that median can minimize the total distance of different points. the math explanation is https://leetcode.com/problems/best-meeting-point/discuss/74217/The-theory-behind-(why-the-median-works) the more human language version is that there are two groups of people, it will decrease the distance if you put the point closer to the group with more people. At end of the day, the two sides will be equal. :type grid: List[List[int]] :rtype: int """ list_y = [] list_x = [] for row in range(0, len(grid)): for col in range(0, len(grid[row])): if grid[row][col] == 1: list_y.append(row) list_x.append(col) list_y.sort() list_x.sort() median_y = list_y[int(len(list_y) / 2)] median_x = list_x[int(len(list_x) / 2)] sum_y = 0 for y in list_y: sum_y += median_y - y if median_y > y else y - median_y sum_x = 0 for x in list_x: sum_x += median_x - x if median_x > x else x - median_x return sum_x + sum_y
71c87f644ac21e84586fa2fcb51e9c160151c6a7
super468/leetcode
/python/src/FlipGameII.py
749
3.734375
4
""" the basic idea is that track every movement of the first player, if the other player can not make a movement, then movement the first player made is a winning movement. the optimization is to use memorization to memorize the string state that we have seen. this is a backtracking problem with memorization optimization """ class Solution1: mem = {} def canWin(self, s): if s not in self.mem: self.mem[s] = any(s[i:i+2]=='++' and not self.canWin(s[:i]+'--'+s[i+2:]) for i in range(len(s)-1)) return self.mem[s] class Solution2(object): def canWin(self, s): for i in range(len(s)-1): if s[i]=='+' and s[i+1]=='+' and not self.canWin(s[:i]+'--'+s[i+2:]): return True return False
3228d9c857bd5e39ca56b0d8d5f4f43b8c8f8d5c
scotchka/scotchka.github.io
/2018/06/16/balance_brackets.py
821
3.578125
4
import inspect BRACKETS = {")": "(", "]": "[", "}": "{"} def _stack(chars): """Push/pop frames to/from call stack.""" while chars: char = chars.pop(0) if char in BRACKETS.values(): _stack(chars) # push elif char in BRACKETS: previous = inspect.stack()[1] if ( previous.function != "_stack" or previous.frame.f_locals["char"] != BRACKETS[char] ): raise IndexError return # pop if inspect.stack()[1].function == "_stack": # check no brackets remain raise IndexError def is_balanced(string): """Check whether brackets in given string balanced.""" try: _stack(list(string)) except IndexError: return False else: return True
cdccb6138c604da36be9d9b97d65e0270bc57cb8
monicadsong/matrix_factorization_mp
/test_multiprocessing.py
3,289
3.5625
4
import multiprocessing from multiprocessing import pool print("cpu count: ", multiprocessing.pool.cpu_count()) import os, time # g_cnt is not shared with each worker def test_process_with_global_variable(): g_cnt = 4 def worker(idx, data, g_cnt): global g_cnt g_cnt += 1 time.sleep(1) print("worker", idx, g_cnt, data) return g_cnt #i is in another virtual memory space for i in range(5): p = multiprocessing.Process(target=worker, args=(i, "pp", g_cnt) ) p.start() #p.join() #all processes have ended print("g_cnt: ", g_cnt) # show several processes run in parallel by pool of processes # does not work yet class XY(): def __init__(self, x, y): self.x = x self.y = y # g_v is not reliable in this case g_v = 4 g_lock = multiprocessing.Lock() def square(d): # print 'module name:', __name__ # if hasattr(os, 'getppid'): # print 'parent process:', os.getppid() # print 'process id:', os.getpid() global g_v with g_lock: #print(g_v) g_v += 1 return d.x*d.x + d.y def test_process_pool_map(): pool = multiprocessing.Pool(processes=multiprocessing.pool.cpu_count()) print('Starting run at ' + time.strftime('%Y-%m-%d-%H:%M:%S', time.gmtime())) tot = 0 iter_cnt = 10000 proc_cnt = 16 for j in xrange(iter_cnt): dl = [XY(1.1111113+i,2.133+j) for i in xrange(proc_cnt)] sqr = pool.map(square, dl) tot += sum(sqr) print(tot) print('Ending run at ' + time.strftime('%Y-%m-%d-%H:%M:%S', time.gmtime())) def test_shared_class(): class SharedClass(): def __init__(self): self.queue = multiprocessing.Queue() self.lock = multiprocessing.Lock() self.process_cnt = 2 self.data = 5.1111 def _process(self, idx): max_cnt = 20 cnt = 0 while cnt < max_cnt: with self.lock: s = "{} + {}".format(idx, cnt) self.queue.put([s, self.data]) cnt += 1 def run(self): pool = [] for i in range(self.process_cnt): self.data += i p = multiprocessing.Process(target=self._process, args=(i,) ) p.start() pool.append(p) for p in pool: p.join() while not self.queue.empty(): d = self.queue.get() print(d) s = SharedClass() s.run() # send back message to parent by pipe def test_shared_by_pipe(): def send_by_pipe(conn): conn.send([42, None, 'hello']) conn.close() parent_conn, child_conn = multiprocessing.Pipe() p = multiprocessing.Process(target=send_by_pipe, args=(child_conn,)) p.start() print parent_conn.recv() p.join() # synchronization among processes def test_locked_print(): def locked_print(lock, i): with lock: print('hello world', i) print('hello world', i+100) time.sleep(0.1) print('hello world', i+200) print('hello world', i+300) l = multiprocessing.Lock() pool = [] for i in range(50): p = multiprocessing.Process(target=locked_print, args=(l, i) ) pool.append(p) p.start() for p in pool: p.join() # python documentation have very good examples for addtional features #test_process_pool_map() # test_locked_print() # test_shared_by_pipe() test_process_with_global_variable() # test_shared_class()
a5333df631bfbbc3f2ab5e6f8631eb7cb17611f1
PanchoF1/56107-Francisco-Saldana
/Clase05 Calculadora/calculadora_test.py
1,052
3.546875
4
import unittest from clases import Calculator class TestCalculador(unittest.TestCase): def resul_calculator_1_add_1_(self): calc = Calculator() calc.ingresar('1') calc.ingresar('+') calc.ingresar('1') calc.ingresar('=') self.assertEqual(calc.display(),'2') def resul_calculator_2_rest_1_(self): calc = Calculator() calc.ingresar('2') calc.ingresar('-') calc.ingresar('1') calc.ingresar('=') self.assertEqual(calc.display(),'1') def resul_calculator_2_x_2_(self): calc = Calculator() calc.ingresar('2') calc.ingresar('*') calc.ingresar('2') calc.ingresar('=') self.assertEqual(calc.display(),'4') def resul_calculator_10_div_5_(self): calc = Calculator() calc.ingresar('10') calc.ingresar('/') calc.ingresar('5') calc.ingresar('=') self.assertEqual(calc.display(),'2') if __name__ == "__main__": unittest.main()
3da888a1d429023b69d7e4efd7e4f7d6909e3f75
afterthought325/cp_lab
/atm_machine-0.5.py
3,095
3.84375
4
################################################################################ # Name: Chaise Farrar Date Assigned:10/16/2014 # # Partner: Rebecca Siciliano # # Course: CSE 1284 Sec 10 Date Due: 10/16/2014 # # File name:ATM Machine # # Program Description: Simulates an ATM experiance, from logging in with # # a pin to checking acount balance # ################################################################################ import getpass def main(): checking_balance = 50000 saving_balance = 10000 pin = int(getpass.getpass('\nHello! Welocome! Please enter your four digit PIN: ')) while pin == 7894: while True: try: choose = int(input('\n1. Inquiry \n'+ '2. Deposit to checking \n' + '3. Deposit to savings \n' + '4. Withdrawl from checking \n' + '5. Withdrawl from savings \n' + '6. Quit \n\nPlease choose an option: ')) except ValueError: print('Input is not valid.') raise SystemExit(0) if choose == 1: inquiry(checking_balance,saving_balance) input('\n Press any key to go back: ') elif choose == 2: checking_balance = deposit(checking_balance) input('\n Press any key to go back: ') elif choose == 3: saving_balance = deposit(saving_balance) input('\n Press any key to go back: ') break elif choose == 4: checking_balance = withdrawl(checking_balance) input('\n Press any key to go back: ') break elif choose == 5: saving_balance = withdrawl(saving_balance) input('\n Press any key to go back: ') elif choose == 6: print('Thank You for your Business') raise SystemExit(0) print('\n Unknown PIN.') input('\n Press any key to go back: ') main() def inquiry(checking_balance,saving_balance): print('\n Checking balance: ',checking_balance) print('\n Savings balance: ',saving_balance) def deposit(balance): dep = int(input('\n Please enter how much you want to deposit: ')) balance += dep print('\n Your new balance is: ', balance) return balance def withdrawl(balance): withdrawl = int(input('\n Please enter how much you want to withdrawl: ')) while withdrawl > balance: print('\n You broke foo.') withdrawl = int(input('\n Please enter how much you want to withdrawl: ')) balance = balance - withdrawl print('\n Your new balance is: ', balance) return balance main()
977125662ad8ba83bbe8cedc6bce54ab9836d207
kunxin-chor/tgc-python
/select-example/main.py
343
3.515625
4
import pymysql connection = pymysql.connect(host='localhost', user="admin", password="password", database="Chinook" ) cursor = connection.cursor() cursor.execute("SELECT * from Employee") for r in cursor: # print (r) # We have to refer each field by its index print ("Name: " + r[1] + " " + r[2] + " is a " + r[3])
8b46f6ce79908a511e258e2af636e398387f0474
accimeesterlin/scrape_linkedin
/filter_contact.py
2,087
3.59375
4
import json from pprint import pprint data = json.load(open("contacts.json")) def set_max(arr, limit): for index, contact in enumerate(arr): if index <= int(limit) - 1: print("_______________________________________") print("_______________________________________") print("Index: ", index + 1) print("Name: ", contact["name"]) print("Occupation: ", contact["occupation"]) print("Link: ", contact["link"]) def search_contact(detail, val, limit): status = False results = [] for index, contact in enumerate(data): if contact[detail].find(val) != -1: status = True current_search = {} current_search["name"] = contact["name"] current_search["link"] = contact["link"] current_search["occupation"] = contact["occupation"] results.append(current_search) if status == False: print("No results found!!!") set_max(results, limit) # TODO # Cleaning def honoring_user_input(_input): if _input == "Company Name": text = input("Enter the company name: ") num = input("How many results do you want? ") search_contact("occupation", text, num) elif _input == "Name": text = input("Enter the name: ") num = input("How many results do you want? ") search_contact("name", text, num) elif _input == "Title": text = input("Enter the title: ") num = input("How many results do you want? ") search_contact("occupation", text, num) options = ["Company Name", "Name", "Title"] # Let user enter based on the option def let_user_pick(options): print("Search people by: ") for idx, element in enumerate(options): print("{}) {}".format(idx + 1, element)) i = input("Enter number: ") try: if 0 < int(i) <= len(options): honoring_user_input(options[int(i) - 1]) return options[int(i) - 1] # value selected except: pass return None let_user_pick(options)
5e6544c168eba12bfd9cc44e1734ec5dd5691dac
ajaycode/study
/class05/math/tests/test_temperature.py
827
3.5
4
# ..\tests>python test_fraction.py import unittest from unittest import TestCase __author__ = 'Ajay' import sys sys.path.append('..\\') from temperature import * class TestTemperature(TestCase): def test_celsius_from_fahrenheit(self): question, answer = celsius_from_fahrenheit (60) self.assertEqual("{}{}C".format (15.6, u'\N{DEGREE SIGN}'), answer) question, answer = celsius_from_fahrenheit (80) self.assertEqual("{}{}C".format (26.7,u'\N{DEGREE SIGN}'), answer) def test_fahrenheit_from_celsius (self): q, a = fahrenheit_from_celsius (60) self.assertEqual("140.0{}F".format (u'\N{DEGREE SIGN}'), a) q, a = fahrenheit_from_celsius (80) self.assertEqual("176.0{}F".format (u'\N{DEGREE SIGN}'), a) if __name__ == '__main__': unittest.main()
d60032107ecb73851a9abeb29cc1f5dedcf0b111
nicolassnider/udemy_machine_learning_r_python
/testProject/seccion08/tuplas.py
268
3.78125
4
p1=(1,) p2=(1,2,3,4) p3=(1,2,'e',3.1415) print(p1) print(p2) print(p3) print(p3[0:2]) a,b,c,d=p3 print(a) print(c) # L4 = list(p3) print(L4) p5=tuple(L4) print(p5) # L=tuple(input('Escribe numeros separados por comas: \n').split(',')) for n in L: print(2*int(n))
10c930abce072e05a3e4b1f1608f918c3b7c5afe
vinaybommana/twitter-analytics
/step_4/influentials_users.py
1,671
3.625
4
import csv import codecs import math def read_csv(filename): rows = list() with open(str(filename), "r") as c: csvreader = csv.reader(c) next(csvreader) for row in csvreader: rows.append(row) return rows def main(): second_rows = read_csv("step_two_output.csv") third_rows = read_csv("step_three_output.csv") unique_users = list() no_of_tweets = list() dict_of_user_retweet = dict() users = list() for second_row in second_rows: user = second_row[1] retweet = second_row[3] if user not in users: dict_of_user_retweet[user] = int(retweet) users.append(user) else: dict_of_user_retweet[user] += int(retweet) for third_row in third_rows: unique_users.append(third_row[1]) no_of_tweets.append(third_row[2]) dict_user_number_tweet = dict(zip(unique_users, no_of_tweets)) # print(dict_of_user_retweet) # serial_number, username@mention, userid, tweet_count, retweet_count, log(retweet_count) with codecs.open('step_four_output.csv', 'w+', 'utf-8') as o: o.write("Serial_number\t" + "," + "screen_name\t" + "," + "No of Tweets" + "," + "No of retweets" + "," + "log base 2 (retweet_count)\n") count = 1 for user, no_of_tweets in dict_user_number_tweet.items(): line = str(count) + "," + str(user) + "," + str(no_of_tweets) + "," + \ str(dict_of_user_retweet[user]) + "," + str(math.log(int(dict_of_user_retweet[user]), 2)) + "\n" o.write(line) count += 1 if __name__ == '__main__': main()
819cdf9e9e096ce54c22847b91c165171bba45be
Ruslan-Skira/PythonHW1
/listModification.py
4,631
4.375
4
"""Первая версия функции извлекает первый аргумент (args – это кортеж) и обходит остальную часть коллекции, отсекая первый элемент (нет никакого смысла сравнивать объект сам с собой, особенно если это довольно крупная структура данных).""" def min1(*args): current = args[0] for i in args[1:]: # all but the first element if i < current: current = i print(current) #min1(1,55,3,2) """Вторая версия позволяет интерпретатору самому выбрать первый аргумент и остаток, благодаря чему отпадает необходимость извлекать первый аргумент и получать срез.""" def min2(first,*rest): for arg in rest: if arg < first: first = arg return first #print(min2(999,44,24,66)) """Третья версия преобразует кортеж в список с помощью встроенной функции list и использует метод списка sort.""" def min3(*args): tmp = list(args) tmp.sort() return tmp[0] #print(min3(8,2,45)) """ обобщить функцию так, что она будет отыскивать либо минимальное, либо максимальное значение, определяя отношения элементов за счет интерпретации строки выражения с помощью таких средств, как встроенная функция eval """ def minmax(func, *args): current = args[0] for i in args[1:]: if func(i, current): current = i return current def lessthan(x, y): return x < y def grtrthan(x, y): return x > y #print(minmax(lessthan, 4,3,2,5,6)) #print(minmax(grtrthan, 4,3,2,5,6)) """found unic I don't know why but it is works only for 2 arg not for all shit""" def union (*args): res = [] for seq in args: for x in seq: if not x in res: res.append(x) return res s1, s2, s3 = "SPAM", "SCAM", "SLAM" print(union(s1, s2, s3)) """write map funciton""" def mymap(func, seq): res = [] for x in seq: res.append(func(x)) return res """lessons for the map function you have different city with temperature""" teps = [("berlin", 23), ("kharkiv", 33), ("barsa", 45)] c_to_t= lambda data: (data[0], (9/5)*data[1]+32)# formula fro the celsius to farengait print(list(map(c_to_t, teps))) """write your own reduce""" def myreduce(function, sequence): tally = sequence[0] for next in sequence[1:]: tally = function(tally, next) return tally #testing myreduce((lambda x, y: x + y), [1,2,3,4,5]) """write your own reduce with for""" L = [1,2,3,4,5] res = L[0] for x in L[1:]: res = res + x """create list with map function for n**2 in range (10)""" list(map((lambda x: x **2), (range(10)))) """wrire generator witch will be concatanate first letter of the spam SPAM like sS sP sA""" print([x + y for x in 'spam' for y in 'SPAM']) """"row in matrix""" M = [[1,2,3],[4,5,6],[7,8,9]] [row[1] for row in M] """matrix diagonal""" [M[i][i] for i in range(len(M))] """multiply 2 matrix""" res = [] for row in range(3): tmp = [] for col in range(3): tmp.append(M[row][col] * N[row][col]) res.append(tmp) res """write the same with lambda""" def f1(x): return x ** 2 def f2(x): return x ** 3 def f3(x): return x ** 4 L = [f1,f2,f3] for f in L: print(f(2)) print(L[0](3)) #answer M = [lambda z: z+1, lambda z: z+2, lambda z: z+3] for k in M: print(k(3)) print(M[2](3)) """create new list with modifided previous list""" counters_ = [1, 2, 3, 4] updated=[] for x in counters_: updated.append(x + 10) print(updated) """create the same with map function""" def inc(x) : x + 10 map(inc, counters_) """put lambda inside map""" list(map((lambda x: x + 3), counters_)) """range""" #1 line of odd numbers res = [] for i in range(1, 25, 2): res.append(i) print(res) #2use the list comprehension res = [x for x in range(1, 20, 2)] print(res) #3 exclude the squares and don't show squares multiples 3 res = [x ** 2 for x in range (1, 100, 2) if x %3 != 0] #4 you have dic = {'John': 1200, 'Paul': 1000, 'jones':450} # output the John = 1200 dic = {'John': 1200, 'Paul': 1000, 'jones':450} print = ("\n".join([f"{name} = {salary:d}" for name, salary in dic.items()]))
69c903b677e32ce1de2e292ef315f68c05361452
Ruslan-Skira/PythonHW1
/OOP/test_resource.py
349
3.703125
4
import unittest from math import pi import resource class TestCircleArea(unittest.TestCase): def test_area(self): # Test areas when radius > = 0 self.assertAlmostEqual(resource.circle_area(1), pi) self.assertAlmostEqual(resource.circle_area(55), 1) self.assertAlmostEqual(resource.circle_area(2.1), pi * 2.1**2)
f40434748d69a754a43d733df64129d39bc12e48
kevinmartinjos/mapleblow
/game.py
2,270
3.640625
4
import pygame from world import Hurdle from vector2 import Vector2 from pygame.locals import * from sys import exit from leaf import Leaf from wind import Wind import wx start=False def run_game(run_is_pressed): pygame.init() clock=pygame.time.Clock() screen=pygame.display.set_mode((640,480)) picture='leaf.png' blocks=[] i=0 while i<5: #blocks.append(Hurdle()) i=i+1 SCREEN_SIZE=(screen.get_width(),screen.get_height()) leaf_velocity=Vector2((0,0.5)) maple=Leaf(SCREEN_SIZE[0]/2,0,leaf_velocity,picture) print maple.w,maple.h gale=Wind(0) while True: for event in pygame.event.get(): if event.type==QUIT: exit() elif pygame.mouse.get_pressed()[0]: pos=pygame.mouse.get_pos() gale.get_dir(maple.get_pos(),pos) maple.wind_affect(gale) elif pygame.mouse.get_pressed()[2]: maple.x=SCREEN_SIZE[0]/2 maple.y=0 maple.velocity=Vector2((0,0.2)) clock.tick(60) screen.fill((255,255,255)) maple.render(screen) i=0 #while(i<5): #blocks[i].render(screen) maple.simple_collision_check() # i=i+1 maple.fall() pygame.display.update() def show_help(info_pressed): wx.MessageBox('Welcome to Maple Blow. Maple Blow is a simple program which lets you control a maple leaf floating in the air. Click anywhere inside the playing area and an imaginary wind (yeah, Imaginary) will blow from that point to the centre of the leaf.The closer you click to the leaf, the stronger the wind that blows. As of now, there is no particular \'objective\' associated with the program (that\' why i call it a program and not a game :D). In case the leaf go out of bounds, right click anywhere to reset','Help') app=wx.App() frame=wx.Frame(None,-1,'Leaves',size=(640,480)) def about_show(about_pressed): about_text=""" Maple Blow V 0.0001 Developer : Kevin Martin Jose License:Freeware/Open Source webpage:www.kevinkoder.tk""" wx.MessageBox(about_text,'About') panel=wx.Panel(frame,-1) run=wx.Button(panel,-1,'RUN',(280,220)) info=wx.Button(panel,0,'HELP',(280,180)) about=wx.Button(panel,1,'ABOUT',(280,260)) panel.Bind(wx.EVT_BUTTON,run_game,id=run.GetId()) panel.Bind(wx.EVT_BUTTON,about_show,id=about.GetId()) panel.Bind(wx.EVT_BUTTON,show_help,id=info.GetId()) frame.Show() app.MainLoop()
5234c1163f18bfd1e095b287f5a75ec97a37a898
tfmorris/wrangler
/runtime/python/wrangler/sort.py
1,806
3.5
4
from transform import Transform def mergesort(list, comparison): if len(list) < 2: return list else: middle = len(list) / 2 left = mergesort(list[:middle], comparison) right = mergesort(list[middle:], comparison) return merge(left, right, comparison) def merge(left, right, comparison): result = [] i ,j = 0, 0 while i < len(left) and j < len(right): if(comparison(left[i], right[i]) == 1): result.append(right[j]) j += 1 else: result.append(left[i]) i += 1 result += left[i:] result += right[j:] return result class Sort(Transform): def __init__(self): super(Sort,self).__init__() self['direction'] = [] self['as_type'] = [] def apply(self, tables): columns = self.get_columns(tables) table = tables[0] types = self['as_type'] directions = [d for d in self['direction']] for d in range(len(self['direction']), len(columns)): directions.append('asc') directions = [(1 if d=='asc' else -1) for d in directions] def sort_fn(a, b): for i in range(0, len(columns)): col = columns[i] result = types[i].compare(col[a], col[b]); if not result == 0: return directions[i]*result if(a<b): return -1 if(a==b): return 0 return 1; # sorted_rows = mergesort(range(0, table.rows()), sort_fn) sorted_rows = range(0, table.rows()) sorted_rows.sort(sort_fn) results = [columns[0][i] for i in sorted_rows] new_table = table.slice(0, table.rows()) for col in range(0, table.cols()): column = table[col]; new_column = new_table[col] for row in range(0, table.rows()): new_column[row] = column[sorted_rows[row]] table.clear() for col in new_table: table.insert_column(col, {})
72cdf859ab9d5adcbddf25295b4da9dea6015c90
EdwardTFS/TensorflowExamples
/example1.py
999
3.84375
4
#based on https://developers.google.com/codelabs/tensorflow-1-helloworld #fitting a linear function import sys print("Python version:",sys.version) import tensorflow as tf import numpy as np print("TensorFlow version:", tf.__version__) from tensorflow import keras #create model model = keras.Sequential([keras.layers.Dense(units=1, input_shape=(1,))]) #compile model model.compile(optimizer='sgd', loss='mean_squared_error') #function for creating data f = lambda x: x * 3 + 1 #learn data xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float) ys = f(xs) #test data x_test = np.array([-0.5, 0.5, 1.5, 2.5, 3.5], dtype=float) y_test = f(x_test) #fit 1 print("FIT") model.fit(xs, ys, epochs=20) #evaluate after fit 1 print("EVALUATE") model.evaluate(x_test, y_test, verbose=2) #fit 2 print("FIT2") model.fit(xs, ys, epochs=100) #evaluate after fit 2 print("EVALUATE2") model.evaluate(x_test, y_test, verbose=2) #predict print("PREDICT") print(model.predict(np.array(range(5))))
5d0b56e2c02f10090b62c259d5b7782c144eb840
prajwolshakya/visualization-sorting-algorithms
/shell_sort.py
762
3.859375
4
from cube import Run def shell_sort(): run = Run() arr = run.display() sublistcount = len(arr) // 2 while sublistcount > 0: for start in range(sublistcount): gap_insertion_sort(arr,start,sublistcount,run) #print(sublistcount) #print(arr) sublistcount = sublistcount // 2 return arr def gap_insertion_sort(arr, start, gap,run): for i in range(start+gap, len(arr),gap): currentvalue = arr[i] position = i while position >= gap and arr[position-gap] > currentvalue: run.remove(arr[position-gap],position-gap) run.remove(arr[position],position) arr[position] = arr[position-gap] run.add( arr[position],position) position = position-gap arr[position] = currentvalue run.add( arr[position],position) # shell_sort()
42167b22a0b27f5172f2c432979a397201cffde4
2508Fernan/Taller-3
/FernandaUshcasina_EstrellaPar_Turtle.py
507
3.921875
4
from turtle import* import time import turtle t= turtle.Pen() ##tamaño de la ventana turtle.setup (500,600) ##establecer el objeto en pantalla wn= turtle.Screen() ##color de la pantalla wn.bgcolor("pink") ##titulo de la pantalla wn.title("Estrella de Puntas Pares") a=int(input("ingrese un numero par:")) print(a) for x in range (1,21): t.pencolor("sky blue") t.pensize(4) t.forward(100) an=180/a ang=180 - an t.left(ang) turtle.getscreen()._root.mainloop()
045cc9ae2292052a918ccca9ab13c76b442ea0bc
SamSweere/MRS
/gui/localization_path.py
2,861
3.578125
4
import pygame import math # Draws a dashed curve # Works by using the fraction variable to keep track of the dash strokes # fraction from 0 to 1 means dash # fraction from 1 to 2 means no dash def draw_dashed_curve(surf, color, start, end, fraction, dash_length=10): start = pygame.Vector2(start) end = pygame.Vector2(end) delta = end - start length = delta.length() if length < 0.0000001: return fraction + length new_fraction = fraction + length / dash_length slope = delta / length if fraction < 1: # If we're in the middle of drawing an dash, finish or continue it dash_end = start + slope * (min(1 - fraction, new_fraction - fraction)) * dash_length pygame.draw.line(surf, color, start, dash_end, 2) # Draw the remaining full-dashes for index in range(2, int(new_fraction), 2): dash_start = start + (slope * index * dash_length) dash_end = start + (slope * (index + 1) * dash_length) pygame.draw.line(surf, color, dash_start, dash_end, 2) if (new_fraction % 2) < 1: # There is still an half finished dash left to draw dash_start = start + slope * int(new_fraction - fraction) * dash_length pygame.draw.line(surf, color, dash_start, end, 2) return new_fraction % 2 class LocalizationPath: def __init__(self, game): self.game = game self.robot = game.robot self.localizer = self.robot.localizer self.path_surface = pygame.Surface((game.screen_width, game.screen_height), pygame.SRCALPHA) self.path_color = pygame.Color('orange') self.old_pos = (self.localizer.state_mu[0], self.localizer.state_mu[1]) self.passed_time = 0 self.dash_fraction = 0 def update(self, delta_time): new_pos = (self.localizer.state_mu[0], self.localizer.state_mu[1]) self.dash_fraction = draw_dashed_curve(surf=self.path_surface, color=self.path_color, start=self.old_pos, end=new_pos, fraction=self.dash_fraction) self.old_pos = new_pos # Freeze the uncertainty ellipse after a set amount of time self.passed_time += delta_time if self.passed_time > 2: self.__draw_uncertainty_ellipse__(self.path_surface) self.passed_time = 0 def draw(self, surface): surface.blit(self.path_surface, (0,0), (0,0, self.game.screen_width, self.game.screen_height)) self.__draw_uncertainty_ellipse__(surface) def __draw_uncertainty_ellipse__(self, surface): x_mu = self.localizer.state_mu[0] y_mu = self.localizer.state_mu[1] x_std = self.localizer.state_std[0,0] y_std = self.localizer.state_std[1,1] pygame.gfxdraw.ellipse(surface, int(x_mu), int(y_mu), int(x_std), int(y_std), self.path_color)
4934d8f72ee6a0b00a6350c29e00f9994ef862ed
marccathomen/troccas
/app/card.py
516
3.5625
4
class Card: def __init__(self, id, power, value, suit, label): self.id = id # unique identification number self.power = power # beating power # value of the card in points self.value = value # suit of the card [r osa,s pada,c uppa,b astun,t rocca,n arr] self.suit = suit # label as on the real card [1,2,3,...,9,10,b uod, c cavagl, f emna, r etg, n arr, 1,2,...,20,21] self.label = label def show(self): print(self.label, self.suit)
1e37be68e28933fc50eb1eff40c74f6fb2d08da0
Krikiba/ATM
/fonction_atm.py
466
3.515625
4
def withdraw(request): i=0 liste=[100,50,10,5,4,3,2,1] for lis in liste: if request>=lis : request-=lis return request else : i+=1 def atm(money,request): balence=request print "Current balance =" +str(money) while request>0: if request>money : print ("le montant n'existe pas en ATM") break else : d=request request=withdraw(request) print "give " +str(d-request) return money-balence print atm(500,455)
3aeec4d5aae9f02d788af92f97af7e1ad5453940
mhurtad14/1500-intergration
/intergration project version 2.py
6,185
4
4
#Mijail Hurtado #Integration Project #COP 1500 #Professor Vanselow import math def get_bmr(): gender = input("What is your gender: M or F?") age = int(input("What is your age?")) height = int(input("What is your height in inches?")) weight = (int(input("What is your weight in pounds?"))) bmr_wght_constant = 4.536 bmr_hght_constant = 15.88 bmr_age_constant = 5 if gender == 'M': bmr = int((bmr_wght_constant * weight) + (bmr_hght_constant * height) - (bmr_age_constant * age) + 5) elif gender == 'F': bmr = int((bmr_wght_constant * weight) + (bmr_hght_constant * height) - (bmr_age_constant * age) - 161) else: print("Please try again.") return bmr def get_daily_calorie_requirement(bmr): dcr_1 = 1.2 dcr_2 = 1.375 dcr_3 = 1.55 dcr_4 = 1.725 dcr_5 = 1.9 act_lvl = int(input("What is your activity level?")) if act_lvl == 1: daily_calorie_requirement = int(bmr * dcr_1) elif act_lvl == 2: daily_calorie_requirement = int(bmr * dcr_2) elif act_lvl == 3: daily_calorie_requirement = int(bmr * dcr_3) elif act_lvl == 4: daily_calorie_requirement = int(bmr * dcr_4) elif act_lvl == 5: daily_calorie_requirement = int(bmr * dcr_5) else: print("Please choose a number 1-5.") return daily_calorie_requirement def main(): print("Hello, welcome to my intergration project!") print("The purpose of this program is to help the user reach their goal and provide helpful suggestions.") print("It will do this by taking your age, gender, height and your level of physical activity in order to calculate your Basal Metabolic Rate(BMR)") print("Your BMR is how many calories you burn in a single day. Combining your BMR with your goals we can suggest a meal plan and excercises that will help reach your goals") print("Let's get started! I will start by asking you a few questions in order to make a profile and give you the best informed advice.") bmr = get_bmr() print("Your BMR is: ", bmr) print("Great! Now that we have calculated your Basal Metabolic Rate, let's calculate your daily calorie requirement!") print("This is the calories you should be taking in to maintain your current weight") print("How active are you on a scale of 1-5?") print("1 being you are sedentary (little to no exercise)") print("2 being lightly active (light exercise or sports 1-3 days a week)") print("3 being moderately active (moderate exercise 3-5 days a week)") print("4 being very active (hard exercise 6-7 days a week)") print("5 being super active (very hard exercise and a physical job)") print("Exercise would be 15 to 30 minutes of having an elevated heart rate.") print("Hard exercise would be 2 plus hours of elevated heart rate.") daily_calorie_requirement = get_daily_calorie_requirement(bmr) print("The amount of calories you should be consuming are: ", daily_calorie_requirement) print("Now that we have calculated your daily caloric requirement, let's figure out your goals.") print("If you are trying to lose weight enter 1, if you are trying to maintain enter 2 or if you are trying to gain weight enter 3.") goal = int(input("What is the goal you are setting for yourself?")) if goal == 1: print("In order to reach your goal safely you will have to reduce your daily caloric intake by 500 in order to lose one pound a week") print("In order to reach your goal, will keep track of the amount of calories you consume.") print("The best way to keep track of your calories is to record the amount of calories consumed after every meal.") cal_goal_1 = daily_calorie_requirement - 500 cal_consumed_1 = 0 while cal_goal_1 >= cal_consumed_1: cal_taken = int(input("How many calories have was your last meal?")) cal_consumed_1 += cal_taken if cal_goal_1 <= cal_consumed_1: print("Congratulations! You have reached your goal for the day by taking in", cal_consumed_1, "calories!") elif goal == 2: print("If you are trying to maintain your current level then just continue taking in the same about of calories daily.") print("In order to reach your goal, will keep track of the amount of calories you consume.") print("The best way to keep track of your calories is to record the amount of calories consumed after every meal.") cal_goal_2 = daily_calorie_requirement cal_consumed_2 = 0 while cal_goal_2 >= cal_consumed_2: cal_taken = int(input("How many calories have was your last meal?")) cal_consumed_2 += cal_taken if cal_goal_2 <= cal_consumed_2: print("Congratulations! You have reached your goal for the day", cal_consumed_2, "calories!") elif goal == 3: print("If you want to bulk up and build lean muscle mass you need to consume 300 to 500 more calories than your daily metabolic requirement") print("If you are just starting out, I would suggest you begin with 300 calories as taking more calories than need will lead to fat also being produced.") print("In order to reach your goal safely you will have to increase your daily caloric intake by 300 in order to gain one half a pound to half a pound a week") print("In order to reach your goal, will keep track of the amount of calories you consume.") print("The best way to keep track of your calories is to record the amount of calories consumed after every meal.") cal_goal_3 = daily_calorie_requirement + 300 cal_consumed_3 = 0 while cal_goal_3 >= cal_consumed_3: cal_taken = int(input("How many calories have was your last meal?")) cal_consumed_3 += cal_taken if cal_goal_3 <= cal_consumed_3: print("Congratulations! You have reached your goal for the day!",cal_consumed_3, "calories!") else: print("Please try again.") main()
aec194198be1a68b82f0fa306aff480d9e4fc396
rbusquet/advent-of-code
/aoc_2021/day11.py
1,880
3.53125
4
from itertools import count, product from pathlib import Path from typing import Iterator Point = tuple[int, int] def neighborhood(point: Point) -> Iterator[Point]: x, y = point for i, j in product([-1, 0, 1], repeat=2): if i == j == 0: continue yield x + i, y + j def flash(point: Point, universe: dict[Point, int], flashed: set[Point]) -> None: for n in neighborhood(point): if n not in universe: continue universe[n] += 1 if universe[n] > 9 and n not in flashed: flashed.add(n) flash(n, universe, flashed) def part_1_and_2() -> tuple[int, int]: universe = dict[Point, int]() with open(Path(__file__).parent / "input.txt") as file: for i, line in enumerate(file): for j, brightness in enumerate(line.strip()): universe[i, j] = int(brightness) flashes_after_100 = 0 for step in count(): flashed = propagate_energy(universe) if step <= 99: flashes_after_100 += len(flashed) if len(flashed) == 100: break # zero flashed for point in universe: if universe[point] > 9: universe[point] = 0 return flashes_after_100, step def propagate_energy(universe: dict[Point, int]) -> set[Point]: for point in universe: universe[point] += 1 flashed = set[Point]() while True: flashing = [ point for point in universe if universe[point] > 9 and point not in flashed ] if not flashing: break for point in flashing: flashed.add(point) for n in neighborhood(point): if n not in universe: continue universe[n] += 1 return flashed if __name__ == "__main__": print(part_1_and_2())
c1232f17b340a952c18208ffe66c59ad3e5b9243
rbusquet/advent-of-code
/aoc_2015/day1.py
622
3.640625
4
from pathlib import Path def part_1() -> int: with open(Path(__file__).parent / "input.txt") as file: floor = 0 while step := file.read(1): floor += step == "(" or -1 return floor def part_2() -> int: with open(Path(__file__).parent / "input.txt") as file: floor = 0 position = 1 while step := file.read(1): floor += step == "(" or -1 if floor == -1: return position position += 1 raise Exception("Something went wrong") if __name__ == "__main__": print(part_1()) print(part_2())
48a7d98ef8acfdd3fc5c7ace832810e2fe3c6092
rbusquet/advent-of-code
/aoc_2020/day3.py
771
3.65625
4
from functools import reduce from itertools import count from operator import mul from typing import Iterator def read_file() -> Iterator[str]: with open("./input.txt") as f: yield from f.readlines() def count_trees(right: int, down: int) -> int: counter = count(step=right) total_trees = 0 for i, line in enumerate(read_file()): if i % down != 0: continue line = line.strip() position = next(counter) % len(line) total_trees += line[position] == "#" return total_trees print("--- part 1 ---") print(count_trees(3, 1)) print("-- part 2 ---") vals = [ count_trees(1, 1), count_trees(3, 1), count_trees(5, 1), count_trees(7, 1), count_trees(1, 2), ] print(reduce(mul, vals))
9abc4c7c745318043728354a75b0e6cc58e532e7
rbusquet/advent-of-code
/aoc_2020/day24.py
2,339
3.78125
4
from collections import defaultdict from dataclasses import dataclass @dataclass class Cube: x: int y: int z: int def __add__(self, cube: "Cube") -> "Cube": return Cube(self.x + cube.x, self.y + cube.y, self.z + cube.z) @classmethod def new(cls) -> "Cube": return Cube(0, 0, 0) # https://www.redblobgames.com/grids/hexagons/#neighbors-cube cube_directions = { "e": Cube(+1, -1, 0), "ne": Cube(+1, 0, -1), "nw": Cube(0, +1, -1), "w": Cube(-1, +1, 0), "sw": Cube(-1, 0, +1), "se": Cube(0, -1, +1), } def read_file(): with open("./input.txt") as f: yield from (c.strip() for c in f.readlines()) hex_grid = defaultdict[Cube, bool](bool) def find_cube(instruction) -> Cube: p = 0 cube = Cube.new() while p < len(instruction): direction = instruction[p : p + 1] if direction not in cube_directions: direction = instruction[p : p + 2] p += 1 p += 1 offset = cube_directions[direction] cube += offset # print(cube) return cube hex_grid = defaultdict[Cube, bool](bool) for instruction in read_file(): cube = find_cube(instruction) hex_grid[cube] = not hex_grid[cube] print(sum(hex_grid.values())) def neighborhood(cube: Cube): yield cube for direction in cube_directions: yield cube + cube_directions[direction] def full_cycle(grid, days): for _ in range(days): cube_to_active_count = defaultdict[Cube, int](int) for cube in grid: if not grid[cube]: continue for n in neighborhood(cube): # neighborhood contains cube and all its neighbors. # `cube_to_active_count[n] += n != cube` ensures # active cubes without active neighbors are counted # and proper deactivated by underpopulation in the # next for-loop. cube_to_active_count[n] += n != cube and grid[cube] for n, count in cube_to_active_count.items(): if grid[n]: if count == 0 or count > 2: grid[n] = False else: if count == 2: grid[n] = True return grid final = full_cycle(hex_grid, 100) print(sum(final.values()))
bedc3696e18c0810fffc6e0095d884de1c42b970
rbusquet/advent-of-code
/aoc_2020/day17.py
1,673
3.578125
4
from collections import defaultdict from itertools import product initial = """ ####.#.. .......# #..##### .....##. ##...### #..#.#.# .##...#. #...##.. """.strip() def neighborhood(*position: int): for diff in product([-1, 0, 1], repeat=len(position)): neighbor = tuple(pos + diff[i] for i, pos in enumerate(position)) yield neighbor def full_cycle(initial, dimensions): space = defaultdict(lambda: ".") padding = (0,) * (dimensions - 2) for x, line in enumerate(initial.splitlines()): for y, state in enumerate(line): cube = (x, y) + padding space[cube] = state for _ in range(6): cube_to_active_count = defaultdict(int) for cube in space: if space[cube] == ".": continue for n in neighborhood(*cube): # neighborhood contains cube and all its neighbors. # `cube_to_active_count[n] += n != cube` ensures # active cubes without active neighbors are counted # and proper deactivated by underpopulation in the # next for-loop. cube_to_active_count[n] += n != cube and space[cube] == "#" for n, count in cube_to_active_count.items(): if space[n] == "#": if count in [2, 3]: space[n] = "#" else: space[n] = "." elif space[n] == "." and count == 3: space[n] = "#" return sum(state == "#" for state in space.values()) print("--- part 1 ---") print(full_cycle(initial, 3)) print("--- part 2 ---") print(full_cycle(initial, 4))
dbcf6b5acffdf9a54c1a18efc214dcaed6bae1c7
HanniSYC/Practice_code
/二维数组中的查找练习.py
1,405
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/11/3 下午9:38 # @Author : Hanni # @Fun : 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。 # 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 print '欢迎来到二维数组中的查找v1.0 @星辰\n' class Solution: def Find(self, target, array): rowcount = len(array) colcount = len(array[0]) if colcount - 1 == 0: #二维数组为空 return False for i in range(rowcount -1 , -1, -1):#从左下角开始检索,到右上角结束,每次移动一个位置 if target > array[i][0]:#要查找的数字大于左下角的数字 for j in range(colcount):#右移比较 if target == array[i][j]:#找到,返回True return True elif target == array[i][0]:#要查找的数字等于左下角的数字,返回True return True #否则上移 return False array = [[1,3,5,7],[2,4,6,8],[3,6,9,12]] #循环显示二维数组 for i in range(0, 3): for j in range(0, 4): print array[i][j], print target = input('请输入待检测的数字:') s = Solution() print(s.Find(target, array))
98144aeef549d072b82e1ec8b6fe04b231c4016d
rollingonroad/Python005-01
/week06/assignment.py
1,777
3.984375
4
from abc import ABCMeta, abstractmethod # 动物 class Animal(metaclass=ABCMeta): def __init__(self, food_type, body_size, character): self.food_type = food_type self.body_size = body_size self.character = character @property def is_fierce(self): return self.body_size != '小' and self.food_type == '食肉' and self.character == '凶猛' @abstractmethod def is_pettable(self): pass # 猫 class Cat(Animal): sound = 'Meow' def __init__(self, name, food_type, body_size, character): super().__init__(food_type, body_size, character) self.name = name @property def is_pettable(self): return not self.is_fierce # 狗 class Dog(Animal): sound = 'Bark' def __init__(self, name, food_type, body_size, character): super().__init__(food_type, body_size, character) self.name = name @property def is_pettable(self): return not self.is_fierce # 动物园类 class Zoo(object): def __init__(self, name): self.name = name # 使用set防止单个动物实例增加多次 self.animals = set() def add_animal(self, animal): # 同一只动物只会记录一次 self.animals.add(animal) # 用类名作为属性名,支持hasattr self.__setattr__(type(animal).__name__, True) if __name__ == '__main__': # 实例化动物园 z = Zoo('时间动物园') # 实例化一只猫,属性包括名字、类型、体型、性格 cat1 = Cat('大花猫 1', '食肉', '小', '温顺') # 增加一只猫到动物园 z.add_animal(cat1) # 动物园是否有猫这种动物 have_cat = hasattr(z, 'Cat') # 测试abc # a = Animal('a', 'b', 'c')
fc9366b9c351ebcc8ee1408a82cbb2a051785b40
schardt8237/Codecademy
/Data Science Career Path/Unit 14: Learn Statistics With Python/life_expectancy_by_country.py
840
3.75
4
import codecademylib3_seaborn import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv("country_data.csv") #print(data.head()) life_expectancy = data["Life Expectancy"] life_expectancy_quartiles = np.quantile(life_expectancy, [0.25, 0.5, 0.75]) print(life_expectancy_quartiles) #plt.hist(life_expectancy) #plt.show() gdp = data["GDP"] median_gdp = np.quantile(gdp, 0.5) low_gdp = data[data['GDP'] <= median_gdp] high_gdp = data[data['GDP'] > median_gdp] low_gdp_quartiles = np.quantile(low_gdp["Life Expectancy"], [0.25, 0.5, 0.75]) high_gdp_quartiles = np.quantile(high_gdp["Life Expectancy"], [0.25, 0.5, 0.75]) plt.hist(high_gdp["Life Expectancy"], alpha = 0.5, label = "High GDP") plt.hist(low_gdp["Life Expectancy"], alpha = 0.5, label = "Low GDP") plt.legend() plt.show()
e1ecce71b4e466e4028e2528e627a61486137ee5
IzMasters/timefuzz
/timefuzz.py
3,720
3.546875
4
class Namespace: def __init__(self, **names): for name in names.keys(): setattr(self, name, names[name]) # helper class for "speaking" units.. # singular and plural are the respective forms, plural defaults to a regular "s"-plural # vowel_onset determines whether or not to use "an" for the indefinite article class Word: def __init__( self, singular, plural = None, vowel_onset = False): self.singular = singular self.plural = plural or singular + "s" self.vowel_onset = vowel_onset class TimeUnit: def __init__( self, value, limit, precisions, word): self.value = value self.limit = limit self.precisions = precisions self.word = word duration = Namespace() setattr(duration, "second", 1) setattr(duration, "minute", duration.second * 60) setattr(duration, "hour", duration.minute * 60) setattr(duration, "day", duration.hour * 24) setattr(duration, "week", duration.day * 7) setattr(duration, "year", int(duration.day * 365.25)) setattr(duration, "month", duration.year // 12) setattr(duration, "decade", duration.year * 10) setattr(duration, "century", duration.year * 100) unit = Namespace( moment = TimeUnit(0, duration.second, [], Word("moment")), second = TimeUnit(duration.second, duration.minute, [(5,1),(30,5),(60,10),(120,30)], Word("second")), minute = TimeUnit(duration.minute, duration.hour, [(5,1),(30,5),(60,10),(120,30)], Word("minute")), hour = TimeUnit(duration.hour, duration.day, [(6,1),(24,3)], Word("hour", vowel_onset = True)), day = TimeUnit(duration.day, duration.week, [(6,1)], Word("day")), week = TimeUnit(duration.week, 2 * duration.month, [(4,1)], Word("week")), month = TimeUnit(duration.month, duration.year, [(12,1),(24,6)], Word("month")), year = TimeUnit(duration.year, 2 * duration.decade, [(10,1),(100,10),(1000,100)], Word("year")), decade = TimeUnit(duration.decade, duration.century, [(9,1)], Word("decade")), century = TimeUnit(duration.century, -1, [(1,1)], Word("century", plural = "centuries"))) # all limits in a central place limits = dict([(getattr(unit, u), getattr(unit, u).limit) for u in vars(unit)]) # the inverse dictionary to look up units by limits inv_limits = dict([(v,k) for (k,v) in limits.items()]) def get_unit(time): """ The appropriate time unit to use for a given duration in seconds, as defined via the limits dictionary above.""" thresholds = list(limits.values()) thresholds.sort() for t in thresholds: if time < t: return inv_limits[t] return unit.century def fuzz(time, granularity=1): """ A human-readable approximate representation of a time duration. The granularity parameter can be used to fine-tune granularity. values > 1 mean less precision; values < 1 mean more precision.""" # first determine appropriate time unit... t_unit = get_unit(time) # next, the magnitude given our time unit value = 0 if t_unit == unit.moment else int(time // t_unit.value) # lastly, figure out the custom precision stuff p = t_unit.precisions p.sort() try: thresh = value * granularity key = next(filter(lambda x: x > thresh, (x[0] for x in p))) precision = dict(p)[key] except StopIteration: # don't use a numeral at all if number too high precision = 0 # values of 0 are used to express "unspecified" as in: "months ago" value = 0 if (precision == 0) else ((value // precision) * precision) # natural lanugage stuff: spit out the correct word forms and such: # TODO make this more configurable if value == 0: return t_unit.word.plural # "months ago", not "0 months" or "0 month" if value == 1: return "an " if t_unit.word.vowel_onset else "a " + t_unit.word.singular return "{} {}".format( value, t_unit.word.plural)
7c7e46570e38bc54ba1c1fabd9c11de78f8f27b9
CharlieGodfrey1/Python-practice
/divisors practice.py
409
4
4
#user enters number num=int(input("Please enter a number: ")) #works out the intigers from 1 to the entered number listrange = list(range(1,num+1)) #list of divisors divisors = [] #for loop to work out divisors for i in listrange: #divides the entered number by the list range integers and if they have a modulas of 0 they are divisers if num % i == 0: divisors.append(i) print(divisors)
cb69532884a199d684d49739f1bc17e3076600a8
calcsam/toyprojects
/socialwire_example.py
3,142
3.65625
4
# in response to http://www.socialwire.com/exercise1.html; took me about 2 hours to code # python 2.7 def test(aString): stillNumber = True expectedExpressions = 0 allExp = [] currentExp = [] for char in aString: #print "iterate" + char if is_number(char) and stillNumber: expectedExpressions = expectedExpressions*10 + float(char) else: if stillNumber == True: # only should enter the else if loop once stillNumber = False if expectedExpressions == 0: expectedExpressions = 1 if notInSet(char): return "INVALID, " + char + " NOT VALID CHARACTER" currentExp = push(char, currentExp) #print currentExp if completeTree(currentExp): allExp.append(currentExp) currentExp = [] if len(allExp) == 0: return "INVALID, NO FULL EXPRESSIONS GIVEN" if not completeTree(allExp[len(allExp)-1]): return "INVALID, LAST EXPRESSION " + str(allExp[len(allExp)-1]) + "NOT COMPLETE" if len(allExp) != expectedExpressions: #print allExp return "EXPECTED "+ str(expectedExpressions) + " EXPRESSIONS. GOT " + str(len(allExp)) print "PARSE TREE: " + str(len(allExp)) + " EXPRESSION(S):", print allExp return "VALID" def push(element,currentTree): # put element into our Tree, using recursion to push it down where necessary if not currentTree: # if empty #print "hello" currentTree.append([element]) return currentTree if currentTree[0] == ["Z"]: if len(currentTree) == 1: currentTree.append([element]) return currentTree if len(currentTree) == 2: return [currentTree[0], push(element,currentTree[1])] if currentTree[0] in (["M"],["K"],["P"],["Q"]): if len(currentTree) == 1: currentTree.append([element]) return currentTree if len(currentTree) == 2 and not completeTree(currentTree[1]): return [currentTree[0], push(element,currentTree[1])] if len(currentTree) == 2 and completeTree(currentTree[1]): currentTree.append([element]) return currentTree if len(currentTree) == 3: return [currentTree[0], currentTree[1], push(element,currentTree[2])] if currentTree[0] in ("M","K","P","Q", "Z"): return [[currentTree[0]],[element]] def completeTree(currentTree): # determines if tree is complete using recursion if not currentTree: # if empty return False if currentTree[0] in (["M"],["K"],["P"],["Q"]) and len(currentTree) == 3 and completeTree(currentTree[1]) and completeTree(currentTree[2]): return True elif currentTree[0] == ["Z"] and len(currentTree) == 2 and completeTree(currentTree[1]): return True elif currentTree[0] in (["a"],["b"],["c"],["d"],["e"],["f"],["g"],["h"],["i"],["j"],"a","b","c","d","e","f","g","h","i","j") and len(currentTree) == 1: return True #print "savory" #print currentTree return False def notInSet(char): # determine if valid input if char in ("a","b","c","d","e","f","g","h","i","j","M","K","P","Q","Z"): return False return True def is_number(s): #okay, this should be self-explanatory try: float(s) return True except ValueError: return False inputString = raw_input() while inputString != "BREAK": print test(inputString) inputString = raw_input()
63825db8fd9cd5e9e6aaa551ef7bfec29713a925
Rohit439/pythonLab-file
/lab 9 .py
1,686
4.28125
4
#!/usr/bin/env python # coding: utf-8 # ### q1 # In[2]: class Triangle: def _init_(self): self.a=0 self.b=0 self.c=0 def create_triangle(self): self.a=int(input("enter the first side")) self.b=int(input("enter the second side")) self.c=int(input("enter the third side")) def print_sides(self): print("first side:",self.a,"second side:",self.b,"third side",self.c) x=Triangle() x.create_triangle() x.print_sides() # ### q2 # In[4]: class String(): def _init_(self): self.str1="" def inputstr(self): self.str1=input("enter the string") def printstr(self): print(self.str1) x=String() x.inputstr() x.printstr() # ### q3 # In[4]: class Rectangle: length=0.0 width=0.0 per=0.0 def rect_values(self,l,w): self.length=l self.width=w def perimeter(self): self.per=2*self.length+self.width return(self.per) r1=Rectangle() r1.rect_values(10,20) k=r1.perimeter() print("the perimeter of rectangle is",k) # ### q4 # In[6]: class Circle: radius=0.0 area=0.0 peri=0.0 def _init_(self,radius): self.radius=radius def area(self): self.area=3.14*self.radius*self.radius return(self.area) def perimeter(self): self.peri=2*3.14*self.radius return(self.peri) c1=Circle() c1._init_(4) a=c1.area() p=c1.perimeter() print("the area and perimeter of circle are:",a,p) # ### q5 # In[7]: class Class2: pass class Class3: def m(self): print("in class3") class Class4(Class2,Class3): pass obj=Class4() obj.m() # In[ ]:
100419d5cdb569188d4c1231a7e603bc6c16353b
racheltsitomeneas/python_homework
/Python Homework/PyBank/Analysis/PyBank.py
1,915
3.84375
4
#pybank homework import os import csv #variables months = [] profit_loss_changes = [] count_months = 0 net_profit_loss = 0 previous_month_profit_loss = 0 current_month_profit_loss = 0 profit_loss_change = 0 os.chdir(os.path.dirname(__file__)) budget_data_csv_path = os.path.join("budget_data.csv") #csv read with open(budget_data_csv_path, newline="") as csvfile: csv_reader = csv.reader(csvfile, delimiter=",") csv_header = next(csvfile) for row in csv_reader: count_months += 1 current_month_profit_loss = int(row[1]) net_profit_loss += current_month_profit_loss if (count_months == 1): previous_month_profit_loss = current_month_profit_loss continue else: profit_loss_change = current_month_profit_loss - previous_month_profit_loss months.append(row[0]) profit_loss_changes.append(profit_loss_change) previous_month_profit_loss = current_month_profit_loss sum_profit_loss = sum(profit_loss_changes) average_profit_loss = round(sum_profit_loss/(count_months - 1), 2) highest_change = max(profit_loss_changes) lowest_change = min(profit_loss_changes) highest_month_index = profit_loss_changes.index(highest_change) lowest_month_index = profit_loss_changes.index(lowest_change) best_month = months[highest_month_index] worst_month = months[lowest_month_index] #final print print("Financial Analysis") print(f"Total Months: {count_months}") print(f"Total: ${net_profit_loss}") print(f"Average Change: ${average_profit_loss}") print(f"Greatest Increase in Profits: {best_month} (${highest_change})") print(f"Greatest Decrease in Losses: {worst_month} (${lowest_change})")
b3717109102391a9eed15d86869e05c0866d6c29
MusawerAli/python_practise
/nesteddict.py
512
3.84375
4
#nested dictionary parent_child = { "child1": { "name": "jorg", "age": 22 }, "child": { "name": "bush", "age": 30 } } parent_brother = { "brother1": { "name": "jonze", "age": 43 }, "brother2": { "name": "bus", "age": 65 } } print(parent_brother) print('create one dictionary from multiole dict') parent_family = { 'parents_child': parent_child, 'parents_brotehr': parent_brother } print(parent_family)
34c328e731795ee17c1e887a966c33a6bf2ca327
MusawerAli/python_practise
/regex/regex.py
125
3.890625
4
import re txt = "The rain in Spain" x = re.search("^The.*Spain$", txt) print("Have a match") if (x) else print("no match")
644dd04680b280b1def7e3d5023e2dfa0a253161
MusawerAli/python_practise
/regex/endwithword.py
182
4.59375
5
import re str = "hello world" #Check if the string ends with 'world': x = re.findall("world$", str) if (x): print("Yes, the string ends with 'world'") else: print("No match")
ea81873f62f22fb784403d68c7c443a4b3749a40
MusawerAli/python_practise
/if_else.py
501
3.890625
4
a = 50 b =20 c = 54 d=50 if b > a: print("b is greater than b") elif c>a: print("c is grater than a") else: print("a is grater than b") #Short Hand if...Else print("A") if a > b else print("B") #print Multiple print("A") if a< d else print("=") if a == d else print("B") if a>b and d>b: print("Both are true") if a<b or c>a: print("one is true") if a > b: print("A grearter than b") if b > a: print("b is greater than b") elif a>b:
80656a2831924d203537b5788143bf03e149dd7d
lalitasharma04/Computer_Networks
/source codes/Bit_Stuffing_and_character_stuffing.py
4,154
3.984375
4
''' ============================================================================== Name :Lalita Sharma RNo :06 =============================================================================== Experiment :02 *************** Aim:Write a program for implementing Bit Stuffing and character stuffing ''' # to convert string into binary def toBinary(string): binary="" for char in string: ascii=ord(char) # print("ascii is {}".format(ascii)) sum=0 w=1 while ascii != 0: d=ascii % 2 sum=sum+d*w w=w*10 ascii=ascii//2 if len(str(sum))!=8: sum1='0'*(8-len(str(sum))) +str(sum) binary=binary+str(sum1) return binary # bit stuffing def DataAfterBitStuffing(b_str): stuffed="" count=0 indx=-1 for char in b_str: indx+=1 if int(char)==1: count=count+1 stuffed+=char elif int(char)!=1: count=0 stuffed+=char if count==5: print("index is {}".format(indx)) stuffed=stuffed[:indx+1] +'0' #adding a 0 indx+=1 count=0 return stuffed # returns a destuffed binary string def destuffing(stuffed_str): count=0 destuff='' highlight=1 #to skip a character after 5 1's for char in stuffed_str: if highlight==60: highlight=1 continue if int(char)==1: count+=1 destuff+=char elif int(char)!=1: count=0 destuff+=char if count==5: count=0 highlight=60 return destuff # to convert destuffed binary string to actual string def Back_to_str(binary_str): len1=8 ori='' ini=0 range1=len(binary_str)//8 for i in range(range1): sum=0 w=1 one_char=binary_str[ini:len1] one_char=int(one_char) while int(one_char)!=0: d=one_char%10 sum=sum+d*w w=w*2 one_char=one_char//10 ori+=chr(sum) ini=len1 len1+=8 return ori # returns a character stuffed string def stuffed_str_characterstuffing(string ,flag): ret='' for i in range(len(string)): if string[i]==flag : ret+=flag ret+=string[i] ret= flag+ret +flag return ret # returns the original string def destuffing_char(stuffed_str_char,flag): sliced_str=stuffed_str_char[1:len(stuffed_str_char)-1] #to remove first and last char ret='' for i in range(1,len(sliced_str)): if (sliced_str[i]==sliced_str[i-1]) and sliced_str[i-1]==flag: continue ret=ret+sliced_str[i-1] return ret+sliced_str[-1] # ********** driver function ******************** while(1): choice=int(input("Please enter your choice(1.bit stuffing \t 2.character stuffing\t 3.Quit)\n")) if choice ==1: string=input("Input data to sent?\n") binary_str=toBinary(string) print("binary string : {}".format(binary_str)) stuffed_str=DataAfterBitStuffing(binary_str) print("data after bit stuffing is ::{}".format(stuffed_str)) binary_str2=destuffing(stuffed_str) print("binary data after destuffing is :::{}".format(binary_str2)) originalstr=Back_to_str(binary_str2) print("string after destuffing is:: {}".format(originalstr)) elif choice==2: string=input("Input data to sent?\n") flag=input("Enter the flag character here..?") stuffed_str_char=stuffed_str_characterstuffing(string,flag) print("stuffed string::",stuffed_str_char) final_destuff_char=destuffing_char(stuffed_str_char,flag) print("Data after destuffing ::",final_destuff_char) else: print("********************** END **************************") break
63e1f1008273f5dcd65fd12e22b47886a6be3bec
lautaroGonzalez97/practica2
/ejercicio3.py
262
3.796875
4
texto="Tres tristes tigres, tragaban trigo en un trigal, en tres tristes trastos, tragaban trigo tres tristes tigres." letra = input("ingrese una letra") lista= texto.lower().replace(",","").split() for ele in lista: if ele[0] == letra: print(ele)
332b831f3602141a6dac113e04bf7caee197b9ce
bartkim0426/algorithm-study
/questions/leetcode_199.py
7,815
4.03125
4
# https://leetcode.com/problems/binary-tree-right-side-view/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right ''' TreeNode{ val:1, left: TreeNode{ val: 2, left: None, right: TreeNode{ val: 5, left: None, right: None, } ... } } ''' # 1차. list라고 생각하고 풀어서 class Solution: def rightSideView(self, root: TreeNode) -> List[int]: ''' # 초반에 root가 list로 잘못 알고 풀어서 실패 binary tree - nodes are incresing with 2**n: 1, 2, 4, 8 ... - Get tree length and "n": len(root) # solution 1: greedy searching - for loop for the root and add stack - add count for the power of 2 (2**n) - if the index is power of 2 -> add to index and make count to 0 - repeat till the end - time complex: O(n) becuase it search all root # solution 2: - return indexs are 0, 2, 6, 14, ... -> 2**n / += 2**(n+1) += 2**(n+2) - find all indexes of them - and return all from root - time complex: O(logn) because it search for power of 2 # solution ''' # solution 2: # find largest 2**n number: n = 0 result = [] q = [root] print(q) index = 0 while True: power = 2 ** n index =+ 2 ** n if index + 1 == len(root): break result.append(q[index]) return result # 2차. root로 풀었는데 실패 -> 이런건 면접관에게 물어볼 수 있으면 물어보면 좋을듯? class Solution: def rightSideView(self, root: TreeNode) -> List[int]: ''' # 초반에 root가 list로 잘못 알고 풀어서 실패 # root -> TreeNode object # solution 1: finding right only find right treenode till the end -> 이 방식으로는 오른쪽게 아닌데 왼쪽에만 있는 경우를 잡지 못함 ex. [1, 2] -> 2가 왼쪽이 아니고 right side로 취급됨 ''' # If no root, return empty list if not root: return [] result = [] while True: # add first value if not result: result.append(root.val) if not root.right: break result.append(root.right.val) root = root.right return result # 3차. solution 3으로 풀었는데 마지막 rightest value를 찾지 못해서 실패 class Solution: def rightSideView(self, root: TreeNode) -> List[int]: ''' # 초반에 root가 list로 잘못 알고 풀어서 실패 # root -> TreeNode object # solution 1: finding right only find right treenode till the end -> 이 방식으로는 오른쪽게 아닌데 왼쪽에만 있는 경우를 잡지 못함 ex. [1, 2] -> 2가 왼쪽이 아니고 right side로 취급됨 # solution 2: greddy 전체 tree를 모두 읽어서 리스트 형태로 만들고 푸는 방식 O(n**2) -> 비효율적임 tree를 한 번 읽어서 바로 처리해야 O(n) 형태가 나옴 # solution 3: read tree and find power of 2 - read tree sequentially (left -> right -> left-left -> left-right ...) - memorize the order (index) - if the index is 1, 3, 7, 15 ... (2**n += 2**(n+1) ...) - add it to result - if end before complete 2**n -> add last tree value - O(n) because it read all the nodes # solution 4: find right tree + if not exist, return left - if right tree exits, the whole tree till now must be comopleted - if right tree not exits, the tree is ended: add the most rightest value - find rightest value: is it impossible without read whole tree?? # solution 5: find rightest value from all floor - add node for specific floor - add rightest value to result per floor (last input) ''' # solution 3: result = [] # indexes list indexes = [] index = 0 # number of nodes in the tree is range [0..100] -> max index will be 2**100 for i in range(100): index += 2**i indexes.append(index) prev = None next_node = None left = True index = 1 while True: # First node if index == 1: prev = current current = root left = False # find next root if left: current = root.left next_node = root.right # if right else: current = root.right next_node = nex if index in indexes: result.append(current.val) prev = current index += 1 # 5번째 풀이 from collections import deque class Solution: def rightSideView(self, root: TreeNode) -> List[int]: ''' # 초반에 root가 list로 잘못 알고 풀어서 실패 # root -> TreeNode object # solution 1: finding right only find right treenode till the end -> 이 방식으로는 오른쪽게 아닌데 왼쪽에만 있는 경우를 잡지 못함 ex. [1, 2] -> 2가 왼쪽이 아니고 right side로 취급됨 # solution 2: greddy 전체 tree를 모두 읽어서 리스트 형태로 만들고 푸는 방식 O(n**2) -> 비효율적임 tree를 한 번 읽어서 바로 처리해야 O(n) 형태가 나옴 # solution 3: read tree and find power of 2 - read tree sequentially (left -> right -> left-left -> left-right ...) - memorize the order (index) - if the index is 1, 3, 7, 15 ... (2**n += 2**(n+1) ...) - add it to result - if end before complete 2**n -> add last tree value - O(n) because it read all the nodes # solution 4: find right tree + if not exist, return left - if right tree exits, the whole tree till now must be comopleted - if right tree not exits, the tree is ended: add the most rightest value - find rightest value: is it impossible without read whole tree?? # solution 5: find rightest value from all floor - add node for specific floor - add rightest value to result per floor (last input) ''' # solution 5: # if no root, return [] if not root: return [] result = [] # create floor with root node floor = deque([[root]]) # loop till the end while floor: current_floor = floor.popleft() print(current_floor) # append rightest value from the floor -> last value from queue result.append(current_floor[-1].val) next_floor = [] for node in current_floor: # append left -> right to next floor if node.left: next_floor.append(node.left) if node.right: next_floor.append(node.right) # add next_floor to floor if next_floor: floor.append(next_floor) return result
6cca9c50b24c23b7b0f45721b84cb06646185442
brpasiliao/Girls_Who_Code_Projects
/commute.py
1,814
3.953125
4
qhome = "walk or drive: " qwalk = "bus or lirr: " qlirr = "subway or speedwalk: " qdrive1 = "lirr or drive: " qdrive2 = "bridge or tunnel: " # def plurality() # if plural == True: # word += "s" # else: # None def end(time, money): hours = time // 60 minutes = time - hours * 60 if time >= 60: print(f"boa, time = {hours} hour & {minutes} minutes, money = ${money}") else: print(f"boa, time = {minutes} minutes, money = ${money}") def back(option): option() def lirr(time, money): time += 40 money += 13.50 user_input = input(qlirr).lower() if user_input == "subway": time += 7 money += 2.75 end(time, money) elif user_input == "speedwalk": time += 15 end(time, money) else: back(lirr) def drive2(time, money): time += 60 user_input = input(qdrive2).lower() if user_input == "bridge": end(time, money) elif user_input == "tunnel": time += 15 end(time, money) else: back(drive2) def drive1(time, money): time += 10 user_input = input(qdrive1).lower() if user_input == "lirr": lirr(time, money) elif user_input == "drive": money += 20 drive2(time, money) else: back(drive1) def walk(time, money): user_input = input(qwalk).lower() if user_input == "bus": time += 30 money += 15 drive2(time, money) elif user_input == "lirr": time += 45 lirr(time, money) else: back(walk) def home(): time = 0 money = 0 user_input = input(qhome).lower() if user_input == "walk": walk(time, money) elif user_input == "drive": drive1(time, money) else: back(home) home()