blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
2626c06833595fd05361b82838fb7495fdeae4f9
gsimbr/ProjectEuler
/problem_2.py
396
3.859375
4
def count_even_fibonacci(threshold): fib_1 = 0 fib_2 = 1 sum_even_fib = 0 while True: fib_3 = fib_1 + fib_2 if fib_3 > threshold: break fib_1 = fib_2 fib_2 = fib_3 if fib_3 % 2 == 0: sum_even_fib += fib_3 return sum_even_fib if __name__ == '__main__': c = count_even_fibonacci(4*1e6) print "c=%d" % c
923177e67d9afe32c3bcc738a8726234c5d08ad2
CTRL-pour-over/Learn-Python-The-Hard-Way
/ex6.py
758
4.5
4
# Strings and Text # This script demonstrates the function of %s, %r operators. x = "There are %d types of people." % 10 binary = "binary" # saves the string as a variable do_not = "don't" y = "Those who know %s and those who %s." % (binary, do_not) # inserting variables () # here's where we print out our variables ^^^ print x print y print "I said: %r." % x # prints print "I also said: '%s'." % y hilarious = False joke_evaluation = "Isn't that joke so funny?! %r" # % hilarious becomes the missing variable for joke_evaluation print joke_evaluation % hilarious # more assigning strings to variables. will be used later w = "This is the left side of..." e = "a string with a right side" # below is where we print the obove variables (w, e) print w + e
84bd788892b101f438b1ee5e6637901383cb0453
CTRL-pour-over/Learn-Python-The-Hard-Way
/keywords/numbers.py
166
3.65625
4
#--- numbers: stores integers ---- i = 100 2 + 2 == 4 # True def math_block(): num = int(raw_input("enter a number >>> ")) a = "1 + 1 = __" math_block()
568c69be02b59df5d2c531bb707be680fc5efa77
CTRL-pour-over/Learn-Python-The-Hard-Way
/ex29.py
1,080
4.65625
5
# What If # The if statements, used in conjunction with the > , < operators will print # the following text if True. # In other words, ( if x is True: print "a short story" ) # Indentation is needed for syntax purpouses. if you do not indent you will get # "IndentationError: expected an indented block". # If you do not create a colon after the new block of code is declared, # you will get a SyntaxError: invalid syntax. people = 20 cats = 30 dogs = 15 if people < cats and 1 == 1: # Prints first print "Too many cats! The world is doomed!" if people > cats: print "Not many cats! The world is saved!" if people < dogs: print "The world is drooled on!" if people > dogs and "test" != "testing": # Prints second print "The world is dry!" dogs += 5 # "increment by" operator. This is the same as 15 + 5 = 20 if people >= dogs: # Prints third print "People are greater than or equal to dogs." if people <= dogs: # Prints fourth print "People are less than or equal to dogs." if (not people != dogs): # Prints fifth print "People are dogs."
46554c75d2000a673d11d628b5921831bec87b74
CTRL-pour-over/Learn-Python-The-Hard-Way
/ex15.py
944
4.25
4
# Reading Files # this file is designed to open and read a given file as plain text # provide ex15.py with an argument (file) and it will read it to you # then it will as for the filename again, you can also give it a different file. from sys import argv # here is how we can give an additional argument when trying to run the script (insert read file) script, filename = argv # line 8 doesnt actually open the file to the user. this is under the hood. txt = open(filename) # line 11 is how we actually read the file to the user. but first you must open it. print "Here's your file %r:" % filename print txt.read() # here is where we ask for the filename again and assign it to a variable (file_again) print "Type the filename again:" file_again = raw_input("> ") # here is how we open the new file in the directory txt_again = open(file_again) # here is how we actually print or read() the second file txt_again.read() print txt_again.read()
faaa06b9de53d47b84700c8aa9d9a058007fa7d4
CTRL-pour-over/Learn-Python-The-Hard-Way
/ex10.py
488
3.796875
4
# What Was That? # here are some variables with strings including \t, \n and \\ escape sequences. tabby_cat = "\t I'm tabbed in." persian_cat = "I'm split\non a line." backslash_cat = "I'm \\ a \\ cat." # fat_cat variable creates a vertical list fat_cat = """ I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """ # here is where we actually print out the variables to get visual output in the interpreter print tabby_cat print persian_cat print backslash_cat print fat_cat
b762e02cebacd34cb378cf8ba01e2901945cd30b
mmuthumanisha/pythonpro
/l.py
87
3.90625
4
year=int() if(year%4): print("is a leap year") else: print("is not leap year")
abe58ea198fb251577aaf5a3154f5733fdf3aef9
pinkjacket/numberpython
/program.py
543
4.09375
4
import random print("-------------------------------------") print(" GUESS THE NUMBER") print("-------------------------------------") print() number = random.randint(0, 100) guess = -1 name = input("Name, please. ") while guess != number: guess_text = input("Guess a number between 0 and 100: ") guess = int(guess_text) if guess < number: print("{0} is too low, {1}.".format(guess, name)) elif guess > number: print("{0} is too high, {1}.".format(guess, name)) else: print("You win!")
d397365d17876b8668222707e765d752ad222675
riva-digital/ledger
/source/ledger/db_query.py
5,008
3.5625
4
""" db_query Riva's database query builder """ __author__ = "mdhananjay" def generate_query_str(select_data=[], from_tables=[], where_and=[], where_or=[], where_and_or=[]): """ This is an all purpose query generator for pretty much any database. The format of the tuples in the where_and & the where_or lists should be (field, comparison operator, value) For example, if in a table you need to search a field called "NAME" whose value is equal to "X", the resultant tuple will be ("NAME", "=", "X") The where_and_or is a slightly more complicated query. Basically, this mixes both AND & OR into the same query, but they are grouped by parenthesis. The format is a list of lists, where each child list contains values you want to join using AND, while the items in the main list will be joined up using OR. For example, consider the following: [[(species, =, snake), (sex, =, 'm')][(species, =, 'bird'), (sex, =, 'f')]] This will translate into the following string: "(species = 'snake' AND sex = 'm') OR (species = 'bird' AND sex = 'f')" :param select_data: A list which contains the fields you want to collect :param from_tables: A list of the tables to collect the fields from :param where_and: A list of tuples containing all values to be joined up using AND :param where_or: A list of tuples containing all values to be joined up using OR :param where_and_or: A list of lists, with each child list containing the tuples for the AND join :return: string The Query String, which is like SELECT * FROM * WHERE value is * """ select_str = "SELECT " from_str = "FROM " where_str = "WHERE " query_str = "" where_and_stat = 0 where_or_stat = 0 where_and_or_stat = 0 # Before we start, make sure that only one of the following parameters is passed: # where_and # where_or # where_and_or if len(where_and): where_and_stat = 1 if len(where_or): where_or_stat = 1 if len(where_and_or): where_and_or_stat = 1 if (where_and_stat and where_or_stat) or (where_and_stat and where_and_or_stat)\ or (where_or_stat and where_and_or_stat): raise ValueError("Multiple conditions found; Please provide for only one type of arguments.") if len(select_data) == 0: select_str += "* " else: select_str += ", ".join(select_data) select_str += " " if len(from_tables) == 0: return query_str else: from_str += ", ".join(from_tables) from_str += " " query_str = select_str + from_str # Now we start the rough part. Basically, WHERE can be used with two keywords, AND & OR # AND has a higher precedence than OR, so where stuff is supposed to be intermixed # it is better to use (x AND y) OR (a AND b) if where_and_or_stat: # A little round of checks here, basically, the main list has to have # at least 2 child lists, which will define the OR conditions, and # within them, each child lists should contain at least two tuples # which will define the AND conditions. if len(where_and_or) < 2: raise ValueError("Insufficient data provided for AND/OR condition.") query_str += where_str for and_list in where_and_or: if len(and_list) < 2: raise ValueError("Insufficient data provided for a child list of AND/OR condition.") query_str += "(" for and_cond in and_list: query_str += "%s %s %s AND " % (and_cond[0], and_cond[1], and_cond[2]) query_str = query_str[:-5] query_str += ") OR " query_str = query_str[:-3] elif where_and_stat: if len(where_and) == 1: query_str += where_str + " ".join(where_and[0]) else: for each_tup in where_and: where_str += "%s %s %s AND " % (each_tup[0], each_tup[1], each_tup[2]) where_str = where_str[:-4] query_str += where_str elif where_or_stat: if len(where_or) == 1: query_str += where_str + " ".join(where_and[0]) else: for each_tup in where_or: where_str += "%s %s %s OR " % (each_tup[0], each_tup[1], each_tup[2]) where_str = where_str[:-4] query_str += where_str return query_str + ";" if __name__ == "__main__": import db_connect q_str = generate_query_str(["a.firstname", "a.lastname", "a.empcode", "b.departmentname"], ["users a", "department b"], where_and_or=[[("a.username", "=", "'akulmi'"), ("a.departmentid", "=", "b.departmentid")], [("a.username", "=", "'mukund.d'"), ("a.departmentid", "=", "b.departmentid")]]) rdb = db_connect.RivaDatabase(dbname="riva_users_prototype", dbuser="root") rdb.connect() print rdb.query(q_str) rdb.close()
11fca8dc0ab7182fb7eee799dff5ccb8874b8d1c
zuFrost/Learning-Python-LinkedIn
/Ex_Files_Learning_Python/Exercise Files/Ch2/number_of_digits.py
662
4.09375
4
# Which code snippet can you use to print the number of digits in the number variable? # You can assume this number is always positive and always less than 10,000. number = 9999 # if (number>=0): # print(1) # elif (number>=10): # print(2) # elif (number>=100): # print(3) # else: # print(4) # if (number<=10): # print(1) # elif (number<=100): # print(2) # elif (number<=1000): # print(3) # else: # print(4) if (number>=1000): print(4) elif (number>=100): print(3) elif (number>=10): print(2) else: print(1) # if (number<10000): # print(4) # elif (number<1000): # print(3) # elif (number<10): # print(2) # else: # print(1)
b53ed033cf11400411a08a01c4749b47398966c4
ianmlunaq/python2019-2020
/quadroots.py
843
3.921875
4
#quadroots.py | CWC | Reference: Amit Saha(Doing Math with Python) def roots(a,b,c): D = (b*b - 4*a*c) print() print("D = " + str(D)) if(D >= 0): print("REAL ROOTS") D = D**0.5 x1 = (-b + D) / (2*a) x1 = (-b - D) / (2*a) print("x1 = " + str(x1) + " x2 = " + str(x2)) elif(D < 0): D = (D * -1)**0.5; print("IMAGINARY ROOTS") print("x1 = -" + str(b/(2*a)) + " - " +str(D/(2*a)) + "i") print("x1 = -" + str(b/(2*a)) + " + " +str(D/(2*a)) + "i") _name_ = "_main_" if _name_ == '_main_': print("Input a, b, and c for the quadratic (ax^2 + bx +c)") a = input("Enter a: ") b = input("Enter b: ") c = input("Enter c: ") roots(float(a), float(b), float(c)) """ Output: Input a, b, and c for the quadratic (ax^2 + bx +c) Enter a: 1 Enter b: 0 Enter c: 9 D = -36.0 IMAGINARY ROOTS x1 = -0.0 - 3.0i x1 = -0.0 + 3.0i """
c111caa5edac1264263a13749ecb10c8855fec9f
ntudavid/PythonWorld
/Python_Station/try_tk2_entry_and_text.py
664
3.5
4
import tkinter as tk window = tk.Tk() window.title('test window') window.geometry('500x300') # width x height e = tk.Entry(window) # show = '*' for passwords e.pack() def add(): s = e.get() t.insert(1.0, s) # row.offset def insert(): s = e.get() t.insert('insert', s) def append(): s = e.get() t.insert('end', s) b1 = tk.Button(window, text='add', width= 10, height=2,command=add) b1.pack() b2 = tk.Button(window, text='insert', width= 10, height=2,command=insert) b2.pack() b3 = tk.Button(window, text='append', width= 10, height=2,command=append) b3.pack() t = tk.Text(window, bg='yellow', height=5) t.pack() window.mainloop()
d80f1f624f4e41badb56d48861708275b6227f8b
ntudavid/PythonWorld
/Python_Station/runPLA.py
2,764
3.9375
4
''' Perceptron Learning Algorithm ''' import numpy as np import matplotlib.pyplot as plt def runPLA(num): # num = number of sample points # target_function: f = [a,b,c] to represent the line: ax+by+c=0 a,b,c = np.random.rand(3)*100-50 f = [a,b,c] x = np.array([-55,55]) y = eval('(-a*x-c)/b') fig = plt.plot(x,y,'c-') # samples [[x1,y1,1],[x2,y2,1],...] points = np.random.rand(num,2)*100-50 offset = np.ones((num,1)) points = np.hstack([points,offset]) # classify the labels and plot Labels = np.ones(num) for i in range(num): check = np.dot(f, points[i,:]) if(check<0): Labels[i] = -1 fig = plt.plot(points[i,0], points[i,1], 'g^') else: fig = plt.plot(points[i,0], points[i,1], 'ro') # plot plt.axis([-55,55,-55,55]) # [Xmin,Xmax,Ymin,Ymax] plt.title('Sample points') plt.xlabel('x') plt.ylabel('y') plt.setp(fig, color = 'r', linewidth = 2.0) #plt.show() # PLA w = PLA(points, Labels) print('Target function =',f) print('PLA predicts =',w) # plot function w a, b, c = w y = eval('(-a*x-c)/b') fig = plt.plot(x,y,'b-') #plt.show() # PLA2 w2 = PLA2(points, Labels) print('Target function =',f) print('PLA predicts =',w2) # plot function w a, b, c = w2 y = eval('(-a*x-c)/b') fig = plt.plot(x,y,'y-') plt.show() def PLA(points, Labels): w = np.zeros(3) pointsT = points.transpose() num = points.shape[0] cnt = 0 while(True): misClassify = [] scores = np.dot(w, pointsT) for i in range(num): if(scores[i]>=0 and Labels[i]==-1): misClassify.append(i) if(scores[i]<0 and Labels[i]==1): misClassify.append(i) n = len(misClassify) if(n==0): break pick = misClassify[np.random.randint(n)] vect = points[pick,:] w = w + Labels[pick]*vect cnt = cnt + 1 print('Iterations', cnt, 'times') return w def PLA2(points, Labels): w = np.zeros(3) pointsT = points.transpose() num = points.shape[0] cnt = 0 while(True): misClassify = [] scores = np.dot(w, pointsT) for i in range(num): if(scores[i]>=0 and Labels[i]==-1): misClassify.append(i) if(scores[i]<0 and Labels[i]==1): misClassify.append(i) n = len(misClassify) if(n==0): break pick = misClassify[0] vect = points[pick,:] w = w + Labels[pick]*vect cnt = cnt + 1 print('Iterations', cnt, 'times') return w runPLA(1000)
9125d42f5cf7be386a8a2790520a1be982e82d40
ntudavid/PythonWorld
/Python_Examples/python_4.py
1,113
4.09375
4
''' tutorial (4) - function, recursive function, module 2016/06/15 David Hsu ''' # factorial: f(n) = n! # function -> def def factorial(n): fact = 1 for i in range(1,n+1): fact *= i return fact def factorialRecursive(n): if n == 0 : return 1 else: return n*factorialRecursive(n-1) # fibonacci function : 0, 1, 1, 2, 3, 5, 8, 13, ... def fibonacci(n): if n==1: return 0 elif n==2: return 1 else: a = 0 b = 1 for i in range(3,n+1): fib = a+b a = b b = fib return fib def fibonacciRecursive(n): if n==1: return 0 elif n==2: return 1 else: return fibonacciRecursive(n-1)+fibonacciRecursive(n-2) # call by reference or call by value def doubleList(L): L=2*L for item in L: item *= 2 # item = item*2 print(L) def doubleList2(L): for i in range(len(L)): L[i] *= 2 # item = item*2 print(L) def test(x): x = x+3 print(x) def testStr(s): s=s.title() print(s)
7cd0811d9b9a7b0ba8fbd477615d63f017acfacf
katelyn-dever/Sir_Quiz-A-Lot
/newsqal.py
11,240
3.5
4
### Sir Quiz-A-Lot desktop application ### ### ITEC 3250 - Katelyn Dever, Elijah Cliett, Brianna Young ### ### Imports ### import math import random # used for GUI from tkinter import * from tkinter import filedialog ### GUI Setup ### root = Tk() terms = dict() windowSize = "750x600" smWindowSize = "400x400" xsWindowSize = "100x100" print("Program running, no errors on load") ### FUNCTIONS ### def updateCount(): countVar = StringVar() countVar.set(str(len(terms))) #counter label counterLabel = Label (root, text = "Number of pairs in your quiz:", width = 75, padx = 20, pady = 20) counterLabel.grid(row = 4, column = 0, columnspan = 3) countLabel = Label(root, textvariable=countVar) countLabel.grid(row = 4, column = 2) def openFile(): root.filename = filedialog.askopenfilename(initialdir = "/", title = "Select file", filetypes = (("txt files", "*.txt"), ("all files", "*.*"))) f = open(root.filename, "r") for line in f: (key, val) = line.split() terms[key] = val updateCount() def saveFile(): root.filename = filedialog.asksaveasfilename(initialdir = "/", title = "Select file", filetypes = (("txt files","*.txt"),("all files","*.*"))) i = 1 f = open(root.filename, "w") for k, v in terms.items(): f.write("%s %s\n" %(k, v)) def addTerm(): if len(termEntry.get()) != 0: if len(defEntry.get()) !=0: terms.update({termEntry.get():defEntry.get()}) termEntry.delete(0, END) defEntry.delete(0, END) updateCount() else: errorWindow = Toplevel() errorWindow.title("Error") errorWindow.iconbitmap('C:/python/sqal/sqal.ico') errorLabel = Label(errorWindow, text = "Invalid Definition Entry") errorLabel.pack() okButton = Button(errorWindow, text = "Okay", command=errorWindow.destroy) okButton.pack() else: errorWindow = Toplevel() errorWindow.title("Error") errorWindow.iconbitmap('C:/python/sqal/sqal.ico') errorLabel = Label(errorWindow, text = "Invalid Term Entry") errorLabel.pack() okButton = Button(errorWindow, text = "Okay", command=errorWindow.destroy) okButton.pack() def QuizA(): if len(terms) >=3: # creates new window QuizAWindow = Toplevel() QuizAWindow.title("Quiz Using Terms/Questions") QuizAWindow.iconbitmap('C:/python/sqal/sqal.ico') QuizAWindow.geometry(smWindowSize) # used for random int num = len(terms)-1 key_list = list(terms.keys()) val_list = list(terms.values()) # creates label to store text variable k = StringVar() l = Label(QuizAWindow, textvariable=k) l.grid(row=1, column=1, pady=20, padx=20) def generate(): x = random.randint(0, num) k.set(key_list[x]) def reveal(): k.set(val_list[x]) revealButton = Button(QuizAWindow, text="Reveal", command=reveal) revealButton.grid(row=2,column=1, columnspan=1,padx=10,pady=10) # generates first term on open generate() # on window buttons nextButton = Button(QuizAWindow, text="Next", command=generate) nextButton.grid(row=2, column=2, columnspan=1, padx=10, pady=10) closeButton = Button(QuizAWindow, text="Close",command=QuizAWindow.destroy) closeButton.grid(row=3,column=2,columnspan=1,padx=10,pady=10) else: errorWindow = Toplevel() errorWindow.title("Error") errorWindow.iconbitmap('C:/python/sqal/sqal.ico') errorLabel = Label(errorWindow, text = "Please enter at least 3 pairs to start a Quiz") errorLabel.pack() okButton = Button(errorWindow, text = "Okay", command=errorWindow.destroy) okButton.pack() def QuizB(): if len(terms) >= 3: # creates new window QuizBWindow = Toplevel() QuizBWindow.title("Quiz Using Definitions/Answers") QuizBWindow.iconbitmap('C:/python/sqal/sqal.ico') QuizBWindow.geometry(smWindowSize) # used for random int num = len(terms)-1 key_list = list(terms.keys()) val_list = list(terms.values()) # creates label to store text variable k = StringVar() l = Label(QuizBWindow, textvariable=k) l.grid(row=1, column=1, pady=20, padx=20) def generate(): x = random.randint(0, num) k.set(val_list[x]) def reveal(): k.set(key_list[x]) revealButton = Button(QuizBWindow, text="Reveal", command=reveal) revealButton.grid(row=2,column=1, columnspan=1,padx=10,pady=10) # generates first definition on open generate() # on window buttons nextButton = Button(QuizBWindow, text="Next", command=generate) nextButton.grid(row=2, column=2, columnspan=1, padx=10, pady=10) closeButton = Button(QuizBWindow, text="Close",command=QuizBWindow.destroy) closeButton.grid(row=3,column=2,columnspan=1,padx=10,pady=10) else: errorWindow = Toplevel() errorWindow.title("Error") errorWindow.iconbitmap('C:/python/sqal/sqal.ico') errorLabel = Label(errorWindow, text = "Please enter at least 3 pairs to start a Quiz") errorLabel.pack() okButton = Button(errorWindow, text = "Okay", command=errorWindow.destroy) okButton.pack() def showAll(): showAllWindow = Toplevel() showAllWindow.title("All Terms Entered") showAllWindow.iconbitmap('C:/python/sqal/sqal.ico') showAllWindow.geometry(windowSize) #counter for rows i = 1 for k, v in terms.items(): stringlist = StringVar() stringlist.set(k + " : " + v) l = Label(showAllWindow, textvariable=stringlist) l.grid(row=i, column = 1, pady=20, padx=50) i= i+1 closeButton = Button(showAllWindow, text="Close",command=showAllWindow.destroy) closeButton.grid(row=i,column=2,columnspan=1,padx=10,pady=10) def clearPrompt(): clearWindow = Toplevel() clearWindow.title("Are you sure?") clearWindow.iconbitmap('C:/python/sqal/sqal.ico') clearLabel = Label(clearWindow, text="Are you sure you want to clear your work?") clearLabel.grid(row=0,column=0,columnspan=3,pady=20,padx=20) clearButtonFinal = Button(clearWindow, text="Clear",command=clearAll) clearButtonFinal.grid(row=2,column=3,pady=10,padx=10) backToProgramButton = Button(clearWindow, text="Go back to my Quiz",command=clearWindow.destroy) backToProgramButton.grid(row=2,column=2,pady=10,padx=10) def clearAll(): terms.clear() updateCount() def rootExit(): #prompts to save upon closing (once save feature added, until then it just warns user to save first) closeWindow = Toplevel() closeWindow.title("*Unsaved Changes*") closeWindow.iconbitmap('C:/python/sqal/sqal.ico') exitLabel = Label(closeWindow, text="Are you sure you want to exit? Please make sure to save all changes.") exitLabel.grid(row=0,column=0,columnspan=3,pady=20,padx=20) exitButtonFinal = Button(closeWindow, text="Exit",command=root.destroy) exitButtonFinal.grid(row=2,column=3,pady=10,padx=10) backToProgramButton = Button(closeWindow, text="Go back to my Quiz",command=closeWindow.destroy) backToProgramButton.grid(row=2,column=2,pady=10,padx=10) ###BEGIN GUI BUILD### # Window creation and overall styles root.title("Sir Quiz-A-Lot") root.iconbitmap('C:/python/sqal/sqal.ico') # File Menu menu = Menu(root) root.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open...", command=openFile) filemenu.add_command(label="Save Quiz", command=saveFile) filemenu.add_separator() filemenu.add_command(label="Exit", command=rootExit) #title at top of GUI introLabel = Label(root, text = "Hello! Welcome to Sir Quiz-A-Lot!", pady = 20, padx = 100) introLabel.grid(row = 0, columnspan = 5) #intro paragraph text detailsLabel = Label(root, text = """Enter as many term/definition or question/answer pairs as you wish, \nthen use the buttons below to quiz yourself!""", pady = 20, padx = 100) detailsLabel.grid(row = 1, columnspan = 5) #term label and entry termLabel = Label(root, text = "Enter a term/question: ", pady = 20) termLabel.grid(row = 2, column = 0) termEntry = Entry(root, width = 75) termEntry.grid(row = 2, column = 1, padx = 20, pady = 20, columnspan = 4) #definition label and entry defLabel = Label(root, text = "Enter its definition/answer: ", padx = 20, pady = 20) defLabel.grid(row = 3, column = 0) defEntry = Entry(root, width = 75) defEntry.grid(row = 3, column = 1, padx = 20, pady = 20, columnspan = 4) #Add to quiz button addToQuizButton = Button(root, text = "Add to Quiz", width = 30, padx = 20, pady = 20, command=addTerm) addToQuizButton.grid(row = 0, column = 5) #Quiz me using Terms button quizTermsButton = Button(root, text = "Quiz me using Terms/Questions", width = 30, padx = 20, pady = 20, command=QuizA) quizTermsButton.grid(row = 1, column = 5) #Quiz me using Defintions button quizDefsButton = Button(root, text = "Quiz Me using Definitions/Answers", width = 30, padx = 20, pady = 20, command=QuizB) quizDefsButton.grid(row = 2, column = 5) #Show All Entries button showAllButton = Button(root, text = "Show All Quiz Entries", command=showAll, padx = 20, pady = 20, width = 30) showAllButton.grid(row = 3, column = 5) #Show All Entries button clearAllButton = Button(root, text = "Clear All Quiz Entries", command=clearPrompt, padx = 20, pady = 20, width = 30) clearAllButton.grid(row = 4, column = 5) #Exit button exitButton = Button(root, text = "Exit", width = 30, padx = 20, pady = 20, command=rootExit) exitButton.grid(row = 5, column = 5) updateCount() root.mainloop()
8f5434c90e5011c5adf3c512d18614ba496dafb7
PacktPublishing/Mastering-Python-Design-Patterns-Second-Edition
/chapter10/command.py
1,910
3.625
4
import os verbose = True class RenameFile: def __init__(self, src, dest): self.src = src self.dest = dest def execute(self): if verbose: print(f"[renaming '{self.src}' to '{self.dest}']") os.rename(self.src, self.dest) def undo(self): if verbose: print(f"[renaming '{self.dest}' back to '{self.src}']") os.rename(self.dest, self.src) class CreateFile: def __init__(self, path, txt='hello world\n'): self.path = path self.txt = txt def execute(self): if verbose: print(f"[creating file '{self.path}']") with open(self.path, mode='w', encoding='utf-8') as out_file: out_file.write(self.txt) def undo(self): delete_file(self.path) class ReadFile: def __init__(self, path): self.path = path def execute(self): if verbose: print(f"[reading file '{self.path}']") with open(self.path, mode='r', encoding='utf-8') as in_file: print(in_file.read(), end='') def delete_file(path): if verbose: print(f"deleting file {path}") os.remove(path) def main(): orig_name, new_name = 'file1', 'file2' commands = (CreateFile(orig_name), ReadFile(orig_name), RenameFile(orig_name, new_name)) [c.execute() for c in commands] answer = input('reverse the executed commands? [y/n] ') if answer not in 'yY': print(f"the result is {new_name}") exit() for c in reversed(commands): try: c.undo() except AttributeError as e: print("Error", str(e)) if __name__ == "__main__": main()
6f2354a40fe60b8650068ae2e1383b49ca72e1ca
PacktPublishing/Mastering-Python-Design-Patterns-Second-Edition
/chapter02/exercise_fluent_builder.py
864
3.84375
4
class Pizza: def __init__(self, builder): self.garlic = builder.garlic self.extra_cheese = builder.extra_cheese def __str__(self): garlic = 'yes' if self.garlic else 'no' cheese = 'yes' if self.extra_cheese else 'no' info = (f'Garlic: {garlic}', f'Extra cheese: {cheese}') return '\n'.join(info) class PizzaBuilder: def __init__(self): self.extra_cheese = False self.garlic = False def add_garlic(self): self.garlic = True return self def add_extra_cheese(self): self.extra_cheese = True return self def build(self): return Pizza(self) if __name__ == '__main__': pizza = Pizza.PizzaBuilder().add_garlic().add_extra_cheese().build() print(pizza)
482fea12d58ab30cd7b4121c95b28a4da36e1486
PacktPublishing/Mastering-Python-Design-Patterns-Second-Edition
/chapter13/iterator.py
959
3.75
4
class FootballTeamIterator: def __init__(self, members): # the list of players and coaches self.members = members self.index = 0 def __iter__(self): return self def __next__(self): if self.index < len(self.members): val = self.members[self.index] self.index += 1 return val else: raise StopIteration() class FootballTeam: def __init__(self, members): self.members = members def __iter__(self): return FootballTeamIterator(self.members) def main(): members = [f'player{str(x)}' for x in range(1, 23)] members = members + ['coach1', 'coach2', 'coach3'] team = FootballTeam(members) team_it = iter(team) while True: print(next(team_it)) if __name__ == '__main__': main()
6412df0a302e2e8dfc6c79bc0787de749f584c96
mistermusk/NASDAQ-Stock-Prediction-Using-Pandas-and-Numpy
/advanced_stats.py
2,561
3.609375
4
import pandas as pd import numpy as np import os.path, time from urllib.request import urlretrieve import datetime as dt import matplotlib.pyplot as plt ################################ Moving Averages ################################### def moving_Avg(stock_file): try: number = int(input("Please enter Moving Average days: ")) if number <= 200: stock_file["numberd"] = np.round(stock_file["Close"].rolling(window = number, center = False).mean(), 2) plt.plot(stock_file["numberd"]) plt.plot(stock_file["Close"]) plt.xlabel('Date') plt.ylabel('Close Price') plt.title('Moving Average') plt.show() else: print("\n You have entered a number greater than 200 for moving average calculation, please try following options\n") moving_Avg(stock_file) except ValueError: print("\n You have entered wrong value for calculation, please try following options\n") moving_Avg(stock_file) ################################ Exponential weighted moving average ################################### def WMA(stock_file): try: number = int(input("Please enter Weighted Moving Average days: ")) if number <= 200: exp_200=stock_file["Close"].ewm(span=number,adjust=False).mean() plt.plot(exp_200) plt.plot(stock_file["Close"]) plt.xlabel('Date') plt.ylabel('Close Price') plt.title('Weighted Moving Average') plt.show() else: print("\n You have entered a number greater than 200 for moving average calculation, please try again....\n") WMA(stock_file) except ValueError: print("\n You have entered wrong value for calculation, please try following options\n") WMA(stock_file) ################################ Moving average convergence/divergence ################################### def MACD(stock_file): # Calcualtes MACD for 10,30 and 60 days. Also based on user input not more than 200 days emaslow =stock_file["Close"].ewm(span=26,adjust=False).mean() emafast =stock_file["Close"].ewm(span=12,adjust=False).mean() MACD = emafast - emaslow exp_9=MACD.ewm(span=9,adjust=False).mean() plt.plot(MACD, 'r', label='MACD') #MACD plt.plot(exp_9, 'b', label='Signal') #Signal Line plt.legend(loc='upper right') plt.xlabel('Date') plt.title('MACD') plt.show()
9741da2737040f20a43a623dd4fe98f7d2540841
minasyan/reverseflow
/reverseflow/arrows/primitive/control_flow_arrows.py
654
3.703125
4
"""These are arrows for control flow of input""" from reverseflow.arrows.primitivearrow import PrimitiveArrow class DuplArrow(PrimitiveArrow): """ Duplicate input f(x) = (x, x, ..., x) """ def __init__(self, n_duplications=2) -> None: self.in_ports = [InPort(self, 0)] self.out_ports = [OutPort(self, i) for i in range(n_duplications)] def invert(self): pass class IdentityArrow(PrimitiveArrow): """ Identity input f(x) = x """ def __init__(self) -> None: self.in_ports = [InPort(self, 0)] self.out_ports = [OutPort(self, 0)] def invert(self): pass
d3c6e63735d52ad672c848ea792620ad8fad2ed2
Bhavyakadiyala/Home-Activity-Task-
/main.py
3,225
3.75
4
from collections import defaultdict import heapq input_file=open("Input.txt","r") slot_regid={} #stores the registration number of vehicle corresponding to the slot number reg_no={} #stores registration_number and slot_number as key-value pairs slot_age={}#Stores slot as key and age as value ageList=defaultdict(list)#Stores slotnumbers for drivers of a particular age slot_cnt=0 available_slots=[] def CreateParkingLot(size): try: n=int(size) print("Created parking of",n,"slots") except: print("Invalid input,Size of parking lot must be a number") def ParkCars(car_num,driver_age): global slot_cnt,size if available_slots: x=heapq.heappop(available_slots) reg_no[car_num]=x ageList[driver_age]+=[x] slot_regid[x]=car_num slot_age[x]=driver_age print("Car with vehicle registration number",car_num,"has been parked at slot number",x) else: #print(int(slot_cnt),int(size)) if slot_cnt==size: print("Parking lot is full") else: slot_cnt+=1 x=slot_cnt reg_no[car_num]=x ageList[driver_age]+=[x] slot_regid[x]=car_num slot_age[x]=driver_age print("Car with vehicle registration number",car_num,"has been parked at slot number",x) def get_list_of_age(X): if ageList[X]: return ageList[X] else: print("There are no drivers with age =",X) def vacate(slt_no): try: vehicle_number=slot_regid[slt_no] del slot_regid[slt_no] del reg_no[vehicle_number] driver_age=slot_age[slt_no] del slot_age[slt_no] ageList[driver_age].remove(slt_no) #print("Slot number",slt_no,"is vacated") print("Slot number",slt_no,"vacated, the car with vehicle registration number",vehicle_number,"left the space, the driver of the car was of age",driver_age) heapq.heappush(available_slots,slt_no) except: global size if slt_no>size: print(slt_no,"is beyond the size of parking lot") else: print("Slot already vacant") def get_slot_number(car_num): try: print(reg_no[car_num]) except: print("Car with given Registration number doesn't exist") def get_registration_numbers(X): try: res=[] for i in ageList[X]: res.append(slot_regid[i]) except: print("Driver with given age doesn't exist") for line in input_file: inp_list=list(line.split()) if inp_list[0]=="Create_parking_lot": size=int(inp_list[-1]) CreateParkingLot(size) #Creating a ParkingLot elif inp_list[0]=="Park": car_num=inp_list[1] driver_age=int(inp_list[-1]) ParkCars(car_num,driver_age) elif inp_list[0]=="Slot_numbers_for_driver_of_age": driver_age=int(inp_list[-1]) result=get_list_of_age(driver_age) if result: #print("Slot numbers having drivers of age",driver_age,"are",end=" ") print(*result,sep=",") elif inp_list[0]=="Slot_number_for_car_with_number": car_num=inp_list[-1] get_slot_number(car_num) elif inp_list[0]=="Leave": slt_no=int(inp_list[-1]) #print(slot_age,available_slots) vacate(slt_no) elif inp_list[0]=="Vehicle_registration_number_for_driver_of_age": age=int(inp_list[-1]) get_registration_numbers(age) else: print("Invalid Command") #print(ageList)
7d0700a70d505b53f72cbf018b4048f93f11a308
hondajyh/Sprint_4_data_manipulation_and_tools
/SQLA_2Tbl_12m.py
4,403
4.1875
4
#DEMONSTRATE A 1 TO MANY RELATIONSHIP W/O CORRESPONDING MANY TO 1 RELATIONSHIP #THIS IS CRUCIAL WHEN WE HAVE SITUATIONS WHERE THE MANY SIDE TABLE OF A 1:MANY RELATIONSHIP #DOES NOT NECESSARILY HAVE A CORRESPONDING RECORED ON THE 1 TABLE SIDE. #connect to SQLite DB w/ SQLAlchemy ORM: from sqlalchemy import create_engine engine = create_engine('sqlite:///:memory:', echo = False) #NOW DEFINE DB SCHEMA (THIS DOESN'T WRITE SCHEMA TO DB, JUST TO SQLALCHEMY CLASSES AND OBJECTS) #define an SQLAlchemy base class to maintain catalog of classes and tables relative to this base from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() #use the base class to define mapped classes in terms of it: #as an initial example, define a table called 'users' by defining a class called 'User' from sqlalchemy import Column, Integer, String # from sqlalchemy import Sequence from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship #http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#relationship-patterns class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50)) fullname = Column(String(50)) password = Column(String(12)) #sets up 1 to many relationship between 1 user and many addresses #define relationship in both tables so that elements added in one direction automatically become visible in the other direction. This behavior occurs based on attribute on-change events and is evaluated in Python, without using any SQL: addresses = relationship("Address") # setup 1 to many relation. addresses is a collection that holds related Address class objects def __repr__(self): #used in query function to return values of queried fields return "<User(id='%s', name='%s', fullname='%s', password='%s')>" % ( self.id, self.name, self.fullname, self.password) class Address(Base): __tablename__ = 'addresses' id = Column(Integer, primary_key=True) email_address = Column(String, nullable=False) user_id = Column(Integer, ForeignKey('users.id')) #sets up many to 1 relationship between 1 user and many addresses def __repr__(self): #used in query function to return values of queried fields return "<Address(id='%s', email_address='%s', user_id='%s')>" % ( self.id, self.email_address, self.user_id) #NOW WRITE SCHEMA TO DB (THIS WRITES TO SQLITE DB): Base.metadata.create_all(engine) #build DB schema from Base objects #NOW WRITE DATA TO DB. YOU NEED A SESSION OBJECT TO DO SO: from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) #define Session class, which is a factory for making session objects (poor naming choice, in my opinion - why the do it this way??!) session = Session() #make a session #now insert data using various insert methods: ed_user = User(name='ed', fullname='Ed Jones', password='edspassword') #single insert to User table. pass the record to object ed_user session.add(ed_user) # add record held in object to the DB - but only as a temp. item (it's not yet comitted) session.add_all([ #insert multiple records to User table User(name='wendy', fullname='Wendy Williams', password='foobar'), User(name='mary', fullname='Mary Contrary', password='xxg527'), User(name='fred', fullname='Fred Thompson', password='blah')]) #insert to User table using dictionary object mydict = {'name':'jake', 'fullname':'jake tonda', 'password': 'jagd'} session.add(User(**mydict)) session.commit() #commit all pending transactions to DB #PLAYING W/ RELATIONSHIPS: jack = User(name='jack', fullname='Jack Bean', password='gjffdd') jack.addresses #no associated addresses yet. so addresses relationship collection returnes empty jack.addresses = [#insert some addresses Address(email_address='jack@google.com'), Address(email_address='j25@yahoo.com')] #write jack to DB: session.add(jack) session.commit() #now add an email into addresses that's not associated w/ any names myeml = Address(email_address='otters@mink.net') session.add(myeml) session.commit() #get all users: for rec in session.query(User): print (rec) #do a join type query: for rec in session.query(User.id, User.fullname, Address.email_address).filter(User.name == 'jack'): print (rec) #get all addresses: for rec in session.query(Address.email_address): print (rec)
f356b9b722b00fb85c8e9afbe60e80181a5aba5c
Programacion-Algoritmos-18-2/tarea-03-tutoria-iaortiz
/paquete1/modelo.py
1,638
3.6875
4
#Creación de clase docente class Docente : def __init__ (self, n, a): self.nombre = n self.ciudad = a # Metodo get y set para nombre def agregar_nombre (self, n): self.nombre = n def obtener_nombre (self): return self.nombre # Metodo get y set para ciudad def agregar_ciudad (self, a): self.ciudad = a def obtener_ciudad(self): return self.ciudad #Presentación def presentar_datos (self): cadena = "%s\n\t%s" %(self.obtener_nombre() , self.obtener_ciudad()) return cadena #Creación de clase estudiante class Estudiante: def __init__ (self,n,listaDocentes): self.nombre = n self.docente = listaDocentes #Metodo get y set para nombre def agregar_nombre (self , n): self.nombre = n def obtener_nombre (self): return self.nombre # Metodo get y set para lista docente def agregar_listaDocentes(self, listaDocentes): self.docente = listaDocentes def obtener_listaDocentes(self): return self.docente #Método de presentación de datos def presentar_datos(self): cadena = "Estudiante: %s\n" % (self.obtener_nombre()) #Variable que concatena el encabezado cadena = "%s%s\n" % (cadena,"Lista de docentes") #Ciclo for para recorrer la lista de docentes for i in self.obtener_listaDocentes(): #Variable cadena con concatenación del encabezado y la presentación con los docentes cadena = "%s\n%s" %(cadena, i.presentar_datos()) return cadena
a43d4838a307397258ce4bf7da29d105ed6313b5
MaciejWanat/AutomataDeterminizer
/determinize.py
3,693
3.546875
4
#!/usr/bin/env python3 import sys import collections detAutomaton = {} nonDetAutomaton = {} acceptStates = set() detAcceptStates = set() alphabet = set() foundState = True nonDetWalks = False def prettyPrint(dicto): print() for key in dicto: print(str(key) + " : " + str(dicto[key])) def prettyPrintOrdered(dicto, acceptStates): print() dicto = collections.OrderedDict(sorted(dicto.items())) for key in dicto: print(str(key[0]) + " " + str(dicto[key]) + " " + str(key[1])) for state in acceptStates: print(state) def printIter(dicto, i): print('\n----------------\n') print('Iteration ' + str(i)) prettyPrint(dicto) print() #Read nondeterministic automaton ---- for line in sys.stdin: if line[0] != '#': words = line.strip().split(' ') if len(words) != 1: pair = (words[0], words[2]) alphabet.add(words[2]) if pair in nonDetAutomaton: nonDetAutomaton[pair].add(words[1]) #used for detecting not needed single states nonDetWalks = True else: nonDetAutomaton[pair] = set(words[1]) else: acceptStates.add(line.strip()) detAcceptStates = set(acceptStates) print('Input: ') prettyPrint(nonDetAutomaton) #if the input automaton is nondeterministic if nonDetWalks: #initialize values for 0 for symbol in alphabet: if ('0', symbol) in nonDetAutomaton: detAutomaton[('0', symbol)] = nonDetAutomaton[('0', symbol)] #used because we cant iterate throught changing dictionary detAutomatonCopy = dict(detAutomaton) i = 0 while foundState == True: detAutomaton = dict(detAutomatonCopy) i = i + 1 printIter(detAutomaton, i) foundState = False for key in detAutomaton: compareKey = key #if its a set, convert it into frozenset (which is hashable) if len(detAutomaton[key]) > 1: compareKey = (frozenset(detAutomaton[key]),key[-1]) elif detAutomaton[key]: compareKey = (next(iter(detAutomaton[key])), key[-1]) if detAutomaton[key] and compareKey not in detAutomaton: print('Found new key : ' + str(detAutomaton[key]) + ". Adding to automaton...") foundState = True for symbol in alphabet: valueAutoma = set() for state in detAutomaton[key]: if (state, symbol) in nonDetAutomaton: valueAutoma.update(nonDetAutomaton[(state, symbol)]) detAutomatonCopy[compareKey[0], symbol] = valueAutoma #Delete empty states toDel = set() for key in detAutomaton: if not len(detAutomaton[key]): toDel.add(key) for state in toDel: del detAutomaton[state] i = i + 1 printIter(detAutomaton, i) #Create map keysMap = {} #Map starting state keysMap['0'] = '0' i = 1 #Map lasting states for key in detAutomaton: if key[0] not in keysMap: keysMap[key[0]] = str(i) i = i + 1 print("--------\n\nMap:") prettyPrint(keysMap) print() detAcceptStates = set() #Get accepting states for key in detAutomaton: for state in frozenset(key[0]): if state in acceptStates: detAcceptStates.add(keysMap[key[0]]) detAutomatonCopy = detAutomaton detAutomaton = {} #Map values for key in detAutomatonCopy: #transfer value set into frozenset, if it is a set or into single element if it is a single element if len(detAutomatonCopy[key]) > 1: detAutomaton[(keysMap[key[0]], key[1])] = keysMap[frozenset(detAutomatonCopy[key])] else: for e in detAutomatonCopy[key]: singleElement = e detAutomaton[(keysMap[key[0]], key[1])] = keysMap[singleElement] print("--------\n\nFinal deterministic automaton:") prettyPrintOrdered(detAutomaton, detAcceptStates) else: print("\nYour automaton is already deterministic!")
e8faa34e0297ab5fb4a6e68c058747b0d011f468
HannahMoses/build-a-blog
/main.py
1,907
3.515625
4
#TEMPLATES feb 20 2017,Mon 6:56pm PRESIDENT'S DAY 4430GSWAY Matt6:1verse import os import webapp2#rgb(0,234,200) also use rgb(0,234,222 form_html = """ <form > <body style='background-color:rgb(0,234,200)' > <h2 style='color:rgb(234,13,156)'> Add a food </h2> <input type = "text" name="food" ><br><br> %s <button> Add food </button> </body> </form> """ hidden_html = """ <input type ="hidden" name="food" value="%s" """ item_html = "<li>%s</li>"#this will be a list item, that goes inside the shopping_list_html shopping_list_html = """ <br> <br> <h2 style='color:white;background-color:rgb(234,13,156)'>Shopping List</h2> <ul> %s </ul> """ class Handler (webapp2.RequestHandler): def write(self,*a,**kw): self.response.out.write(*a,**kw) class MainPage(Handler): def get(self): a="<h4 style='color:white;background-color:rgb(234,13,156);text-align:center''>Hello, Udacity !!!!<h4>" self.write(a) output = form_html output_hidden =""#output_html will hold the content that is going # to be stuffed into %sFOR NOW ,it is an empty string "" items = self.request.get_all("food")#gets all GET parameters and #POST parameters of the same name "food"in the URL if items: output_items = "" for item in items : output_hidden+= hidden_html % item#hidden_html refers to the HTML string %s that is going to hold the hiden value.For every item in items, add to the string #output_hidden, the value os hidden_html, substituting the food name in item output_items+= item_html % item output_shopping = shopping_list_html % output_items output += output_shopping output = output % output_hidden self.write(output) app = webapp2.WSGIApplication([('/',MainPage), ], debug=True)
eb2d569e01206cbcb7269945473a28ec5ed9fb47
sanjib-upreti/IQVIA-Test
/disease_activity.py
1,506
3.796875
4
import feedparser from datetime import datetime from time import mktime from disease_list import disease_list_all, disease_list_small # disease list created for testing # initializing the value of days by 2(for testing Module) days=2 def disease_monitor(days): try: if 0 < days <= 30: # putting condition for input must between 1- 30 for disease in disease_list_small: # iterting through the disease list, one by one # STRING URL OF RSS FEED...using string formatting feed_string = f'https://clinicaltrials.gov/ct2/results/rss.xml?rcv_d={days}&lup_d=&sel_rss=new14&cond={disease}' Feed = feedparser.parse(feed_string) # using parse funtion entries = Feed.entries # collecting the feed entries in dictionary format # PRINTING RESULTS if len(entries) == 0: # if dictionary item is absent print(f'{len(entries)} cases of {disease}: in last {days} days') else: print('Please provide input in range 1-30 only') except: pass # for calling the function if __name__ == "__main__": try: days = int(input('Disease cases in last (enter days)\n')) # getting number of days from user disease_monitor(days) # calling the fucntion with days in parameter except ValueError: # passing the valueError if type is not integer print("Please enter number between (1-30)")
7945f90ec505986bbff390dacdfe8a21f28edcdd
Del-virta/goit-python
/lesson3/func.py
418
3.859375
4
def total(a=5, *numbers, **phone_book): print('a', a) # проход по всем элементам кортежа for single_item in numbers: print('single_item', single_item) #проход по всем элементам словаря for first_part, second_part in phone_book.items(): print(first_part,second_part) print(total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560))
47677a52fd86358fcfea3fe06461d155e7df408a
Del-virta/goit-python
/lesson5/text_length.py
511
3.703125
4
def real_len(text): t_length = 0 for char in text: if char in ['\v','\n','\t','\r','\f']: pass else: t_length+=1 return t_length text = 'Мы думали над тем, как можно все бросить и удететь в космос.\nГде-то там останется семья и друзья. \v а ты сидишь и смотришь в глубокую синеву день за днем.' print(real_len(text)) print(len(text))
ffad24a7368cd7032d28f7a8bde96b75ba0f01b1
Del-virta/goit-python
/lesson4/coordinates3.py
559
3.703125
4
points = { (0, 1): 2, (0, 2): 3.8, (0, 3): 2.7, (1, 2): 2.5, (1, 3): 4.1, (2, 3): 3.9, } def calculate_distance(coordinates): distance = 0 if len(coordinates) <=1: return 0 else: for i in range(len(coordinates)-1): couple = (coordinates[i],coordinates[i+1]) coordinate = sorted(couple) for key in points.keys(): if tuple(coordinate) == key: distance+=points.get(key) return distance print(calculate_distance([0,1,3,2,0,2]))
a10a51dbf22db51031019c4a9fa845cbe34cce0f
Del-virta/goit-python
/lesson8/screencasts/scrncst5.py
221
3.734375
4
import collections person1 = ('Bob', 'Dou', 25) Person = collections.namedtuple('Person', ['name', 'surname', 'age']) person = Person('Jack', 'Watson', 55) print(person1[0]) print(person.age) print(person) print(person1)
1f4f1946267dc3dc4f634785899b55a634264e2d
Del-virta/goit-python
/lesson8/screencasts/scrncst9.py
452
3.921875
4
squares = [] for i in range(11): squares.append(i ** 2) print(squares) # Using comprehensions squares_new = [i **2 for i in range(11)] print(squares_new) # using function and comprehensions def func(x): return x * 2 # with list dubbled = [func(i) for i in range(11)] print(dubbled) # with set dubbled_set = {func(i) for i in range(11)} print(dubbled_set) # with dictionary dubbled_dict = {i: func(i) for i in range(11)} print(dubbled_dict)
a23e8c41a233fc338f09052190a74c9fe17d0561
Del-virta/goit-python
/lesson8/screencasts/scrncst2.py
483
3.90625
4
import random from datetime import datetime, timedelta def main(): starting_date = input('Enter starting date: ') end_date = input('Enter ending date: ') starting_date = datetime.strptime(starting_date, "%Y-%m-%d") end_date = datetime.strptime(end_date, "%Y-%m-%d") inerval_days = (end_date - starting_date).days days_delta = random.randint(0, inerval_days + 1) print(starting_date + timedelta(days=days_delta)) if __name__ == '__main__': main()
38650ab2af9fb1f6f7b9d91fa82744a37746903a
Del-virta/goit-python
/lesson7/m7t09.py
241
3.734375
4
def all_sub_lists (data): sub_lists = [[]] for i in range(len(data)+1): for j in range(i+1,len(data)+1): sub_lists.append(data[i:j]) return sorted(sub_lists, key=len) print(all_sub_lists([4,6,1,3]))
7658ba056e4e191d6668856e78875e4fce56a202
Del-virta/goit-python
/lesson2/odd_even.py
181
4.125
4
number = 0 while True: if number % 2: print(f"{number} is odd") else: print(f"{number} is even") if number > 20: break number = number + 1
2de85a372010730f1881ad33cae76b32d92e933c
Del-virta/goit-python
/First practice.py
473
3.921875
4
# Linear equation print("We are trying to solve linear equation 'ax + b = c'") a = 3 b = 2 c = 1 print(f"a = {a}, b = {b}, c = {c}") x = (c - b)/a print(f"x = {x}") # Pifagor theorema print("We are trying to find hypotenuse") a = int(input('Enter "a" value: ')) b = int(input('Enter "b" value: ')) print(f"a = {a}, b = {b}, c = {c}") c = (a ** 2 + b ** 2) ** 0.5 c = round(c, 2) pribt(f'c = {c}') # Bool operations user_input = input('Enter somethibg') bool(user_input)
3088bf061b059d4af2a3c7bdeb536262bb80dc08
BlaiseCosico/100DaysOfCode
/CSV-Data-Analysis/ramen.py
1,663
3.546875
4
import os import csv from collections import namedtuple, Counter from typing import List data = [] Record = namedtuple('Record', ['Review', 'Brand', 'Variety_Style', 'Country', 'Stars', 'Top_Ten']) def init(): base_file = os.path.dirname(__file__) filename = os.path.join(base_file, 'data', 'ramen_ratings.csv') with open(filename, 'r', encoding='utf-8') as file: reader = csv.DictReader(file) for line in reader: record = parse_row(line) data.append(record) def parse_row(row): try: row['Stars'] = float(row['Stars']) except ValueError: row['Stars'] = 0.0 except Exception as x: print(x) record = Record(Review = row.get('Review'), Brand = row.get('Brand'), Variety_Style = row.get('Variety Style'), Country = row.get('Country'), Stars = row.get('Stars'), Top_Ten = row.get('Top_ten')) return record # Record(Review='2580', Brand='New Touch', Variety_Style=None, Country='Japan', Stars=3.75, Top_Ten=None) def most_common_country(n=0): country = list(r.Country for r in data) country = Counter(country) country_list = [c[0] for c in country.most_common(n)] return country_list def revert(country_list) -> List[Record]: return [d for d in data if d.Country not in country_list] def top_rated(): return sorted(data, key=lambda s: s.Stars, reverse=True) def lowest_rated(): return sorted(data, key=lambda s: s.Stars) def top_ten(): return [[r for r in d] for d in data if d.Top_Ten is not None] most_common_country()
783eba19b95768cc63c698d5af91ee7a7f4561e9
mpentler/edinbustrack
/edinbustrack.py
1,524
3.546875
4
# edinbustrack V0.05 - get all of the upcoming services at a particular stop # (c) Mark Pentler 2017 # # This uses screen scraping as you appear to have to be a proper developer to # get access to the Edinburgh City Council's BusTracker API from bs4 import BeautifulSoup import requests def get_bus_times(stop_id): # returns a list of expected buses at the chosen stop url = "http://www.mybustracker.co.uk/?module=mobile&mode=1&busStopCode=" + stop_id + "&subBusStop=Display+Departures" r = requests.get(url) # make our request data = r.text soup = BeautifulSoup(data, "html.parser") # bs4 doing its work stop_data = soup.find_all("tr", attrs={"style": None, "class": None}) # grab every single bus entry in the table - this ID changes! services = [] # service list goes in here for row_num, row in enumerate(stop_data): cols = row.find_all("td") # this will grab every column per bus services.append ([row_num, cols[0].get_text(strip=True).encode("ascii"), cols[2].get_text(strip=True).encode("ascii")]) # extract service and time remaining return services def get_stop_name(stop_id): url = "http://www.mybustracker.co.uk/?module=mobile&mode=1&busStopCode=" + stop_id + "&subBusStop=Display+Departures" r = requests.get(url) # make our request data = r.text soup = BeautifulSoup(data, "html.parser") stop_name = soup.find("span", attrs={"class": "resultTitleText"}).get_text(strip=True).encode("ascii").split("Next departures from ") # find the stop name and chop it out of the string return stop_name[1]
21580bb63d57f66c2dd94a8882ebb725af71445c
junzhiwang/cs231n
/assignment1/cs231n/classifiers/softmax.py
2,535
3.625
4
import numpy as np from random import shuffle from past.builtins import xrange def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X: A numpy array of shape (N, D) containing a minibatch of data. - y: A numpy array of shape (N,) containing training labels; y[i] = c means that X[i] has label c, where 0 <= c < C. - reg: (float) regularization strength Returns a tuple of: - loss as single float - gradient with respect to weights W; an array of same shape as W """ # Initialize the loss and gradient to zero. loss = .0 dW = np.zeros_like(W) num_train, dim = X.shape num_classes = W.shape[1] for i in xrange(num_train): score = np.exp(X[i].dot(W)) sum_score = np.sum(score) prob_score = score / sum_score for j in xrange(num_classes): # Correct label, compute log loss and contribute to loss if j == y[i]: loss -= np.log(prob_score[j]) dW[:, j] += (prob_score[j] - 1) * X[i] # Incorrect score, no compute to log loss, contribute to gradient else: dW[:, j] += prob_score[j] * X[i] loss = loss / num_train + .5 * reg * np.sum(W * W) dW = dW / num_train + reg * W return loss, dW def softmax_loss_vectorized(W=None, X=None, y=None, reg=None, scores=None): """ Softmax loss function, vectorized version. Inputs and outputs are the same as softmax_loss_naive. """ # Initialize the loss and gradient to zero. loss = .0 dW, score = None, None if scores is None: dW = np.zeros_like(W) num_train, dim = X.shape num_classes = W.shape[1] score = X.dot(W) else: num_train, num_classes = scores.shape score = scores exp_score = np.exp(score) sum_score = np.sum(exp_score, axis=1) prob_score = (exp_score.T / sum_score).T correct_label_prob_score = prob_score[np.arange(num_train), y] loss -= np.sum(np.log(correct_label_prob_score)) loss = loss / num_train # Modify prob_score, substract correct label score by 1 if W is not None: loss += .5 * reg * np.sum(W * W) prob_score[np.arange(num_train), y] -= 1 dW = X.T.dot(prob_score) / num_train + reg * W return loss, dW
cfc7efb3972ee25f68f2f3da0ac4b55269bc6245
kumararun2002/Dragons-and-Terminators-Game-Python-
/dragons/characters/dragons/dragon.py
1,316
3.921875
4
from ..fighter import Fighter class Dragon(Fighter): """A Dragon occupies a place and does work for the colony.""" is_dragon = True implemented = False # Only implemented Dragon classes should be instantiated food_cost = 0 blocks_path=True is_container=False # ADD CLASS ATTRIBUTES HERE def __init__(self, armor=1): """Create a Dragon with a ARMOR quantity.""" Fighter.__init__(self, armor) def can_contain(self, other): return False def contain_dragon(self, other): assert False, "{0} cannot contain a dragon".format(self) def remove_dragon(self, other): assert False, "{0} cannot contain a dragon".format(self) def add_to(self, place): if place.dragon is None: place.dragon = self else: # BEGIN 3.1 assert place.dragon is None, 'Two dragons in {0}'.format(place) # END 3.1 Fighter.add_to(self, place) def remove_from(self, place): if place.dragon is self: place.dragon = None elif place.dragon is None: assert False, '{0} is not in {1}'.format(self, place) else: # container or other situation place.dragon.remove_dragon(self) Fighter.remove_from(self, place)
835ea6ee01cc4527c3a94285754d6f08c4e6499f
kumararun2002/Dragons-and-Terminators-Game-Python-
/dragons/places/place.py
3,339
4.34375
4
class Place(object): """A Place holds fighters and has an exit to another Place.""" def __init__(self, name, exit=None): """Create a Place with the given NAME and EXIT. name -- A string; the name of this Place. exit -- The Place reached by exiting this Place (may be None). """ self.name = name self.exit = exit self.terminators = [] # A list of Terminators self.dragon = None # A Dragon self.entrance = None # A Place # Phase 1: Add an entrance to the exit # BEGIN 1.2 if self.exit != None: exit.entrance=self # END 1.2 def add_fighter(self, fighter): """Add a Fighter to this Place. There can be at most one Dragon in a Place, unless exactly one of them is a container dragon , in which case there can be two. If add_fighter tries to add more Dragons than is allowed, an assertion error is raised. There can be any number of Terminators in a Place. """ if fighter.is_dragon: if self.dragon is None: self.dragon = fighter else: # BEGIN 3.2 if (self.dragon).can_contain(fighter)==True: (self.dragon).contain_dragon(fighter) elif (fighter).can_contain(self.dragon)==True: fighter.contain_dragon(self.dragon) self.dragon=fighter else: assert self.dragon is None, 'Two dragons in {0}'.format(self) # END 3.2 else: self.terminators.append(fighter) fighter.place = self def remove_fighter(self, fighter): """Remove a FIGHTER from this Place. A target Dragon may either be directly in the Place, or be contained by a container Dragon at this place. The true DragonKing may not be removed. If remove_fighter tries to remove a Dragon that is not anywhere in this Place, an AssertionError is raised. A Terminator is just removed from the list of Terminators. """ if fighter.is_dragon: # Special handling for DragonKing # BEGIN 4.3 if hasattr(fighter,'name'): if fighter.name=='King': if fighter.imp==False: return # END 4.3 # Special handling for container dragons if self.dragon is fighter: # Bodyguard was removed. Contained dragon should remain in the game if hasattr(self.dragon, 'is_container') and self.dragon.is_container: self.dragon = self.dragon.contained_dragon else: self.dragon = None else: # Contained dragon was removed. Bodyguard should remain if hasattr(self.dragon, 'is_container') and self.dragon.is_container \ and self.dragon.contained_dragon is fighter: self.dragon.contained_dragon = None else: assert False, '{0} is not in {1}'.format(fighter, self) else: self.terminators.remove(fighter) fighter.place = None def __str__(self): return self.name
bd260f44a1128dc5a445b33b9a64d3727b8a0b9a
hupipi96/pyldpc
/pyldpc/ldpc_images.py
10,715
3.578125
4
import numpy as np from .imagesformat import int2bitarray, bitarray2int, Bin2Gray, Gray2Bin, RGB2Bin, Bin2RGB from .codingfunctions import Coding from .decodingfunctions import Decoding_BP_ext, Decoding_logBP_ext, DecodedMessage from .ldpcalgebra import Bits2i, Nodes2j, BitsAndNodes import scipy import warnings __all__=['ImageCoding','ImageDecoding','int2bitarray','bitarray2int','Bin2Gray', 'Gray2Bin','RGB2Bin','Bin2RGB','BER','ImageCoding_rowbyrow','ImageDecoding_rowbyrow'] def ImageCoding(tG,img_bin,snr): """ CAUTION: SINCE V.0.7 Image coding and decoding functions TAKES TRANSPOSED CODING MATRIX tG. IF G IS LARGE, USE SCIPY.SPARSE.CSR_MATRIX FORMAT TO SPEED UP CALCULATIONS. Codes a binary image (Therefore must be a 3D-array). Each pixel (k bits-array, k=8 if grayscale, k=24 if colorful) is considered a k-bits message. If the original binary image is shaped (X,Y,k). The coded image will be shaped (X,Y,n) Where n is the length of a codeword. Then a gaussian noise N(0,snr) is added to the codeword. Remember SNR: Signal-Noise Ratio: SNR = 10log(1/variance) in decibels of the AWGN used in coding. Of course, showing an image with n-bits array is impossible, that's why if the optional argument show is set to 1, and if Coding Matrix G is systematic, showing the noisy image can be possible by gathering the k first bits of each n-bits codeword to the left, and the redundant bits to the right. Then the noisy image is changed from bin to uint8. Remember that in this case, ImageCoding returns a tuple: the (X,Y,n) coded image, and the noisy image (X,Y*(n//k)). Parameters: G: Coding Matrix G - (must be systematic to see what the noisy image looks like.) See CodingMatrix_systematic. img_bin: 3D-array of a binary image. SNR: Signal-Noise Ratio, SNR = 10log(1/variance) in decibels of the AWGN used in coding. Returns: (default): Tuple: noisy_img, coded_img """ n,k = tG.shape height,width,depth = img_bin.shape if k!=8 and k!= 24: raise ValueError('Coding matrix must have 8 xor 24 rows ( grayscale images xor rgb images)') coded_img = np.zeros(shape=(height,width,n)) noisy_img = np.zeros(shape=(height,width,k),dtype=int) for i in range(height): for j in range(width): coded_byte_ij = Coding(tG,img_bin[i,j,:],snr) coded_img[i,j,:] = coded_byte_ij systematic_part_ij = (coded_byte_ij[:k]<0).astype(int) noisy_img[i,j,:] = systematic_part_ij if k==8: noisy_img = Bin2Gray(noisy_img) else: noisy_img = Bin2RGB(noisy_img) return coded_img,noisy_img def ImageDecoding(tG,H,img_coded,snr,max_iter=1,log=1): """ CAUTION: SINCE V.0.7 Image coding and decoding functions TAKES TRANSPOSED CODING MATRIX tG. IF G IS LARGE, USE SCIPY.SPARSE.CSR_MATRIX FORMAT (IN H AND G) TO SPEED UP CALCULATIONS. Image Decoding Function. Taked the 3-D binary coded image where each element is a codeword n-bits array and decodes every one of them. Needs H to decode. A k bits decoded vector is the first k bits of each codeword, the decoded image can be transformed from binary to uin8 format and shown. Parameters: tG: Transposed coding matrix tG. H: Parity-Check Matrix (Decoding matrix). img_coded: binary coded image returned by the function ImageCoding. Must be shaped (heigth, width, n) where n is a the length of a codeword (also the number of H's columns) snr: Signal-Noise Ratio: SNR = 10log(1/variance) in decibels of the AWGN used in coding. log: (optional, default = True), if True, Full-log version of BP algorithm is used. max_iter: (optional, default =1), number of iterations of decoding. increase if snr is < 5db. """ n,k = tG.shape height, width, depth = img_coded.shape img_decoded_bin = np.zeros(shape=(height,width,k),dtype = int) if log: DecodingFunction = Decoding_logBP_ext else: DecodingFunction = Decoding_BP_ext systematic = 1 if not (tG[:k,:]==np.identity(k)).all(): warnings.warn("In LDPC applications, using systematic coding matrix G is highly recommanded to speed up decoding.") systematic = 0 BitsNodes = BitsAndNodes(H) for i in range(height): for j in range(width): decoded_vector = DecodingFunction(H,BitsNodes,img_coded[i,j,:],snr,max_iter) if systematic: decoded_byte = decoded_vector[:k] else: decoded_byte = DecodedMessage(tG,decoded_vector) img_decoded_bin[i,j,:] = decoded_byte if k==8: img_decoded = Bin2Gray(img_decoded_bin) else: img_decoded = Bin2RGB(img_decoded_bin) return img_decoded def ImageCoding_rowbyrow(tG,img_bin,snr): """ CAUTION: SINCE V.0.7 Image coding and decoding functions TAKE TRANSPOSED CODING MATRIX tG. USE SCIPY.SPARSE.CSR_MATRIX FORMAT (IN H AND G) TO SPEED UP CALCULATIONS. K MUST BE EQUAL TO THE NUMBER OF BITS IN ONE ROW OF THE BINARY IMAGE. USE A SYSTEMATIC CODING MATRIX WITH CodingMatrix_systematic. THEN USE SCIPY.SPARSE.CSR_MATRIX() -------- Codes a binary image (Therefore must be a 3D-array). Each row of img_bin is considered a k-bits message. If the image has a shape (X,Y,Z) then the binary image will have the shape (X,k). The coded image will be shaped (X+1,n): - The last line of the coded image stores Y and Z so as to be able to construct the decoded image again via a reshape. - n is the length of a codeword. Then a gaussian noise N(0,snr) is added to the codeword. Remember SNR: Signal-Noise Ratio: SNR = 10log(1/variance) in decibels of the AWGN used in coding. ImageCoding returns a tuple: the (X+1,n) coded image, and the noisy image (X,Y,Z). Parameters: tG: Transposed Coding Matrix G - must be systematic. See CodingMatrix_systematic. img_bin: 3D-array of a binary image. SNR: Signal-Noise Ratio, SNR = 10log(1/variance) in decibels of the AWGN used in coding. Returns: (default): Tuple: coded_img, noisy_img """ n,k = tG.shape height,width,depth = img_bin.shape if not type(tG)==scipy.sparse.csr_matrix: warnings.warn("Using scipy.sparse.csr_matrix format is highly recommanded when computing row by row coding and decoding to speed up calculations.") if not (tG[:k,:]==np.identity(k)).all(): raise ValueError("G must be Systematic. Solving tG.tv = tx for images has a O(n^3) complexity.") if width*depth != k: raise ValueError("If the image's shape is (X,Y,Z) k must be equal to 8*Y (if Gray ) or 24*Y (if RGB)") img_bin_reshaped = img_bin.reshape(height,width*depth) coded_img = np.zeros(shape=(height+1,n)) coded_img[height,0:2]=width,depth for i in range(height): coded_img[i,:] = Coding(tG,img_bin_reshaped[i,:],snr) noisy_img = (coded_img[:height,:k]<0).astype(int).reshape(height,width,depth) if depth==8: return coded_img,Bin2Gray(noisy_img) if depth==24: return coded_img,Bin2RGB(noisy_img) def ImageDecoding_rowbyrow(tG,H,img_coded,snr,max_iter=1,log=1): """ CAUTION: SINCE V.0.7 ImageDecoding TAKES TRANSPOSED CODING MATRIX tG INSTEAD OF G. USE SCIPY.SPARSE.CSR_MATRIX FORMAT (IN H AND G) TO SPEED UP CALCULATIONS. -------- Image Decoding Function. Taked the 3-D binary coded image where each element is a codeword n-bits array and decodes every one of them. Needs H to decode and tG to solve tG.tv = tx where x is the codeword element decoded by the function itself. When v is found for each codeword, the decoded image can be transformed from binary to uin8 format and shown. Parameters: tG: Transposed Coding Matrix ( SCIPY.SPARSE.CSR_MATRIX FORMAT RECOMMANDED ) H: Parity-Check Matrix (Decoding matrix).( SCIPY.SPARSE.CSR_MATRIX FORMAT RECOMMANDED) img_coded: binary coded image returned by the function ImageCoding. Must be shaped (heigth, width, n) where n is a the length of a codeword (also the number of H's columns) snr: Signal-Noise Ratio: SNR = 10log(1/variance) in decibels of the AWGN used in coding. log: (optional, default = True), if True, Full-log version of BP algorithm is used. max_iter: (optional, default =1), number of iterations of decoding. increase if snr is < 5db. """ n,k = tG.shape width,depth = img_coded[-1,0:2] img_coded = img_coded[:-1,:] height,N = img_coded.shape if N!=n: raise ValueError('Coded Image must have the same number of columns as H') if depth !=8 and depth != 24: raise ValueError('type of image not recognized: third dimension of the binary image must be 8 for grayscale, or 24 for RGB images') if not (tG[:k,:]==np.identity(k)).all(): raise ValueError("G must be Systematic. Solving tG.tv = tx for images has a O(n^3) complexity") if not type(H)==scipy.sparse.csr_matrix: warnings.warn("Used H is not a csr object. Using scipy.sparse.csr_matrix format is highly recommanded when computing row by row coding and decoding to speed up calculations.") img_decoded_bin = np.zeros(shape=(height,k),dtype = int) if log: DecodingFunction = Decoding_logBP_ext else: DecodingFunction = Decoding_BP_ext BitsNodes = BitsAndNodes(H) for i in range(height): decoded_vector = DecodingFunction(H,BitsNodes,img_coded[i,:],snr,max_iter) img_decoded_bin[i,:] = decoded_vector[:k] if depth==8: img_decoded = Bin2Gray(img_decoded_bin.reshape(height,width,depth)) if depth==24: img_decoded = Bin2RGB(img_decoded_bin.reshape(height,width,depth)) return img_decoded def BER(original_img_bin,decoded_img_bin): """ Computes Bit-Error-Rate (BER) by comparing 2 binary images. The ratio of bit errors over total number of bits is returned. """ if not original_img_bin.shape == decoded_img_bin.shape: raise ValueError('Original and decoded images\' shapes don\'t match !') height, width, k = original_img_bin.shape errors_bits = sum(abs(original_img_bin-decoded_img_bin).reshape(height*width*k)) total_bits = np.prod(original_img_bin.shape) BER = errors_bits/total_bits return(BER)
47ebab0595681ce148e3b375e05f966c943cdd76
pradyotprakash/matasano
/all/challenge15.py
579
3.5
4
def paddingValidation(string, blockSize): if len(string) % blockSize != 0: raise Exception("Not PKCS#7 padding!") lastBlock = string[-16:] lastChar = lastBlock[-1] lastCharNum = ord(lastChar) if lastCharNum == 0: raise Exception("Not PKCS#7 padding!") i = lastCharNum - 1 while i >= 0: if lastBlock[-(lastCharNum-i)] != lastChar: raise Exception("Not PKCS#7 padding!") i -= 1 return string[:len(string)-lastCharNum] if __name__ == '__main__': print paddingValidation('ICE ICE BABY1234\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', 16)
e18d097ce869fbc176141c7ae2b0d8a206c4a715
code-gauchos/SamC
/BOM.py
603
3.515625
4
import json import Product jsonFile = open("./machine.json") machine = json.load(jsonFile) print("Let's Build a PC that fits your budget. What setup type would you like? We offer the Budget Gamer, the Mid Ranger, the Power Budget, and the All Out Power.") products = [] for machineCounter in range(len(machine)): product = Product.Product() product.systemName = machine[machineCounter]["systemName"] product.systemPrice = machine[machineCounter]["systemPrice"] products.append(product) print(product.systemName) print(product.systemPrice) machineCounter+=1
6a9d9421a0abf10145985ec3f601fcc1d9c7e7ff
Maximusmax30/LesMilies
/les_milies.py
6,561
3.671875
4
# -*-coding:Latin-1 -* import os # On importe le module os import pickle from gestion_compte import * from function_milies import * from liste_milies import * from commandes_milies import * from characteristique_milies import * from random import randrange os.chdir("D:/programme/Python/PROJET/Les Milies") print("Bienvenue sur le jeu des Milies alpha0.1") continue_partie=True continuer_partie=True changement="1" while continue_partie==True: print("Menu :") print("1 : Jouer") print("2 : Voir les Milies") print("3 : Creer un compte") print("4 : Quitter") choix=input("Votre choix :") try: choix=int(choix) except ValueError: print("Votre choix doit tre un chiffre !") if choix==4: continue_partie=False if choix==3: pseudo=input("Votre pseudo : ") mdp=input("Votre mot de passe : ") compte=ouvrir_compte(pseudo, mdp) if choix==2: print("----------------") for elt in milies: print("{}".format(elt)) print("----------------") if choix==1: verification_compte_j1=False verification_compte_j2=False while verification_compte_j1==False: pseudo_j1=input("Votre pseudo J1 : ") mdp_j1=input("Votre mot de passe J1: ") verification_compte_j1=verifie_compte(pseudo_j1, mdp_j1) liste_j1_milies=charger_milies(pseudo_j1)#fonction a def voir le prog sur gestion mdp pour aide. sauvegarder_milies(pseudo_j1, liste_j1_milies) while verification_compte_j2==False: pseudo_j2=input("Votre pseudo J2 : ") mdp_j2=input("Votre mot de passe J2: ") verification_compte_j2=verifie_compte(pseudo_j2, mdp_j2) liste_j2_milies=charger_milies(pseudo_j2)#fonction a df sauvegarder_milies(pseudo_j2, liste_j2_milies) print("Connexion des deux comptes effectu !") while continuer_partie==True: print("Menu :") print("1 : Lancer partie") print("2 : Changer Milies J1") print("3 : Changer Milies J2") choix=input("Votre choix :") try: choix=int(choix) except ValueError: print("Votre choix doit tre un chiffre !") if choix==2: changer_milies=True print("----------------") for elt in milies: print("{}".format(elt)) print("----------------") while changer_milies==True: print(liste_j1_milies) milies_a_changer=input("Entrez le nom du Milies que vous voulez changer : ") new_milies=input("Entrez le nom du Milies ajouter : ") place_liste_j1=input("En quel position doit-il tre ? (1 3)") liste_j1_milies=changement_milies(milies_a_changer,new_milies,place_liste_j1,liste_j1_milies,milies) choix=input("En changer un autre ? (o/n)") choix=choix.upper() if choix=="O": sauvegarder_milies(pseudo_j1, liste_j1_milies) else: changer_milies=False sauvegarder_milies(pseudo_j1, liste_j1_milies) print("Vos choix on bien t sauvegard !") if choix==3: changer_milies=True print("----------------") for elt in milies: print("{}".format(elt)) print("----------------") while changer_milies==True: print(liste_j2_milies) milies_a_changer=input("Entrez le nom du Milies que vous voulez changer : ") new_milies=input("Entrez le nom du Milies ajouter : ") place_liste_j2=input("En quel position doit-il tre ? (1 3)") liste_j2_milies=changement_milies(milies_a_changer,new_milies,place_liste_j2,liste_j2_milies,milies) choix=input("En changer un autre ? (o/n)") choix=choix.upper() if choix=="O": sauvegarder_milies(pseudo_j2, liste_j2_milies) else: changer_milies=False sauvegarder_milies(pseudo_j2, liste_j2_milies) print("Vos choix on bien t sauvegard !") if choix==1: cmd=CommandMilies() choix_milies=input("blabla: ") print("|-----------------------------|") print("|Charactristique de",choix_milies) print("|-----------------------------|") for cle, valeur in griffal.items(): print("|{} : {}".format(cle, valeur)) print("|-----------------------------|") os.system("pause")
4d1ab49efc9907e015cb8eb8f45c6678f658c5bd
frogermcs/AIND-Isolation
/game_agent.py
16,374
3.625
4
"""This file contains all the classes you must complete for this project. You can use the test cases in agent_test.py to help during development, and augment the test suite with your own test cases to further test your code. You must test your agent's strength against a set of agents with known relative strength using tournament.py and include the results in your report. """ import math class Timeout(Exception): """Subclass base exception for code clarity.""" pass def custom_score(game, player): """Calculate the heuristic value of a game state from the point of view of the given player. Note: this function should be called from within a Player instance as `self.score()` -- you should not need to call this function directly. Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` encoding the current state of the game (e.g., player locations and blocked cells). player : object A player instance in the current game (i.e., an object corresponding to one of the player objects `game.__player_1__` or `game.__player_2__`.) Returns ------- float The heuristic value of the current game state to the specified player. """ if game.is_loser(player): return float("-inf") if game.is_winner(player): return float("inf") # return number_of_moves_and_blank_spaces(game, player) # return number_of_moves_and_location(game, player) return number_of_moves_improved(game, player) # 80-85% def number_of_moves_and_blank_spaces(game, player): """This is modification of our number_of_moves_improved function. Besides moves count difference, there is additional parameter: number of empty fields around current player position minus number of empty fields around opponent. Empty fields are checked in 5x5 square around player (reachable area for L-shaped move). Assumption was that the more empty fields, the better (comparing to opponent). Major factor in this evaluation function was still the difference between player moves and opponent moves. The difference between empty fields around player and opponent is just an adjustment to original evaluation: number_of_moves_improved + (num_of_blanks / 100). Final result is better for about 5% than number_of_moves_improved function. Factors for own_blanks and opp_blanks were found in ranges [0, 10]. (2,1) is the best performing pair. Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` encoding the current state of the game (e.g., player locations and blocked cells). player : hashable One of the objects registered by the game object as a valid player. (i.e., `player` should be either game.__player_1__ or game.__player_2__). Returns ---------- float The heuristic value of the current game state """ opponent = game.get_opponent(player) own_moves = len(game.get_legal_moves(player)) * 5 opp_moves = len(game.get_legal_moves(opponent)) * 2 game_blank_spaces = game.get_blank_spaces() own_blanks = len(get_blank_spaces_around(game, game_blank_spaces, game.get_player_location(player))) * 2 opp_blanks = len(get_blank_spaces_around(game, game_blank_spaces, game.get_player_location(opponent))) * 1 return float(own_moves - opp_moves) + float(own_blanks - opp_blanks) / 100 def get_blank_spaces_around(game, game_blank_spaces, position): """This is helper function to find blank spaces around current position. The biggest possible square around box is 5x5. L shape moves (1,2 or 2,1 in each direction) generates bounds for square in this size. Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` encoding the current state of the game (e.g., player locations and blocked cells). game_blank_spaces : hashable Array of empty spaces in entire board. position : (x, y) Position on board which is the center to find blank spaces around Returns ---------- Array The array of blank spaces around given position """ return [(x, y) for x in range(max(0, position[0] - 2), min(game.width, position[0] + 2) + 1) for y in range(max(0, position[1] - 2), min(game.width, position[1] + 2) + 1) if (x, y) in game_blank_spaces] # (5,2,1) # ~75-80% def number_of_moves_and_location(game, player): """This is modification of our number_of_moves_improved function. Besides moves count difference, there is additional parameter: distance between current player and current opponent position. Assumption that it's better to keep opponent closer to ourselves improved our original evaluation efficiency by ~5%. Factors: 5 (own moves), 2 (opponent moves) and 1 (1/distance) were find as the best in ranges [1, 10] each. Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` encoding the current state of the game (e.g., player locations and blocked cells). player : hashable One of the objects registered by the game object as a valid player. (i.e., `player` should be either game.__player_1__ or game.__player_2__). Returns ---------- float The heuristic value of the current game state """ own_moves = len(game.get_legal_moves(player)) * 5 opp_moves = len(game.get_legal_moves(game.get_opponent(player))) * 2 own_loc = game.get_player_location(player) opp_loc = game.get_player_location(game.get_opponent(player)) distance = math.sqrt((own_loc[0] - opp_loc[0]) ** 2 + (own_loc[1] - opp_loc[1]) ** 2) return float(own_moves - opp_moves + 1 / distance) # 70-75% def number_of_moves_improved(game, player): """This is modified function of The "Improved" evaluation discussed in lecture. Originally both: player and opponent moves are equally important in valuation. Here We used different const factors: 5 for own moves and 2 for opp moves. Factors were found in very simple "Machine Learning" way: in a loops we checked all values (i, j) in range [(1, 1)] ... [(10, 10)], where "i" is own_moves factor and "j" is opp_moves factor. The best performing and most stable values were: (9,1) and (5,2) - the last pair is used in this function. Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` encoding the current state of the game (e.g., player locations and blocked cells). player : hashable One of the objects registered by the game object as a valid player. (i.e., `player` should be either game.__player_1__ or game.__player_2__). Returns ---------- float The heuristic value of the current game state """ own_moves = len(game.get_legal_moves(player)) * 5 opp_moves = len(game.get_legal_moves(game.get_opponent(player))) * 2 return float(own_moves - opp_moves) class CustomPlayer: """Game-playing agent that chooses a move using your evaluation function and a depth-limited minimax algorithm with alpha-beta pruning. You must finish and test this player to make sure it properly uses minimax and alpha-beta to return a good move before the search time limit expires. Parameters ---------- search_depth : int (optional) A strictly positive integer (i.e., 1, 2, 3,...) for the number of layers in the game tree to explore for fixed-depth search. (i.e., a depth of one (1) would only explore the immediate sucessors of the current state.) This parameter should be ignored when iterative = True. score_fn : callable (optional) A function to use for heuristic evaluation of game states. iterative : boolean (optional) Flag indicating whether to perform fixed-depth search (False) or iterative deepening search (True). When True, search_depth should be ignored and no limit to search depth. method : {'minimax', 'alphabeta'} (optional) The name of the search method to use in get_move(). timeout : float (optional) Time remaining (in milliseconds) when search is aborted. Should be a positive value large enough to allow the function to return before the timer expires. """ def __init__(self, search_depth=3, score_fn=custom_score, iterative=True, method='alphabeta', timeout=10.): self.search_depth = search_depth self.iterative = iterative self.score = score_fn self.method = method self.time_left = None self.TIMER_THRESHOLD = timeout def get_move(self, game, legal_moves, time_left): """Search for the best move from the available legal moves and return a result before the time limit expires. This function must perform iterative deepening if self.iterative=True, and it must use the search method (minimax or alphabeta) corresponding to the self.method value. ********************************************************************** NOTE: If time_left < 0 when this function returns, the agent will forfeit the game due to timeout. You must return _before_ the timer reaches 0. ********************************************************************** Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` encoding the current state of the game (e.g., player locations and blocked cells). legal_moves : list<(int, int)> DEPRECATED -- This argument will be removed in the next release time_left : callable A function that returns the number of milliseconds left in the current turn. Returning with any less than 0 ms remaining forfeits the game. Returns ------- (int, int) Board coordinates corresponding to a legal move; may return (-1, -1) if there are no available legal moves. """ if not legal_moves: return (-1, -1) self.time_left = time_left # Perform any required initializations, including selecting an initial # move from the game board (i.e., an opening book), or returning # immediately if there are no legal moves def keep_spinning(): return time_left() > 0 and (self.search_depth == -1 or depth <= self.search_depth) move = (-1, -1) try: depth = 1 if self.iterative: while keep_spinning(): move = self.find_best_move(depth, game, legal_moves) depth += 1 else: move = self.find_best_move(depth, game, legal_moves) except Timeout: pass finally: return move def find_best_move(self, depth, game, legal_moves): if self.method == "minimax": _, move = self.minimax(game, depth) elif self.method == "alphabeta": _, move = self.alphabeta(game, depth) else: _, move = max([(self.score(game.forecast_move(m), self), m) for m in legal_moves]) return move def minimax(self, game, depth, maximizing_player=True): """Implement the minimax search algorithm as described in the lectures. Parameters ---------- game : isolation.Board An instance of the Isolation game `Board` class representing the current game state depth : int Depth is an integer representing the maximum number of plies to search in the game tree before aborting maximizing_player : bool Flag indicating whether the current search depth corresponds to a maximizing layer (True) or a minimizing layer (False) Returns ------- float The score for the current search branch tuple(int, int) The best move for the current branch; (-1, -1) for no legal moves Notes ----- (1) You MUST use the `self.score()` method for board evaluation to pass the project unit tests; you cannot call any other evaluation function directly. """ if self.time_left() < self.TIMER_THRESHOLD: raise Timeout() legal_moves = game.get_legal_moves() if not legal_moves: return (-1, -1) def min_value(game, d): if d == depth: return self.score(game, self) legal_moves = game.get_legal_moves() if not legal_moves: return -1 v = float("inf") for move in legal_moves: v = min(v, max_value(game.forecast_move(move), d + 1)) return v def max_value(game, d): if d == depth: return self.score(game, self) legal_moves = game.get_legal_moves() if not legal_moves: return -1 v = float("-inf") for move in legal_moves: v = max(v, min_value(game.forecast_move(move), d + 1)) return v best_move = float("-inf"), (-1, -1) for move in legal_moves: best_move = max(best_move, (min_value(game.forecast_move(move), 1), move)) return best_move def alphabeta(self, game, depth, alpha=float("-inf"), beta=float("inf"), maximizing_player=True): """Implement minimax search with alpha-beta pruning as described in the lectures. Parameters ---------- game : isolation.Board An instance of the Isolation game `Board` class representing the current game state depth : int Depth is an integer representing the maximum number of plies to search in the game tree before aborting alpha : float Alpha limits the lower bound of search on minimizing layers beta : float Beta limits the upper bound of search on maximizing layers maximizing_player : bool Flag indicating whether the current search depth corresponds to a maximizing layer (True) or a minimizing layer (False) Returns ------- float The score for the current search branch tuple(int, int) The best move for the current branch; (-1, -1) for no legal moves Notes ----- (1) You MUST use the `self.score()` method for board evaluation to pass the project unit tests; you cannot call any other evaluation function directly. """ if self.time_left() < self.TIMER_THRESHOLD: raise Timeout() legal_moves = game.get_legal_moves() if not legal_moves: return (-1, -1) def min_value(game, d, alpha, beta): if d == depth: return self.score(game, self) legal_moves = game.get_legal_moves() if not legal_moves: return -1 v = float("inf") for move in legal_moves: v = min(v, max_value(game.forecast_move(move), d + 1, alpha, beta)) if v <= alpha: return v beta = min(v, beta) return v def max_value(game, d, alpha, beta): if d == depth: return self.score(game, self) legal_moves = game.get_legal_moves() if not legal_moves: return -1 v = float("-inf") for move in legal_moves: v = max(v, min_value(game.forecast_move(move), d + 1, alpha, beta)) if v >= beta: return v alpha = max(v, alpha) return v best_move = float("-inf"), (-1, -1) for move in legal_moves: best_move = max(best_move, (min_value(game.forecast_move(move), 1, alpha, beta), move)) alpha = best_move[0] return best_move
eb6e112fbf2a8a3fcf4ac1a137cd6651b322959d
unpsjb-ieee-student-branch/curso-python
/Colab/05-OOP/examples/bravo_1.py
827
3.953125
4
# How to debug # sears.py bill_thickness = 0.11 * 0.001 # Meters (0.11 mm) sears_height = 442 # Height (meters) num_bills = 1 day = 1 while num_bills * bill_thickness < sears_height: print(day, num_bills, num_bills * bill_thickness) day = days + 1 num_bills = num_bills * 2 print('Number of days', day) print('Number of bills', num_bills) print('Final height', num_bills * bill_thickness) # Reading error messages is an important part of Python code. # If your program crashes, the very last line of the traceback message # is the actual reason why the the program crashed. # Above that, you should see a fragment of source code and then an identifying filename and line number. # Which line is the error? # What is the error? # Fix the error # Run the program successfully
2ca7c4e31ad857f80567942a0934d9399a6da033
zoeyangyy/algo
/exponent.py
600
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Time : 2018/8/16 下午10:27 # @Author : Zoe # @File : exponent.py # @Description : # -*- coding:utf-8 -*- class Solution: def Power(self, base, exponent): # write code here result = base if exponent == 0: return 1 elif exponent > 0: for i in range(exponent-1): result *= base return result else: for i in range(-exponent-1): result *= base return 1/result c = Solution() print(c.Power(2,-3))
bce4de78e56bd835490c43ff95d25fadd905ee97
zoeyangyy/algo
/arrange_min.py
1,373
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Time : 2018/8/21 下午10:34 # @Author : Zoe # @File : arrange_min.py # @Description : # class Solution: # def PrintMinNumber(self, numbers): # # write code here # str_li = [str(one) for one in numbers] # sort = self.quick(str_li, 0, len(str_li)-1) # return ''.join(sort) # # def quick(self, li, start, end): # if start < end: # base = li[start] # i, j = start, end # while i < j: # while j > i and self.compare(li[j],base): # j -= 1 # li[i] = li[j] # while i < j and self.compare(base, li[i]): # i += 1 # li[j] = li[i] # li[i] = base # self.quick(li, start, i - 1) # self.quick(li, j + 1, end) # return li # # def compare(self, A, B): # if int(A+B) > int(B+A): # return True # A>=B # return False class Solution: def PrintMinNumber(self, numbers): # write code here if not numbers: return "" lmb = lambda n1, n2:int(str(n1)+str(n2))-int(str(n2)+str(n1)) array = sorted(numbers, cmp=lmb) return ''.join([str(i) for i in array]) print(Solution().PrintMinNumber([3,321,4,45,43]))
a3ebe6e0f49e7e61fd94455218577b5d5e81dbc5
itgsod-julia-waldhagen/Uppgift---Filter
/lib/filters.py
391
3.90625
4
lista = ["Papaya", "Banan", "Apelsin", "Banan", "Druvor", "Melon"] def filter(lista, x): newlista = [] for i in lista: if i == x: newlista.append(i) return newlista print filter(lista,"Banan") def exclude(lista, x): for i in range(len(lista)-1,-1,-1): if lista[i] == x: lista.pop(i) return lista print exclude(lista, "Banan")
36d281d594ec06a38a84980ca15a5087ccb2436a
connor-giles/Blackjack
/hand.py
847
4.125
4
"""This script holds the definition of the Hand class""" import deck class Hand: def __init__(self): self.cards = [] # A list of the current cards in the user's hand self.hand_value = 0 # The actual value of the user's hand self.num_aces = 0 # Keeps track of the number of aces that the user has def __len__(self): return len(self.cards) def add_card(self, new_card): self.cards.append(new_card) self.hand_value += deck.values[new_card.rank] if new_card.rank == 'Ace': self.num_aces += 1 def adjust_for_ace(self): # If the users hand value is greater than 21 but the user still has an ace, you need to re-adjust the hand value while self.hand_value > 21 and self.num_aces: self.hand_value -= 10 self.num_aces -= 1
a3c08ecf3ee320a6b7a9956dd56d1145826b8e88
mpumbya/shoppinglist
/test/ntest_bank.py
732
3.65625
4
import unittest from bank import BankAccount class AccountBalanceTestCases(unittest.TestCase): def setUp(self): self.account_yangu = BankAccount() def test_balance(self): self.assertEqual(self.account_yangu.balance, 3000, msg= 'Account balance Invalid') def test_deposit(self): self.account_yangu.deposit(4000) self.assertEqual(self.account_yangu.balance, 7000, msg='deposit has jam') def test_withdraw(self): self.account_yangu.withdraw(500) self.assertEqual(self.account_yangu.balance, 2500, msg='withdraw has jam') def test_invalid_trans(self): self.assertEqual(self.account_yangu.withdraw(6000), "invalid transaction", msg ='invalid transaction')
aa8032e5c37f4954258a53de50d658799af3c5a8
Shajidur-Rahman/Automatic_Messenger
/main.py
343
3.578125
4
number_of_message = int(input("How many message do you want to send? ")) import pyautogui import time message = 0 while message < number_of_message: time.sleep(2) pyautogui.typewrite('hello we make song and programming projects. Now i made a project called automatic messenger') pyautogui.press('enter') message = 1 + message
878a1e71286c0a41bfb6a205cd9c70b91ff74bf9
Fuzzy087/FizzBuzz
/main.py
580
4.0625
4
primes = [] for possiblePrime in range(2, 100): isPrime = True for num in range(2, possiblePrime): if possiblePrime % num == 0: isPrime = False if isPrime: primes.append(possiblePrime) print(primes) for num in range(1, 100): if num in primes: print(num, "Prime") elif num % 5 == 0 and num % 3 == 0: print (num, "FizzBuzz") elif num % 5 == 0 and num % 3 != 0: print (num, "Fizz") elif num % 5 != 0 and num % 3 == 0: print (num, "Buzz") else: print(num)
660681269136d8731f9b01fea37dc16b1ebe577a
i-soo/PS
/BOJ/Steps/Step1/2588-a.py
317
3.75
4
inp1 = int(input()) # int형으로 변환 inp2 = input() # 문자열 그대로 저장 # 문자열의 인덱스를 이용 out1 = inp1 * int(inp2[2]) out2 = inp1 * int(inp2[1]) out3 = inp1 * int(inp2[0]) result = inp1 * int(inp2) # sep='\n'로 한번에 출력 처리 print(out1, out2, out3, result, sep='\n')
b1c3f1c7eba77049582306dbf076a2c75042caa7
i-soo/PS
/BOJ/Steps/Step5/3052.py
123
3.515625
4
nums = [] for i in range(10): temp = int(input()) nums.append(temp%42) num_list = set(nums) print(len(num_list))
3423f54a655e7812a3328e29fee3bc3123a93700
i-soo/PS
/BOJ/Steps/Step1/2588-b.py
274
3.59375
4
inp1 = int(input()) inp2 = int(input()) # int형으로 변환 # 자릿수 각각을 계산 out1 = inp1*((inp2%100)%10) out2 = inp1*((inp2%100)//10) out3 = inp1*(inp2//100) result = inp1*inp2 # sep='\n'로 한번에 출력 처리 print(out1, out2, out3, result, sep='\n')
cf9364dc72547a3058d861b6234668e21d1b681c
KrisAlone2k/matura_inf
/67/67-1.py
646
3.6875
4
#zad 1 print('zad 1') x = 1 fib = [1,1] for i in range(2,40): fib.append(fib[i-2] + fib[i-1]) print('F10',fib[9]) print('F20',fib[19]) print('F30',fib[29]) print('F40',fib[39]) #zad 2 print('zad 2') def isPrime(x): i = 2 if x >= 2: while i < x: if x%i == 0: return False i += 1 return True else: return False for number in fib: if isPrime(number): print(number) #zad 3 print('zad 3') for number in fib: print(format(number,'0b')) #zad 4 print('zad 4') for x in fib: number = str(bin(x)[2:]) if number.count('1') == 6: print(number)
6b16f67a76c4951b641d252d40a1931552381975
by46/geek
/codewars/4kyu/52e864d1ffb6ac25db00017f.py
2,083
4.1875
4
"""Infix to Postfix Converter https://www.codewars.com/kata/infix-to-postfix-converter/train/python https://www.codewars.com/kata/52e864d1ffb6ac25db00017f Construct a function that, when given a string containing an expression in infix notation, will return an identical expression in postfix notation. The operators used will be +, -, *, /, and ^ with standard precedence rules and left-associativity of all operators but ^. The operands will be single-digit integers between 0 and 9, inclusive. Parentheses may be included in the input, and are guaranteed to be in correct pairs. to_postfix("2+7*5") # Should return "275*+" to_postfix("3*3/(7+1)") # Should return "33*71+/" to_postfix("5+(6-2)*9+3^(7-1)") # Should return "562-9*+371-^+" c++ to_postfix("2+7*5") # Should return "275*+" to_postfix("3*3/(7+1)") # Should return "33*71+/" to_postfix("5+(6-2)*9+3^(7-1)") # Should return "562-9*+371-^+" You may read more about postfix notation, also called Reverse Polish notation, here: http://en.wikipedia.org/wiki/Reverse_Polish_notation """ ORDERS = { '+': 1, '-': 1, '*': 2, '/': 2, '^': 3, '(': 0, ')': 4 } def to_postfix(infix): """Convert infix to postfix >>> to_postfix("2+7*5") '275*+' >>> to_postfix("3*3/(7+1)") '33*71+/' >>> to_postfix("5+(6-2)*9+3^(7-1)") '562-9*+371-^+' >>> to_postfix("(5-4-1)+9/5/2-7/1/7") '54-1-95/2/+71/7/-' """ stack = [] result = [] for c in infix: if c.isdigit(): result.append(c) elif c == '(': stack.append(c) elif c == ')': while stack[-1] != '(': result.append(stack.pop()) stack.pop() else: while stack and ORDERS[stack[-1]] >= ORDERS[c]: result.append(stack.pop()) stack.append(c) if stack: result.extend(reversed(stack)) return ''.join(result) if __name__ == '__main__': import doctest doctest.testmod()
df1fc547862bf9ec5259c00c39e591857b73b8b3
Aurelius10/kattisTasks
/hard/completed/0_1sequence/test3.py
8,524
3.546875
4
import sys import math def add(x): return int((x+1)*x/2) def nCr_list_n2(num): res_list = [] meas = int(num/2 + 0.5) res_list = [0]*(meas+1) res_list[0] = 1 for i in range(1, meas+1): res_list[i] = res_list[i-1]*(num+1-i)//i return res_list def nCr_list_test(num): res_list = [] meas = int(num/2 + 0.5) res_list.append(1) for i in range(1, meas+1): factor = (num+1-i)//i res_list.append((res_list[i-1]*factor)) return res_list def nCr_list_n1(num): res_list = [] meas = num/2 + 0.5 alpha_list = [] t = time.time() alpha = math.factorial(num) alpha_list.append(1) alpha_list.append(1) for i in range(2, num-1): alpha_list.append(alpha_list[i-1]*i) print("tester:", time.time() - t) i = 2 res_list.append(1) res_list.append(num) while i < meas: res_list.append(alpha//(alpha_list[i]*alpha_list[num-i])) i += 1 return res_list def nCr_n(x, y, al): return al//(math.factorial(y)*math.factorial(x-y)) def nCr_list_n(num, al): res_list = [] meas = num/2 + 0.5 i = 0 while i < meas: res_list.append(nCr_n(num, i, al)) i += 1 return res_list def nCr(x, y): return math.factorial(x)//(math.factorial(y)*math.factorial(x-y)) def nCr_list(num): res_list = [] meas = num/2 + 0.5 i = 0 while i < meas: res_list.append(nCr(num, i)) i += 1 return res_list def teller4(string): t = time.time() number = 10**9+7 count0=0 count_spm=0 sum0 = 0 sumS = 0 for i in range(len(string)): if string[i]=="0": count0+=1 sum0 += i+1 elif string[i] == "?": count_spm+=1 sumS += i+1 fac1 = (2**count_spm)%number res = (sum0-add(count0))*fac1 fac2 = (2**(count_spm-1)) res += sumS*fac2%number print("Interval1:", time.time()-t) t = time.time() if count_spm == 0: return int(res) elif count_spm == 1: res -= (count0+1) return int(res) else: fac3 = (count_spm)*fac2 res -= fac3*(count0+1) res -= (count_spm-1)*fac3//4 return res%number def teller2(string): t = time.time() number = 10**9+7 count0=0 count_spm=0 sum0 = 0 sumS = 0 for i in range(len(string)): if string[i]=="0": count0+=1 sum0 += i+1 elif string[i] == "?": count_spm+=1 sumS += i+1 fac1 = 2**count_spm res = (sum0-add(count0))*fac1 fac2 = fac1//2 res += sumS*fac2 counter = 1 print("Interval1:", time.time()-t) t = time.time() facs = nCr_list_n2(count_spm) ind = 1 print("Interval2:", time.time()-t) t = time.time() for ind in range(1, int(count_spm/2)+1): res -= (count0 + ind) * (fac1 - counter) counter += facs[ind] pen = 0 if count_spm%2==0: pen = 1 if count_spm != 1: ind += 1 for j in range(int(count_spm/2+0.5)): res -= (count0 + j + ind) * (fac1 - counter) counter += facs[int(count_spm/2)-j-pen] print("Interval3:", time.time()-t) res = res%number return res #---------------------------------------------------------------------- def teller1(string): t = time.time() number = 10**9+7 count0=0 count_spm=0 sum0 = 0 sumS = 0 for i in range(len(string)): if string[i]=="0": count0+=1 sum0 += i+1 elif string[i] == "?": count_spm+=1 sumS += i+1 fac1 = 2**count_spm res = (sum0-add(count0))*fac1 fac2 = fac1//2 res += sumS*fac2 counter = 1 print("Interval1:", time.time()-t) t = time.time() facs = nCr_list_n1(count_spm) ind = 1 print("Interval2:", time.time()-t) t = time.time() for ind in range(1, int(count_spm/2)+1): res -= (count0 + ind) * (fac1 - counter) counter += facs[ind] pen = 0 if count_spm%2==0: pen = 1 if count_spm != 1: ind += 1 for j in range(int(count_spm/2+0.5)): res -= (count0 + j + ind) * (fac1 - counter) counter += facs[int(count_spm/2)-j-pen] print("Interval3:", time.time()-t) res = res%number return res #---------------------------------------------------------------------- def teller_old(string): t = time.time() number = 10**9+7 count0=0 count_spm=0 sum0 = 0 sumS = 0 for i in range(len(string)): if string[i]=="0": count0+=1 sum0 += i+1 elif string[i] == "?": count_spm+=1 sumS += i+1 fac1 = 2**count_spm res = (sum0-add(count0))*fac1 fac2 = fac1//2 res += sumS*fac2 counter = 1 print("Interval1:", time.time()-t) t = time.time() alpha = math.factorial(count_spm) facs = nCr_list_n(count_spm, alpha) ind = 1 print("Interval2:", time.time()-t) t = time.time() for ind in range(1, int(count_spm/2)+1): res -= (count0 + ind) * (fac1 - counter) counter += facs[ind] pen = 0 if count_spm%2==0: pen = 1 if count_spm != 1: ind += 1 for j in range(int(count_spm/2+0.5)): res -= (count0 + j + ind) * (fac1 - counter) counter += facs[int(count_spm/2)-j-pen] print("Interval3:", time.time()-t) res = res%number return res #---------------------------------------------------------------------- def teller_old_old(string): t = time.time() number = 10**9+7 count0=0 count1=0 count_spm=0 sum0 = 0 idx_1 = [] idx_spm = [] length = len(string) for i in range(length): if string[i]=="0": count0+=1 sum0 += i + 1 elif string[i]=="1": count1+=1 idx_1.append(i+1) elif string[i] == "?": count_spm+=1 idx_spm.append(i+1) res = (sum0-add(count0))*2**count_spm for index_spm in idx_spm: res += index_spm*2**(count_spm-1) counter = 1 print("Interval1:", time.time()-t) t = time.time() facs = nCr_list(count_spm) ind = 1 print("Interval2:", time.time()-t) t = time.time() for ind in range(1, int(count_spm/2)+1): res -= (count0 + ind) * (2**count_spm - counter) counter += facs[ind] pen = 0 if count_spm%2==0: pen = 1 if count_spm != 1: ind += 1 for j in range(int(count_spm/2+0.5)): res -= (count0 + j + ind) * (2**count_spm - counter) counter += facs[int(count_spm/2)-j-pen] print("Interval3:", time.time()-t) res = res%number return res #---------------------------------------------------------------------- def teller_old_old_old(string): t = time.time() number = 10**9+7 count0=0 count1=0 count_spm=0 sum0 = 0 idx_1 = [] idx_spm = [] length = len(string) for i in range(length): if string[i]=="0": count0+=1 sum0 += i + 1 elif string[i]=="1": count1+=1 idx_1.append(i+1) elif string[i] == "?": count_spm+=1 idx_spm.append(i+1) res = (sum0-add(count0))*2**count_spm print("Interval1:", time.time()-t) t = time.time() for index_spm in idx_spm: res += index_spm*2**(count_spm-1) counter = 1 print("Interval2:", time.time()-t) t = time.time() for i in range(1, count_spm+1): factor = nCr(count_spm, i) res -= (count0 + i) * (2**(count_spm)-counter) #print(count0 + i, factor, counter) counter += factor print("Interval3:", time.time()-t) res = res%number return res #------------------------------------------------------------------ #-- MAKING TEST #------------------------------------------------------------------ import random string="" for i in range(1000000): rand = random.random() if rand < 0.33: string = string+"0" elif rand < 0.67: string = string+"1" else: string = string+"?" #print(string) #sys.stdin = open("test.in") #string = sys.stdin.readlines()[0] import time t = time.time() print("---teller4---") print(teller4(string)) print("elapsed:", time.time()-t) t = time.time() print("---teller2---") print(teller2(string)) print("elpased:", time.time()-t) #t = time.time() #print("---NEW---") #print(teller_old(string)) #print("elapsed:", time.time()-t)
4bb5d3cdaa0029076e7f1e7cc68b809e51913d1f
anshu3769/KeplerProject
/Backend/data/models.py
1,729
3.5
4
""" This module contains all the models required by the application. """ from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, func from sqlalchemy.orm import backref, relationship from .database import Base class Player(Base): """ Class to create a table for storing a player's personal information """ __tablename__ = 'player' id = Column(Integer,primary_key=True) first_name = Column(String) last_name = Column(String) user_name = Column(String, nullable=False, unique=True) # to have a relationship with scores scores = relationship('Score') class Score(Base): """ Class to create a table for storing player's scores """ __tablename__ = 'score' id = Column(Integer, primary_key=True) user_name = Column(String, ForeignKey('player.user_name')) value = Column(Integer) player = relationship( Player, backref=backref( 'score', uselist=True, cascade='delete,all' ) ) class TopFiveScore(Base): """ Class to create a table for storing top five scores for across all the players """ __tablename__ = 'topfivescore' id = Column(Integer,primary_key=True) value = Column(Integer) user_name = Column(String, ForeignKey('player.user_name')) player = relationship( Player, backref=backref('topfivescore', uselist=True, cascade='delete,all' ) ) class Word(Base): """ Class to create a table for storing words """ __tablename__ = 'words' id = Column(Integer,primary_key=True) word = Column(String)
6871c3ff47b4586a2b566ca6f1c4aaa6cb0f5031
tomomof/kadai
/0726kadai.py
117
3.703125
4
x=4545 print(x) x_str=str(x) print("my fav num is", x, ".", "x=", x) print("my fav num is " + x_str +"."+"x="+x_str)
2b5931eade99c213d86c4f5a26eed1ec45dea907
tianchengcheng-cn/LeetCode
/动态规划/5-最长回文字串.py
889
3.640625
4
""" 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 输入: "babad" 输出: "bab" 注意: "aba" 也是一个有效答案。 """ class Solution: def longestPalindrome(self, s: str) -> str: n = len(s) # 中心扩展 # 判断边界条件 if n == 0: return "" def extend(i: int, j: int, s: str) -> str: while (i >= 0 and j < len(s) and s[i] == s[j]): i -= 1 j += 1 return s[i + 1 : j] max_len = 1 tmp = s[0] for i in range(n - 1): e1 = extend(i, i, s) e2 = extend(i, i + 1, s) max_e = max(len(e1), len(e2)) if max_e >= max_len: max_len = max_e tmp = e1 if len(e1) > len(e2) else e2 return tmp
617ad0d0bc92053499ee96aa212c6d9bc14fd38c
tianchengcheng-cn/LeetCode
/双指针/239-滑动窗口中的最大值.py
1,223
3.71875
4
""" 给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。 返回滑动窗口中的最大值。 输入:nums = [1,3,-1,-3,5,3,6,7], k = 3 输出:[3,3,5,5,6,7] 解释: 滑动窗口的位置 最大值 --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 时空复杂度:O(n), O(k) """ from typing import List class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: # 双端队列 deque = collections.deque() ans = [] n = len(nums) for i, j in zip(range(1 - k, n + 1 - k), range(n)): if i > 0 and deque[0] == nums[i - 1]: deque.popleft() # 删除小数,保证deque内部递减 while deque and deque[-1] < nums[j]: deque.pop() deque.append(nums[j]) if i >= 0: ans.append(deque[0]) return ans
810e0a5b90c6973ad04f2fcc20b8fe4451bbec7b
dararod/python-101
/lista_de_compras.py
492
3.921875
4
lista_de_compras = [] preguntar_de_vuelta = True while preguntar_de_vuelta: # obtiene el producto del usuario item = input("Ingrese producto: ") # agrega el producto a la lista lista_de_compras.append(item) # preguntar si desea continuar continuar = int(input("Desea agregar otro item?: (0: No/1: Si)")) if continuar == 1: continue else: preguntar_de_vuelta = False break print("Seleccion de la lista: ") for producto in lista_de_compras: print(producto)
82e3e5f9567aca3deda01c7bc8a5157d44c4947f
Akai-Kumako/100knock
/Chapter1/00.py
80
3.578125
4
#00.文字列の逆順 f = reversed(list("stressed")) a = ''.join(f) print(a)
f0b311eb85eb267e0e4e4ca3da2af2fba1071451
apugithub/Python_Self
/pandas_intro.py
795
3.921875
4
import pandas as pd df = pd.read_csv('data/pokemon_data.csv') #Dataframe (the core of pandas) #print(df) # Print the dataframe #print(df.info()) #Prints the summary of dataframe #print(df.head()) # head prints first 5 records + you may specify number inside head too #print(df['HP'].max()) # displaying the max value of the column HP #print(df.columns) # prints the column names #print (df[['HP','Name']]) #Multiple columns... by specifying a list #print(df['HP'][10:15]) #print(df.iloc[0:4,[0,1,2,3]]) # 0:4 is the index range of rows and [0,1,2,3] are the position of columns like 1st, 2nd #print(df.loc[df['HP']==80]) #like where condition #print(df.describe()) #print(df.shape) # returns number of rows and columns print (df.count()) # returns column wise not null count
81cfaff6e7ed2ac0be013d2439592c4fb8868e63
apugithub/Python_Self
/negetive_num_check.py
355
4.15625
4
# Negetive number check def check(num): return True if (num<0) else False print(check(-2)) ### The function does check and return the negatives from a list lst = [4,-5,4, -3, 23, -254] def neg(lst): return [num for num in lst if num <0] # or the above statement can be written as= return sum([num < 0 for num in nums]) print(neg(lst))
0d4883a8d8d46f1e6b5fb5fd1e9647abac80034e
ftahrirc/Snake1
/snake.py
752
3.859375
4
import turtle,random class Cell: def__init__(self,size,t,x,y): self.x=x self.y=y self.t=t self.size=size def draw_square(self): for side in range(4): self.t.fd(self.size) self.t.left(90) def draw_snake()(self) for side in range(5): cell=cell(10,turtle.turtle(),i*10,i*10) cell.draw_square() cell.draw_snake() cell=Cell(10,turtle.Turtle(),0,0) cell.draw_square() class food: def__init__(self): self.cell=Cell(x,y) class Cell: def __init__(self,t): # set initial position self.x = 0 self.y = 0 # set initial size of a cell self.cell_size = 10 # set the turtle self.t = t
41f879b9e85bc1dd1fab73cba29e6e5828d6a1be
jurogrammer/studying
/algorithm_study/week3/190129/InJae/[SWEA]1231.중위순회.py
441
3.78125
4
def InorderTraveral(tree,i,N): if i<=N: InorderTraveral(tree,i*2,N) print(tree[i],end="") InorderTraveral(tree,i*2+1,N) for t in range(1,11): N = int(input()) tree = [0 for _ in range(N+1)] for _ in range(N): inputValue = input().split(" ") node, item = inputValue[0:2] tree[int(node)] = item print("#{}".format(t),end = " ") InorderTraveral(tree,1,N) print("")
c71ff8bc6ad2d290c7ed03222e46acbc5570f481
jurogrammer/studying
/Algorithm/[프로그래머스]가장먼노드.py
1,173
3.515625
4
from queue import Queue #인접행렬로 만들기엔 2만이므로 공간복잡도가 매우 큼. 2만x2만 -> 4백만. def ConvertEdgeToGraph(edge): #1번 노드부터 시작, 최대 2만개. 그래프는 인덱스가 u,value가 v graph = [[] for _ in range(20001)] #양방향 그래프 for u,v in edge: graph[u].append(v) graph[v].append(u) return graph def solution(n, edge): # BFS로 탐색하나, 최종 size 기록. 매 size만큼 pop해주는 과정 거치기. #초기화 que = Queue() graph = ConvertEdgeToGraph(edge) visited = 1<<1 que.put(1) #큐가 빌때까지 반복(마지막까지) while not que.empty(): #사이즈 얻기 size = que.qsize() #사이즈 만큼 pop하고 pop한 vertex에서 다음으로 이동한 것 que에 삽입 for _ in range(size): u = que.get() for v in graph[u]: if not visited&(1<<v): que.put(v) visited = visited|(1<<v) answer = size return answer n = 6 edge = [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]] print(solution(n,edge))
4419c26eda4759d30d80a8e9681c8164f60414ac
jurogrammer/studying
/Algorithm/[백준]9461.파도반수열.py
271
4
4
''' https://jurogrammer.tistory.com/6 ''' memo = {1:1,2:1,3:1} def Wave(n): if n in memo: return memo[n] else: memo[n] = Wave(n-2)+Wave(n-3) return memo[n] n = int(input()) for _ in range(n): req = int(input()) print(Wave(req))
0e5b6c497c37d0e6023ddc712687dc588f85ffd7
jurogrammer/studying
/algorithm_study/week1/200108/InJae/[SWEA_lesson6_1day]min_max.py
660
3.6875
4
def BubbleSort(input_list): #input : list , output= sorted_list for i in range(len(input_list)-1,-1,-1): for j in range(0,i): if input_list[j]>input_list[j+1]: temp = input_list[j] input_list[j] = input_list[j+1] input_list[j+1] = temp return input_list n_test = int(input()) rst_list = [] for _ in range(n_test): n_my_list = int(input()) my_list = list(map(int,input().split())) sorted_my_list = BubbleSort(my_list) rst_list.append(sorted_my_list[n_my_list-1]-sorted_my_list[0]) for t,rst_list in enumerate(rst_list): print("#{} {}".format(t+1,rst_list))
1fcd14f968db19cc71a7409145afa61c6031d728
gaylonalfano/Python-3-Bootcamp
/__name__variable.py
1,067
3.546875
4
''' A "dunder" variable. Special properties represented by __name__ variable. When run, every Python file/module has its own __name__ variable. If the file is the main file being run, its value is "__main__". Otherwise, its value is the file name. ***check out say_hi.py and say_sup.py for example*** Basically, the __name__ variable is set to __main__ in the main/executed file. But, if you Here's what happens you import something: 1. Tries to find the module (if it doesn't find it, it throws an error). 2. But if found, it runs the code inside of the module being imported So, in the example with say_hi and say_sup, when you import say_sup into the say_hi file, it will run the code in the say_sup module FIRST, which has a say_sup() function call. If you want to prevent this code from running, then here's the trick to ignore code on import: if __name__ == "__main__": # this code will only run # if the file is the main file! Ex. Modify the say_sup.py file and add this code to call the function: if __name__ == "__main__": say_sup() '''
8f27badfdef2487c0eb87e659fac64210faa1646
gaylonalfano/Python-3-Bootcamp
/card.py
767
4.125
4
# Card class from deck of cards exercise. Using for unit testing section # Tests: __init__ and __repr__ functions from random import shuffle class Card: available_suits = ("Hearts", "Diamonds", "Clubs", "Spades") available_values = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K") def __init__(self, suit, value): if suit not in Card.available_suits: raise ValueError # (f"{suit} is not a valid suit.") elif str(value) not in Card.available_values: raise ValueError # (f"{value} is not a valid value.") else: self.suit = suit self.value = value def __repr__(self): return "{} of {}".format(self.value, self.suit) # f"{self.value} of {self.suit}"
6bcb51fae80c295f98d6004344c5ffec1028f602
gaylonalfano/Python-3-Bootcamp
/infinite_generators_get_multiples.py
649
4.21875
4
# def get_multiples(number=1, count=10): # for i in range(1, count+1): # yield number*i # # evens = get_multiples(2, 3) # print(next(evens)) # print(next(evens)) # print(next(evens)) # print(next(evens)) # GET_UNLIMITED_MULTIPLES EXERCISE: def get_unlimited_multiples(number=1): next_num = number while True: yield next_num next_num += number # Student's example with * # def get_unlimited_multiples(num=1): # next_num = 1 # while True: # yield num*next_num # next_num += 1 fours = get_unlimited_multiples(4) print(next(fours)) print(next(fours)) print(next(fours)) print(next(fours))
d3aab6c3a00102b36f6eea2c25e5bd4015217d9b
gaylonalfano/Python-3-Bootcamp
/deck_of_cards_class_project.py
9,080
4.21875
4
''' Introduction Your goal in this exercise is to implement two classes, Card and Deck . Specifications Card Each instance of Card should have a suit ("Hearts", "Diamonds", "Clubs", or "Spades"). Each instance of Card should have a value ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"). Card 's __repr__ method should return the card's value and suit (e.g. "A of Clubs", "J of Diamonds", etc.) Deck: Each instance of Deck should have a cards attribute with all 52 possible instances of Card . Deck should have an instance method called count which returns a count of how many cards remain in the deck. Deck 's __repr__ method should return information on how many cards are in the deck (e.g. "Deck of 52 cards", "Deck of 12 cards", etc.) Deck should have an instance method called _deal which accepts a number and removes at most that many cards from the deck (it may need to remove fewer if you request more cards than are currently in the deck!). If there are no cards left, this method should return a ValueError with the message "All cards have been dealt". Deck should have an instance method called shuffle which will shuffle a full deck of cards. If there are cards missing from the deck, this method should return a ValueError with the message "Only full decks can be shuffled". shuffle should return the shuffled deck. Deck should have an instance method called deal_card which uses the _deal method to deal a single card from the deck and return that single card. Deck should have an instance method called deal_hand which accepts a number and uses the _deal method to deal a list of cards from the deck and return that list of cards. ''' from random import shuffle class Card: available_suits = ("Hearts", "Diamonds", "Clubs", "Spades") available_values = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K") def __init__(self, suit, value): if suit not in Card.available_suits: raise ValueError # (f"{suit} is not a valid suit.") elif str(value) not in Card.available_values: raise ValueError # (f"{value} is not a valid value.") else: self.suit = suit self.value = value def __repr__(self): return "{} of {}".format(self.value, self.suit) # f"{self.value} of {self.suit}" class Deck: def __init__(self): # Save each instance of Card to the cards list attribute -- how? # Not fully sure about the self.name = name, self.cards = cards naming/meaning? # Can set self.cards to a list instead of cards??? # **Think of these attributes as key: value pairs. See Chicken Coop hard set eggs self.cards = [Card(s, v) for v in Card.available_values for s in Card.available_suits] def __repr__(self): return f"Deck of {self.count()} cards" # "Deck of {} cards".format(len(self.cards)) # f"Deck of {len(self.cards)} cards" def __iter__(self): return iter(self.cards) ''' Once we learn GENERATORS, we can also write it like this: def __iter__(self): for card in self.cards: yield card ''' def reset(self): '''Reset the deck back to original init state''' self.cards = [Card(s, v) for v in Card.available_values for s in Card.available_suits] return self def count(self): return len(self.cards) def shuffle(self): if self.count() < 52: raise ValueError("Only full decks can be shuffled") return shuffle(self.cards) # !!! Forgot to return self.CARDS!! def _deal(self, number=1): if self.count() == 0: raise ValueError("All cards have been dealt") elif self.count() < number: # Use try/except here? print("Only {} cards left. Will deal all remaining cards.".format(self.count())) dealt = [self.cards.pop() for x in range(self.count())] return dealt[-number:] else: dealt = [self.cards.pop() for x in range(number)] # if len(dealt) == 1: # return dealt[0] # Returns the single Card instance # else: return dealt[-number:] # Returns list of Card instances def deal_card(self): return self._deal(1)[0] # Need trick to add [0] to return Card not []. Saves if/else logic in _deal. def deal_hand(self, number): return self._deal(number) my_deck = Deck() my_deck.shuffle() my_deck.reset() for card in my_deck: print(card) # d = Deck() # print(d) # print(d.cards) # d.shuffle() # print(d.cards) # d.deal_hand(5) # print(d.count()) # print(d.deal_card()) # c1 = Card('Diamonds', 4) # c2 = Card('Hearts', 5) # # print(c1) # print(c2.value) # # deck1 = Deck() # print(deck1) # # print(deck1.cards[12].suit) # Colt's solution just has deck[12].suit # # # print(deck1.count()) # print(len(deck1.cards)) # print(len(deck1)) # print(deck1.deal_hand(40)) # print(deck1.count()) # print(deck1.deal_hand(10)) # print(deck1.count()) # print(deck1.deal_card()) # print(deck1.count()) # print(deck1.deal_hand(2)) # print(deck1.count()) ''' Why not write the entire game in just one class? Great question! Technically, you could write all programming logic for a massive game or app inside of a single class (or not even using a class at all). So on one level, it's really just a nice way of organizing things into logical containers. More specifically to the Card class...I know right now you could represent all the information in a card with a simple dictionary: {"value": "A", "suit": "hearts"} But by making it into a separate class, we could add way more functionality. For example, what if we actually wanted each card to print out it's full name rather than just "Q", it should print "Queen of Hearts". What if we wanted to add in functionality to compare cards to each other like: card1 > card2 We could also add in error checking so that cards could only be created with valid suits and values. Lastly, we can reuse the card class in any other card game we created. So at the end of the day, you 100% can get away without using a Card class. All of OOP is just a nice way of organizing your code. It is never required to do anything, but it often can help make your code more readable and logical. ''' ''' Colt's SOLUTION: from random import shuffle # Each instance of Card should have a suit ("Hearts", "Diamonds", "Clubs", or "Spades"). # Each instance of Card should have a value ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"). # Card 's __repr__ method should display the card's value and suit (e.g. "A of Clubs", "J of Diamonds", etc.) class Card: def __init__(self, value, suit): self.value = value self.suit = suit def __repr__(self): # return "{} of {}".format(self.value, self.suit) return f"{self.value} of {self.suit}" # Each instance of Deck should have a cards attribute with all 52 possible instances of Card . # Deck should have an instance method called count which returns a count of how many cards remain in the deck. # Deck 's __repr__ method should display information on how many cards are in the deck (e.g. "Deck of 52 cards", "Deck of 12 cards", etc.) # Deck should have an instance method called _deal which accepts a number and removes at most that many cards from the deck (it may need to remove fewer if you request more cards than are currently in the deck!). If there are no cards left, this method should return a ValueError with the message "All cards have been dealt". # Deck should have an instance method called shuffle which will shuffle a full deck of cards. If there are cards missing from the deck, this method should return a ValueError with the message "Only full decks can be shuffled". # Deck should have an instance method called deal_card which uses the _deal method to deal a single card from the deck. # Deck should have an instance method called deal_hand which accepts a number and uses the _deal method to deal a list of cards from the deck. class Deck: def __init__(self): suits = ["Hearts", "Diamonds", "Clubs", "Spades"] values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K'] self.cards = [Card(value, suit) for suit in suits for value in values] def __repr__(self): return f"Deck of {self.count()} cards" def count(self): return len(self.cards) def _deal(self, num): count = self.count() actual = min([count,num]) if count == 0: raise ValueError("All cards have been dealt") cards = self.cards[-actual:] self.cards = self.cards[:-actual] return cards def deal_card(self): return self._deal(1)[0] def deal_hand(self, hand_size): return self._deal(hand_size) def shuffle(self): if self.count() < 52: raise ValueError("Only full decks can be shuffled") shuffle(self.cards) return self d = Deck() d.shuffle() card = d.deal_card() print(card) hand = d.deal_hand(50) card2 = d.deal_card() print(card2) print(d.cards) card2 = d.deal_card() # print(d.cards) '''
c68446d2fa042a3c279654f3937c16d632bf2420
gaylonalfano/Python-3-Bootcamp
/decorators_logging_wraps_metadata.py
2,667
4.40625
4
""" Typical syntax: def my_decorator(fn): def wrapper(*args, **kwargs): # do stuff with fn(*args, **kwargs) pass return wrapper Another tutorial example: https://www.youtube.com/watch?v=swU3c34d2NQ from functools import wraps import logging logging.basicConfig(filename='example.log', level=logging.INFO) def logger(func): @wraps(func) def log_func(*args): logging.info(f"Running {func.__name__} with arguments {args}") print(func(*args)) return log_func @logger # With Decorator def add(x, y): return x+y @logger # With Decorator def sub(x, y): return x-y # WITH DECORATOR??? Not sure with add since it's built-in... add(3, 3) add(4, 5) sub(10, 5) sub(20, 10) # WITHOUT DECORATOR: add_logger = logger(add) sub_logger = logger(sub) add_logger(3, 3) # 6 add_logger(4, 5) # 9 sub_logger(10, 5) # 5 sub_logger(20, 10) # 10 # **NEXT** Open the file example.log to see log results """ # USING WRAPS TO PRESERVE METADATA - LOGGING FUNCTION DATA # def log_function_data(fn): # def wrapper(*args, **kwargs): # """I'm a WRAPPER function""" # This is the doc string __doc__ # print(f"You are about to call {fn.__name__}") # print(f"Here's the documentation: {fn.__doc__}") # return fn(*args, **kwargs) # return wrapper # # @log_function_data # def add(x,y): # """Adds two numbers together.""" # return x+y # # print(add(10, 30)) # PROBLEM WITH ADD FUNCTION! # print(add.__doc__) # ALL referring to WRAPPER instead! NOT GOOD! # print(add.__name__) # help(add) ''' SOLUTION - Module called functools with WRAPS FUNCTION! wraps is simply a function we use to wrap around our wrapper function. It ensures that the metadata of the functions that get decorated are not lost by the decorator. So, for example, if you decorate @ add or len, you won't lose the original metadata for those functions. from functools import wraps # wraps preserves a function's metadata # when it is decorated! def my_decorator(fn): @wraps(fn) def wrapper(*args, **kwargs): # do some stuff with fn(*args, **kwargs) pass return wrapper ''' from functools import wraps def log_function_data(fn): @wraps(fn) def wrapper(*args, **kwargs): """I'm a WRAPPER function""" # This is the docstring __doc__ print(f"You are about to call {fn.__name__}") print(f"Here's the documentation: {fn.__doc__}") return fn(*args, **kwargs) return wrapper @log_function_data def add(x,y): """Adds two numbers together.""" return x+y print(add(10, 30)) print(add.__doc__) print(add.__name__) help(add)
0fa247aef355f85a8a00d44357933f418038c91d
gaylonalfano/Python-3-Bootcamp
/debugging_pdb.py
1,790
4.1875
4
''' Python Debugger (pdb) -- To set breakpoints in our code we can use pdb by inserting this line: def function(params): import pdb; pdb.set_trace() - Usually added/imported like this inside a function *Rest of code* Usually placed right before something starts breaking. Allows you to see a preview of what happens before/after. Pdb Commands: l (list) n (next line) a all values p (print) c (continue - finishes debugging by running the rest of the code) NOTE - If you have parameters/variable names that are any of these above COMMANDS, then you need to type: "p [variable name]" to print the value of that var. Ex. p c # ''' # import pdb # # # first = 'First' # second = 'Second' # pdb.set_trace() # result = first + second # third = 'Third' # result += third # print(result) # def add_numbers(a, b, c, d): # import pdb; pdb.set_trace() # # return a + b + c + d # # add_numbers(1, 2, 3, 4) # DIVIDE() - two params num1, num2. If you don't pass the correct amount of args # it should say "Please provided two integers or floats". If num2 == 0, should # raise a ZeroDivisionError, so return string "Please do not divide by zero" def divide(num1, num2): try: return num1/num2 except TypeError: print("Please provide two integers or floats") except ZeroDivisionError: print("Please do not divide by zero") # def divide2(num1): # import pdb; pdb.set_trace() # if type(num1) != int or type(num1) != float: # raise TypeError("Please provide two integers or floats") # # elif num2 == 0: # # raise ZeroDivisionError("Please do not divide by zero") # else: # print(num1) # divide(4, 2) # divide([], "1") # divide(1, 0) # divide2('1', '2') # divide2(4, '1') # divide2([], 0) divide2(5)
1f60486620945a344e4de43c3644a16ce1886b49
gaylonalfano/Python-3-Bootcamp
/say_hi.py
945
3.9375
4
''' Here's what happens you import something: 1. Tries to find the module (if it doesn't find it, it throws an error). 2. But if found, it runs the code inside of the module being imported So, in the example with say_hi and say_sup, when you import say_sup into the say_hi file, it will run the code in the say_sup module FIRST, which has a say_sup() function call. If you want to prevent this code from running, then here's the trick to ignore code on import: if __name__ == "__main__": # this code will only run # if the file is the main file! Ex. Modify the say_sup.py file and add this code to call the function: if __name__ == "__main__": say_sup() ''' from say_sup import say_sup def say_hi(): print(f"Hi! My __name__ is {__name__}") say_hi() say_sup() # Get 3 outputs IF you don't add if __name__ == "__main__" in say_sup.py # Sup! My __name__ is say_sup # Hi! My __name__ is __main__ # Sup! My __name__ is say_sup
9c309fa1bc6df7bf3d6e6b7ed047df45eb670316
gaylonalfano/Python-3-Bootcamp
/sorted.py
1,583
4.5625
5
''' sorted - Returns a new sorted LIST from the items in iterable (tuple, list, dict, str, etc.) You can also pass it a reverse=True argument. Key difference between sorted and .sort() is that .sort() is a list-only method and returns the sorted list in-place. sorted() accepts any type of iterable. Good for sorted on a key in dictionaries, etc. ''' more_numbers = [6, 1, 8, 2] sorted(more_numbers) # [1, 2, 6, 8] print(more_numbers) print(sorted(more_numbers, reverse=True)) sorted((2, 1, 45, 23, 99)) users = [ {'username': 'samuel', 'tweets': ['I love cake', 'I love pie']}, {'username': 'katie', 'tweets': ["I love my cat"], "color": "purple"}, {'username': 'jeff', 'tweets': []}, {'username': 'bob123', 'tweets': [], "num": 10, "color": "green"}, {'username': 'doggo_luvr', 'tweets': ["dogs are the best"]}, {'username': 'guitar_gal', 'tweets': []} ] # sorted(users) # Error message. Need to specify on what you want to sort on print(sorted(users, key=len)) # default is ascending print(sorted(users, key=lambda user: user['username'])) # 'bob123', 'doggo_luvr', etc. # Sort based off of who has the most tweets print(sorted(users, key=lambda user: len(user['tweets']), reverse=True)) # Ascending default. 0 tweets > 2 tweets # List of songs w/ playcount. How to sort based on playcount? songs = [ {'title': 'happy birthday', 'playcount': 1}, {'title': 'Survive', 'playcount': 6}, {'title': 'YMCA', 'playcount': 99}, {'title': 'Toxic', 'playcount': 31} ] print(sorted(songs, key=lambda song: song['playcount'], reverse=True))
f6c7ea3bf3080757bd268ee0b701e6c29c0d584f
gaylonalfano/Python-3-Bootcamp
/interleaving_strings_zip_join.py
686
4.3125
4
''' Write a function interleave() that accepts two strings. It should return a new string containing the two strings interwoven or zipped together. For example: interleave('hi', 'ha') # 'hhia' interleave('aaa', 'zzz') # 'azazaz' interleave('lzr', 'iad') # 'lizard' ''' def interleave(str1, str2): return ''.join( map( lambda i: i[0] + i[1], zip(str1, str2) ) ) def interleave(str1, str2): return ''.join(map(lambda i: i[0]+i[1], zip(str1, str2))) # Instructor's code: def interleave2(str1, str2): return ''.join(''.join(x) for x in (zip(str1, str2))) print(interleave('aaa', 'zzz')) print(interleave('lzr', 'iad'))
e02c57c26c880e076aae5b89ad58ebc5c774b541
gaylonalfano/Python-3-Bootcamp
/any_all_genexp_sysgetsize.py
2,594
4.0625
4
''' all - Return True if all elements of the iterable are truthy (or if the iterable is empty) ''' all([0, 1, 2, 3,]) # False all([char for char in 'eio' if char in 'aeiou']) # True all([num for num in [4, 2, -1, 10, 6, 8] if num % 2 == 0]) # False # Do all first letters start with 'c'? people = ['Charlie', 'Casey', 'Cody', 'Carly', 'Cristina'] print(all(name for name in people if name[0].lower() == 'c')) # True # Alternative syntax... pretty neat! # Just the simple list comprehension returns a list of True or False values # [name[0] == 'C' for name in people] # [True, True, True, True, True] print(all(name[0] == 'C' for name in people)) nums = [2, 60, 26, 18] all(num % 2 == 0 for num in nums) # True ''' any - Returns True if ANY element of the iterable is truthy. If the iterable is empty, returns False. ''' any([0, 1, 2, 3, 4]) # True any([val for val in [1, 2, 3] if val > 2]) # True any([val for val in [1, 2, 3] if val > 5]) # False any([num % 2 == 1 for num in nums]) # False # Could also write it like this: # for person in people: # if person[0] != 'C': # return False.... ''' GENERATOR EXPRESSIONS - "Basically, use a generator expresssion if all you're doing is iterating ONCE. If you want to store and use the generated results, then you're probably better off with a list comprehension." See stackoverflow "Generator Expressions vs. List Comprehension" ''' print((x*2 for x in range(256))) # Returns <generator object> print([x*2 for x in range(256)]) # List Comp # Example to show memory size between genexpr and listcomp import sys list_comp = sys.getsizeof([x * 10 for x in range(1000)]) gen_expr = sys.getsizeof(x * 10 for x in range(1000)) print("To do the same thing, it takes...") print(f"List comprehension: {list_comp} bytes") # 9024 bytes print(f"Generator expression: {gen_expr} bytes") # 88 bytes!!!! # IS_ALL_STRINGS() - accepts single iterable and returns True if it contains ONLY strings # isinstance(1, str) = False # isinstance('stuff', str) # True # isinstance(1, int) # True def is_all_strings(l): return all(isinstance(i, str) == True for i in l) # Instructor's gen expr using type(i) == str def is_all_strings2(lst): return all(type(l) == str for l in lst) # # Instructor's list comp: # def is_all_strings(lst): # return all([type(l) == str for l in lst]) print(is_all_strings(['a', 'b', 'c', 4])) # False print(is_all_strings(['', 'gaylon', 'lkjlkj', '33333'])) # True print(is_all_strings2(['a', 'b', 'c', 4])) # False print(is_all_strings2(['', 'gaylon', 'lkjlkj', '33333'])) # True
a5668f587fe9b9b26b70afd0e7bf97bc317c35b3
gaylonalfano/Python-3-Bootcamp
/polymorphism_OOP.py
1,806
4.3125
4
''' POLYMORPHISM - A key principle in OOP is the idea of polymorphism - an object can take on many (poly) forms (morph). Here are two important practical applications: 1. Polymorphism & Inheritance - The same class method works in a similar way for different classes Cat.speak() # meow Dog.speak() # woof Human.speak() # Yo A common implementation of this is to have a method in a base (or parent) class that is overridden by a subclass. This is called METHOD OVERRIDING. If other people on a team want to write their own subclass methods, this is useful. class Animal: def speak(self): raise NotImplementedError("Subclass needs to implement this method") class Dog(Animal): def speak(self): return "woof" class Cat(Animal): def speak(self): return "meow" class Fish(Animal): pass d = Dog() print(d.speak()) f = Fish() print(f.speak()) # NotImplementedError: Subclass needs to implement this method - need a speak() 2. Special Methods (__dunder__ methods, etc) - The same operation works for different kinds of objects: sample_list = [1, 2, 3] sample_tuple = (1, 2, 3) sample_string = "awesome" len(sample_list) len(sample_tuple) len(sample_string) 8 + 2 = 10 "8" + "2" = "82" Python classes have special (aka "magic") methods that are dunders. These methods with special names that give instructions to Python for how to deal with objects. ''' class Animal: def speak(self): raise NotImplementedError("Subclass needs to implement this method") class Dog(Animal): def speak(self): return "woof" class Cat(Animal): def speak(self): return "meow" class Fish(Animal): pass d = Dog() print(d.speak()) f = Fish() print(f.speak()) # NotImplementedError: Subclass needs to implement this method - need a speak()
01f789624331400198854db00783dd92238b33ec
gaylonalfano/Python-3-Bootcamp
/RockPaperScissors.py
3,615
4.375
4
# # Now adding a computer player (random pics) # from random import randint # # player = input('Player: Enter rock, paper, or scissors: ').lower() # computer = randint(0, 2) # if computer == 0: # computer = 'rock' # elif computer == 1: # computer = 'paper' # else: # computer = 'scissors' # # print("...rock...\n...paper...\n...scissors...") # print('SHOOT!') # # if player == computer: # print(f'It\'s a tie! Player chose {player}. Computer chose {computer}. Play again!') # elif player == 'rock' and computer == 'scissors': # print(f"Player chose {player}. Computer chose {computer}. Player wins!") # elif player == 'paper' and computer == 'rock': # print(f"Player chose {player}. Computer chose {computer}. Player wins!") # elif player == 'scissors' and computer == 'paper': # print(f"Player chose {player}. Computer chose {computer}. Player wins!") # else: # print(f"Player chose {player}. Computer chose {computer}. Computer wins!") # Updating game to include a loop that exits once someone has won 2 of 3, or 3 or 5, etc. from random import randint # Wrapping whole program into a big while loop start_game = True while start_game: player_wins = 0 computer_wins = 0 winning_score = 2 # Can change this to do your 2/3 or 3/5, etc. while player_wins < winning_score and computer_wins < winning_score: # for i in range(3): **Don't need this FOR loop if you use WHILE print(f'Player: {player_wins} Computer: {computer_wins}') player = input("Enter 'rock', 'paper', or 'scissors': ").lower() # Helps with data entry validation if player == 'quit' or player == 'q': # Adding a break so user can quit out break computer = randint(0, 2) if computer == 0: computer = 'rock' elif computer == 1: computer = 'paper' else: computer = 'scissors' print("...rock...\n...paper...\n...scissors...\nSHOOT!") if player == computer: print(f'It\'s a tie! Player chose {player}. Computer chose {computer}. Play again!') elif player == 'rock' and computer == 'scissors': print(f"Player chose {player}. Computer chose {computer}. Player wins!") player_wins += 1 elif player == 'paper' and computer == 'rock': print(f"Player chose {player}. Computer chose {computer}. Player wins!") player_wins += 1 elif player == 'scissors' and computer == 'paper': print(f"Player chose {player}. Computer chose {computer}. Player wins!") player_wins += 1 else: print(f"Player chose {player}. Computer chose {computer}. Computer wins!") computer_wins += 1 if player_wins > computer_wins: print(f'Congrats, you won! Final score: Player {player_wins} vs. Computer {computer_wins}') play_again = input('Want to play again? (y/n) ') if play_again == 'n': print('Thanks for playing!') start_game = False elif player_wins == computer_wins: # only happens if we quit when it's a tie print('It\'s a tie! Well done to both contestants.') play_again = input('Want to play again? (y/n) ') if play_again == 'n': print('Thanks for playing!') start_game = False else: print(f'Oh no, you lost! Final score: Player {player_wins} vs. Computer {computer_wins}') play_again = input('Want to play again? (y/n) ') if play_again == 'n': print('Thanks for playing!') start_game = False
3b95bdfc9e342ab8269671b0d7410d311fdcba43
gaylonalfano/Python-3-Bootcamp
/try_except.py
3,737
4.5
4
''' In Python, it is STRONGLY encouraged to use try/except blocks to catch exceptions when we can do something about them. Let's see what that looks like. Most basic form: try: foobar except NameError as err: print(err) ''' ''' WHEN TO USE TRY/EXCEPT VS. RAISE: You would want to use try-except when you want to try running a code that may or may not cause an error, and you want to catch that error in the except block and add some additional logic that needs to get run if the error does get triggered. In this exercise, we are just returning messages to the user which explain what went wrong and that only numbers can be used/no zero for division. Really important difference is that if you don't raise an error within try-except, the code under the blocks can continue running, the script doesn't necessarily need to stop like when using raise alone. It's also considered a cleaner approach to try executing a potentially error-prone code and catching those errors if they happen. raise can be used with try-except, where you can raise a custom error for the user, for example. It can also be used alone for your own errors, when you want to check a value of something and if it isn't what you except, you can just directly throw an error to the user and stop the script. So, try is used to execute code that might raise an Exception that you're expecting. Instead of stopping the program, you can catch the exception and deal with it in your code. Also, finally can be really useful in the combination, see here. The important point is that it doesn't have to stop the execution, the code below try-except can keep running - you can set some values in the except block which will then make the code below works differently, and adapt to the error that got triggered in the try block. Read more here: https://stackoverflow.com/questions/40182944/difference-between-raise-try-and-assert Please let me know if you have any more questions. Regards, Zarko ''' # try: # foobar # except: # print("PROBLEM!") # print("after the try") # def get(d, key): # try: # return d[key] # except KeyError: # return (f'{key} is not in {d.keys()}') # # # # d = {"name": "Ricky", 'address': 'shanghai', 'color': 'purple'} # #d["city"] # KeyError if you don't add to dict # print(get(d, 'name')) # Ricky # print(get(d, 'city')) # None ''' Common use for when you are accepting user input. try: except: else: The else block is only executed if the code in the try doesn't raise an exception. finally: Runs no matter what. Good for closing database connections or a file. ''' # while True: # try: # num = int(input('please enter a number: ')) # 10 # except ValueError: # print('That\'s not a number!') # Runs if a problem # else: # print("Good job, you entered a number!") # break # finally: # print("Runs no matter what!") # Problem or no problem it will run! # # print("Rest of game logic runs!") # try: # num = int(input('please enter a number: ')) # 10 # except: # print('That\'s not a number!') # Runs if a problem # else: # print("I'm in the ELSE!") # 10 # finally: # print("Runs no matter what!") # Problem or no problem it will run! def divide(a, b): try: result = a/b except ZeroDivisionError: # Can combined multiple Errors using a TUPLE (ZeroDivisionError, TypeError) as err: print('do not divide by zero please') except TypeError as err: # can add 'as err' print(f'{a} and {b} must be ints or floats') print(err) else: print(f"{a} divided by {b} is {result}") print(divide(1, 2)) #print(divide(1, 'a')) #print(divide(1, 0))
79c42425fad9a2049934a8208d0b8cf9ca9b0a08
gaylonalfano/Python-3-Bootcamp
/custom_for_loop_iterator_iterable.py
1,648
4.4375
4
# Custom For Loop ''' ITERATOR - An object that can be iterated upon. An object which returns data, ONE element at a time when next() is called on it. Think of it as anything we can run a for loop on, but behind the scenes there's a method called next() working. ITERABLE - An object which will return an ITERATOR when iter() is called on it. IMPORTANT: A list is also just an iterable. The list is actually never directly looped over. What actually happens is the for loop calls iter("HELLO"), which returns the iterator that is then the loop will call next() on that iterator over and over again until it hits the end! UNDERSTAND THE ITER() AND NEXT() METHODS ITER() - Returns an iterator object. NEXT() - When next() is called on an iterator, the iterator returns the next ITEM. It keeps doing so until it raises a StopIteration error. It's actually using a try/except block until it reaches the end and raises the StopIteration error. ''' def my_for(iterable, func): iterator = iter(iterable) while True: # Need to add in try/except block to stop error from displaying to user try: # Would be nice to add some functionality to it (sum, mul, etc.) other than just print # print(next(iterator)) i = next(iterator) func(i) except StopIteration: # print("End of loop") break # else: Another syntax is to do the func() call in the else statement # func(i) def square(x): print(x**2) # If you only use RETURN, then it won't PRINT #my_for("hello") my_for([1, 2, 3, 4], square) # 1, 4, 9, 16 my_for('lol', print)
1c99eb986dc4930076e17100b281bcc2f21c2c8b
gaylonalfano/Python-3-Bootcamp
/generator_expressions.py
778
3.796875
4
# g = (yield num for num in range(1, 10)) WRONG! DON'T NEED TO ADD YIELD # g = (num for num in range(1,10)) # print(g) # <generator object <genexpr> at 0x104005780> GENERATOR EXPRESSION # print(next(g)) # # def nums(): # for num in range(1,10): # yield num # # f = nums() # print(f) # <generator object nums at 0x1015d6bf8> GENERATOR FUNCTION # print(next(f)) # # print(sum(num for num in range(1,10))) # Time how long it takes for generators vs. lists import time gen_start_time = time.time() print(sum(n for n in range(100000000))) gen_time = time.time() - gen_start_time list_start_time = time.time() print(sum([n for n in range(100000000)])) list_time = time.time() - list_start_time print(f"Gen took: {gen_time}") print(f"List took: {list_time}")
2e9cde6ddaf45706eb646ec7404d22a851430e3f
gaylonalfano/Python-3-Bootcamp
/dundermethods_namemangling.py
1,096
4.5
4
# _name - Simply a convention. Supposed to be "private" and not used outside of the class # __name - Name Mangling. Python will mangle/change the name of that attribute. Ex. p._Person__lol to find it # Used for INHERITANCE. Python mangles the name and puts the class name in there for inheritance purposes. # Think of hierarchy (Person > [Teacher, Cop, Coach, Student, etc.]). Teacher could also have self._Teacher__lol # __name__ - Don't go around making your own __dunder__ methods class Person: def __init__(self): self._secret = 'hi!' self.name = 'Tony' self.__msg = "I like turtles" self.__lol = "hahahaha" # In other programming languages to make private do: # private self._secret = "hi!" # def doorman(self, guess): # if guess == self._secret: # let them in p = Person() print(p.name) print(p._secret) # print(p.__msg) # AttributeError: 'Person' object has no attribute '__msg' print(dir(p)) # list ['_Person__msg', '_Person_lol', '__class__', '__delattr__', ...] print(p._Person__msg) print(p._Person__lol)
e25847f26dc7c05266590c808073ab6b9828705a
SamiFatmi/python-programming-SAMI-FATMI
/Labs/Labb-3/shapes.py
38,556
4.53125
5
import math import matplotlib.pyplot as plt class Shape: """ This class will be parent to the classes 'Rectangle' and 'Circle', it will contain the coordinates of the 2D shapes """ def __init__ (self,x:float,y:float)->None: self.x= x self.y= y @property def x(self): return self._x @property def y(self): return self._y @x.setter def x(self,value)->None: if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("x coordinate must be an int or a float") self._x = value @y.setter def y(self,value:float)->None: if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("y coordinate must be an int or a float") self._y = value def move(self,xdistance:float,ydistance:float)->None: """ Moving the Shape Input from the user : X and Y translation distances function will move the shape by adding the distances to the X and Y coordinates """ if not all([isinstance(i,(int,float)) for i in [xdistance,ydistance]]) or not all([ not isinstance(i,bool) for i in [xdistance,ydistance]]): #https://stackoverflow.com/questions/23986266/is-there-a-better-way-of-checking-multiple-variables-are-a-single-type-in-python raise TypeError("X and Y distances should be a number") self._x+=xdistance self._y+=ydistance def move_to(self,x:float,y:float)->None: """ Moving the shape to an exact point Input from the user : X and Y coordinates of the point function will move the shape by changing the center of the shape's coordinates to the coordinates given by the user """ if not all([isinstance(i,(int,float)) for i in [x,y]]) or not all([not isinstance(i,bool) for i in [x,y]]): raise TypeError("X and Y coordinates should be a number") self._x=x self._y=y def __repr__ (self)->str: return (f"Type: 2D Shape\nCenter : ({self.x},{self.y})") class Circle(Shape): """ This is a child class of Shape, it takes the X and Y coordinates from Shape This class will contain all the methods for plotting, area and circumference counting, moving, scaling or changing size and comparing to other circles. """ def __init__(self,x:float,y:float,radius:float)->None: super().__init__(x,y) self.radius=radius @property def radius(self): return self._radius @radius.setter def radius(self,value:float)->None: if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("Radius must be an int or a float") if value==0: raise ValueError("Radius can't be 0 ") if value<0: raise ValueError("Radius can't be negative ") self._radius = value def area(self)->float: """ Calculating and returning the area of the circle """ return math.pi*(self._radius**2) def perimeter(self)->float: """ Calculating and returning the circumference of the circle """ return 2*math.pi*self._radius def move(self,xdistance:float,ydistance:float)->'Circle': """ Moving the circle Input from the user : X and Y translation distances function will move the circle by adding the distances to the X and Y coordinates """ if not all([isinstance(i,(int,float)) for i in [xdistance,ydistance]]) or not all([not isinstance(i,bool) for i in [xdistance,ydistance]]): #https://stackoverflow.com/questions/23986266/is-there-a-better-way-of-checking-multiple-variables-are-a-single-type-in-python raise TypeError("X and Y distances should be a number") self._x+=xdistance self._y+=ydistance return Circle(self._x,self._y,self._radius) def move_to(self,x:float,y:float)->'Circle': """ Moving the circle to an exact point Input from the user : X and Y coordinates of the point function will move the circle by changing the center of the circle's coordinates to the coordinates given by the user """ if not all([isinstance(i,(int,float)) for i in [x,y]]) or not all([not isinstance(i,bool) for i in [x,y]]): #https://stackoverflow.com/questions/23986266/is-there-a-better-way-of-checking-multiple-variables-are-a-single-type-in-python raise TypeError("X and Y distances should be a number") self._x=x self._y=y return Circle(self._x,self._y,self._radius) def scale(self,value:float)->'Circle': """ Scaling the circle input from the user : scaling value The method scales the circle by multiplying the radius by the scaling value """ if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("Value must be an int or a float") if value==0: raise ValueError("Value can't be 0 ") if value<0: raise ValueError("Value can't be negative ") self._radius *= value return Circle(self._x,self._y,self._radius) def change_radius(self,value:float)->'Circle': """ Changing the circle's radius input from the user : new radius The method changes the circle's radius to the new value """ if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("Value must be an int or a float") if value==0: raise ValueError("Value can't be 0 ") if value<0: raise ValueError("Value can't be negative ") self._radius = value return Circle(self._x,self._y,value) def contain(self,x:float,y:float)->bool: """Check if a point is within a circle by comparing the distance from the point to the center of the circle and the radius point coordinates should be given by the user""" if not all([isinstance(i,(int,float)) for i in [x,y]]) or not all([not isinstance(i,bool) for i in [x,y]]): raise TypeError("Point coordinates should be numbers") if pow(pow(x-self._x,2)+pow(y-self._y,2),0.5)<=self._radius : return True else : return False def __eq__(self,other:'Circle')->bool: """ Compairing 2 circles and checking if their radius is the same if they have the same radius then they are equal""" if type(other) != type(self): raise TypeError("Can't compare a circle with a non-circle") return True if self._radius == other._radius else False def plot(self)->None: """ Plotting 360 degrees of a circle """ X = [ self._x+ self._radius*math.cos(math.radians(i)) for i in range(1,361)] Y = [ self._y+ self._radius*math.sin(math.radians(i)) for i in range(1,361)] plt.plot(X,Y) def __repr__(self)->str: return (f"Type: Circle\nCenter : ({self.x},{self.y})\nRadius : {self.radius}") class Rectangle(Shape): """ This is a child class of Shape, it takes the X and Y coordinates from Shape This class will contain all the methods for plotting, area and circumference counting, moving, scaling or changing size and comparing to other rectangles. """ def __init__(self,x:float,y:float,side1:float,side2:float,angle:float=0)->None: super().__init__(x,y) self.side1=side1 self.side2=side2 self.angle=angle @property def side1(self): return self._side1 @property def side2(self): return self._side2 @property def angle(self): return self._angle @side1.setter def side1(self,value:float)->None: if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("Height must be an int or a") if value==0: raise ValueError("Height can't be 0 ") if value<0: raise ValueError("Height can't be negative ") self._side1 = value @side2.setter def side2(self,value:float)->None: if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("Height must be an int or a float") if value==0: raise ValueError("Height can't be 0 ") if value<0: raise ValueError("Height can't be negative ") self._side2 = value @angle.setter def angle(self,value:float)->None: if not isinstance(value,(int,float)) : raise TypeError("Angle must be an int or a float ") self._angle = value def move(self,xdistance:float,ydistance:float)->'Rectangle': """ Moving the rectangle Input from the user : X and Y translation distances function will move the rectangle by adding the distances to the X and Y coordinates """ if not all([isinstance(i,(int,float)) for i in [xdistance,ydistance]]) or not all([not isinstance(i,bool) for i in [xdistance,ydistance]]): #https://stackoverflow.com/questions/23986266/is-there-a-better-way-of-checking-multiple-variables-are-a-single-type-in-python raise TypeError("X and Y distances should be a number") self._x+=xdistance self._y+=ydistance return Rectangle(self._x,self._y,self._side1,self._side2) def move_to(self,new_x:float,new_y:float)->'Rectangle': """ Moving the rectangle to an exact point Input from the user : X and Y coordinates of the point function will move the rectangle by changing the center of the rectangle's coordinates to the coordinates given by the user """ if not all([isinstance(i,(int,float)) for i in [new_x,new_y]]) or not all([not isinstance(i,bool) for i in [new_x,new_y]]): #https://stackoverflow.com/questions/23986266/is-there-a-better-way-of-checking-multiple-variables-are-a-single-type-in-python raise TypeError("X and Y distances should be a number") self._x=new_x self._y=new_y return Rectangle(new_x,new_y,self._side1,self._side2) def area(self)->float: """ Calculating and returning the area of the rectangle """ return self._side1*self._side2 def perimeter(self)->float: """ Calculating and returning the circumference of the rectangle """ return 2*self._side1 + 2*self._side2 def scale(self,value:float)->'Rectangle': """ Scaling the rectangle input from the user : scaling value The method scales the rectangle by multiplying the width and height by the scaling value """ if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("Scaling Value should be a number") if value == 0 : raise ValueError("Scaling value can't be 0") if value<0 : raise ValueError("Scaling Value can't be negative") self._side1*=value self._side2*=value return Rectangle(self._x,self._y,self._side1,self._side2,self._angle) def change_size(self,new_side1:float,new_side2:float)->'Rectangle': """ Changing the rectangle's size input from the user : new radius The method changes the rectangle's width and height to the new values """ if not all([isinstance(i,(int,float)) for i in [new_side1,new_side2]]) or not all([not isinstance(i,bool) for i in[new_side1,new_side2]]): raise TypeError("The new length and width must be numbers") if new_side1==0 or new_side2==0: raise ValueError("Length and width can't be 0") if new_side1<0 or new_side2<0: raise ValueError("Length and width can't be negative") self._side1=new_side1 self._side2=new_side2 return Rectangle(self._x,self._y,self._side1,self._side2,self._angle) def rotate(self,rotation_angle:float)->'Rectangle': """ Rotating the rectangle input from the user : rotation angle Method rotates the rectangle by adding the rotation angle value to the actual angle value""" if not isinstance(rotation_angle,(int,float)) or isinstance(rotation_angle,bool): raise TypeError("Rotation angle should be an int or a float") self._angle+=rotation_angle return Rectangle(self._x,self._y,self._side1,self._side2,self._angle) def make_horizontal(self)->'Rectangle': """ Making the rectangle horizontal by checking which side is longer and setting the angle to 0 or 90 depending on the cases""" if self._side1>=self._side2: self._angle = 0 return Rectangle(self._x,self._y,self._side1,self._side2,0) else: self._angle = 90 return Rectangle(self._x,self._y,self._side1,self._side2,90) def make_vertical(self)->'Rectangle': """ Making the rectangle vertical by checking which side is longer and setting the angle to 0 or 90 depending on the cases""" if self._side1>=self._side2: self._angle = 90 return Rectangle(self._x,self._y,self._side1,self._side2,90) else: self._angle = 0 return Rectangle(self._x,self._y,self._side1,self._side2,0) def contains(self,x:float,y:float)->bool: """ Checking if a point is within our rectangle Input by the user is the point coordinates since the user can rotate the rectangle we can't only check if the point X coordinate is betwen center X +/- width and the same for Y coordinates. We will check the area of all the triangles that could be made including our point in this way: Let's say our rectangle is made of 4 points A,B,C,D Our point is called P then for the point P to be within ABCD, all these triangles: PAB ,PBC, PCD and PDA should have areas that add up to the area of the rectangle, if the areas of those triangles' sum is bigger than the area of the rectangle then our point P is outside the rectangle ABCD. """ if not all([isinstance(i,(int,float)) for i in [x,y]]) or not all([not isinstance(i,bool) for i in [x,y]]): raise TypeError("Point coordinates must be numbers") if self._angle == 0 : if self._x-self._side1/2 <= x <= self._x+self._side1/2 and self._y-self._side2/2 <= y <= self._y+self._side2/2: return True else: return False else : rec_corners=self.corners() point1=rec_corners[0] point2=rec_corners[1] point3=rec_corners[2] point4=rec_corners[3] triangle1_area= max(abs(point1[0]-point2[0]),abs(point1[0]-x),abs(x-point2[0]))*max(abs(point1[1]-point2[1]),abs(point1[1]-y),abs(y-point2[1])) - abs((point1[0]-point2[0])*(point1[1]-point2[1]))/2 - abs((point1[0]-x)*(point1[1]-y))/2 - abs((x-point2[0])*(y-point2[1]))/2 triangle2_area= max(abs(point3[0]-point2[0]),abs(point3[0]-x),abs(x-point2[0]))*max(abs(point3[1]-point2[1]),abs(point3[1]-y),abs(y-point2[1])) - abs((point3[0]-point2[0])*(point3[1]-point2[1]))/2 - abs((point3[0]-x)*(point3[1]-y))/2 - abs((x-point2[0])*(y-point2[1]))/2 triangle3_area= max(abs(point3[0]-point4[0]),abs(point3[0]-x),abs(x-point4[0]))*max(abs(point3[1]-point4[1]),abs(point3[1]-y),abs(y-point4[1])) - abs((point3[0]-point4[0])*(point3[1]-point4[1]))/2 - abs((point3[0]-x)*(point3[1]-y))/2 - abs((x-point4[0])*(y-point4[1]))/2 triangle4_area= max(abs(point1[0]-point4[0]),abs(point1[0]-x),abs(x-point4[0]))*max(abs(point1[1]-point4[1]),abs(point1[1]-y),abs(y-point4[1])) - abs((point1[0]-point4[0])*(point1[1]-point4[1]))/2 - abs((point1[0]-x)*(point1[1]-y))/2 - abs((x-point4[0])*(y-point4[1]))/2 if (triangle1_area+triangle2_area+triangle3_area+triangle4_area) - self.area() > 0.01: return False return True def __eq__(self,other:'Rectangle')->bool: """ Comparing 2 rectangles by checking if they have the same width and height since rectangles can be rotated, 2 rectangles having """ if type(other)!=type(self): raise TypeError("Can't compare a rectangle with a non rectangle") if (self._side1 == other._side1 and self._side2 == other._side2 ) or (self._side2 == other._side1 and self._side1 == other._side2 ) : return True else : return False @staticmethod def euc_distance(point1:list,point2:list)->float: return ((point1[0]-point2[0])**2+(point1[1]-point2[1])**2)**0.5 def corners (self)->list: """ Calculating the coordinates of the corners of the rectangle we will use the corners for plotting angle is taken into account in the calculation to make it possible to rotate the rectangle returning the 4 corners and the first corner at the end because we need 5 points to get 4 lines when plotting """ distance = pow(pow(self._side1/2,2)+pow(self._side2/2,2),0.5) inner_angle=math.acos(self._side1/(2*distance)) c1=[self._x + math.cos(inner_angle+math.radians(self.angle))*distance, self._y +math.sin(inner_angle+math.radians(self.angle))*distance] c2=[self._x + math.cos(math.pi - inner_angle +math.radians(self.angle))*distance,self._y + math.sin(math.pi - inner_angle +math.radians(self.angle))*distance] c3=[self._x + math.cos(math.pi + inner_angle+math.radians(self.angle))*distance,self._y + math.sin(math.pi + inner_angle+math.radians(self.angle))*distance] c4=[self._x + math.cos(math.tau - inner_angle+math.radians(self.angle))*distance,self._y +math.sin(math.tau - inner_angle+math.radians(self.angle))*distance] return [c1,c2,c3,c4,c1] def plot(self): """ plotting method, gets the corners coordinates and plots lines between points""" X_coordinates = [(self.corners())[i][0] for i in range(5)] Y_coordinates = [(self.corners())[i][1] for i in range(5)] plt.plot(X_coordinates,Y_coordinates) def __repr__(self)->str: """ description of the rectangle""" if self._side1!=self._side2: return (f"Type: Rectangle\nCenter : ({self.x},{self.y})\nWidth : {self.side1}\nHeight: {self.side2}") else: return (f"Type: Square\nCenter : ({self.x},{self.y})\nWidth : {self.side1}") # 3D shapes class Shape_3D: def __init__(self,x:float,y:float,z:float)->None: self.x=x self.y=y self.z=z @property def x(self)->float: return self._x @property def y(self)->float: return self._y @property def z(self)->float: return self._z @x.setter def x(self,value:float)->None: if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("Value should be a number") self._x = value @y.setter def y(self,value:float)->None: if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("Value should be a number") self._y = value @z.setter def z(self,value:float)->None: if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("Value should be a number") self._z = value def move(self,x:float,y:float,z:float)->None: """ Moving the 3D Shape Input from the user : X,Y and Z translation distances function will move the 3D shape by adding the distances to the X,Y and Z coordinates """ if not all([isinstance(i,(int,float)) for i in [x,y,z]]) or not all([not isinstance(x,bool) for i in [x,y,z]]): raise TypeError("Values should be numbers") self._x+=x self._y+=y self._z+=z def move_to(self,x:float,y:float,z:float): """ Moving the shape to an exact point Input from the user : X,Y and Z coordinates of the point function will move the shape by changing the center of the shape's coordinates to the coordinates given by the user """ if not all([isinstance(i,(int,float)) for i in [x,y,z]]) or not all([not isinstance(x,bool) for i in [x,y,z]]): raise TypeError("Values should be numbers") self._x=x self._y=y self._z=z def __repr__(self)->str: return (f"Type: 3D Shape\nCenter : ({self.x},{self.y},{self.z})") class Cube(Shape_3D): def __init__(self,x:float,y:float,z:float,side1:float)->None: super().__init__(x,y,z) self.side1=side1 @property def side1(self)->float: return self._side1 @side1.setter def side1(self,value:float)->None: if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("Dimension of side 1 should be a valid number") if value==0: raise ValueError("Dimension of side 1 can't be 0") if value<0: raise ValueError("Dimension of side 1 can't be negative") self._side1=value def volume(self)->float: """ Calculating and returning the volume of the cube """ return self.side1**3 def circumference_surface(self)->float: """ Calculating and returning the circumference surface of the cube """ return (self.side1**2)*6 def move(self,X:float,Y:float,Z:float)->'Cube': """ Moving the cube Input from the user : X,Y and Z translation distances function will move the cube by adding the distances to the X,Y and Z coordinates """ if not all([isinstance(i,(int,float)) for i in [X,Y,Z]]) or not all([not isinstance(i,bool) for i in [X,Y,Z]]): raise TypeError ("Distances must be valid numbers") self.x+=X self.y+=Y self.z+=Z return Cube(self.x,self.y,self.z,self.side1) def move_to(self,X:float,Y:float,Z:float)->'Cube': """ Moving the cube to an exact point Input from the user : X,Y and Z coordinates of the point function will move the cube by changing the center of the cube's coordinates to the coordinates given by the user """ if not all([isinstance(i,(int,float)) for i in [X,Y,Z]]) or not all([not isinstance(i,bool) for i in [X,Y,Z]]): raise TypeError ("Distances must be valid numbers") self.x=X self.y=Y self.z=Z return Cube(self.x,self.y,self.z,self.side1) def scale(self,scaling_value:float)->'Cube': """ Scaling the cube input from the user : scaling value The method scales the cube by multiplying the width,height and depth by the scaling value """ if not isinstance(scaling_value,(int,float)) or isinstance(scaling_value,bool): raise TypeError("Scaling value must be a valid number") if scaling_value == 0: raise ValueError("Scaling value can't be 0") if scaling_value < 0 : raise ValueError("Scaling value can't be negative") self.side1*=scaling_value return Cube(self.x,self.y,self.z,self.side1) def change_size(self,side_value:float)->'Cube': """ Changing the cube's size input from the user : new width The method changes the cubes's width to the new value """ if not isinstance(side_value,(int,float)) or isinstance(side_value,bool): raise TypeError("Side dimension must be a valid number") if side_value == 0: raise ValueError("Side dimension can't be 0") if side_value < 0 : raise ValueError("Side dimension can't be negative") self.side1=side_value return Cube(self.x,self.y,self.z,self.side1) def contains(self,X:float,Y:float,Z:float)->bool: """ Checking if the cube contains a point input is the point's coordinates we check if all the coordinates are between the center coordinate +/- the width/2 """ if not all([isinstance(i,(int,float)) for i in [X,Y,Z]]) or not all([not isinstance(i,bool) for i in [X,Y,Z]]): raise TypeError ("Point coordinates must be valid numbers") return True if (self.x-self.side1/2<=X<=self.x+self.side1/2 and self.y-self.side1/2<=Y<=self.y+self.side1/2 and self.z-self.side1/2<=Z<=self.z+self.side1/2) else False def __eq__(self, o: object) -> bool: """ comparing two cubes, if the cubes have the same width they are considered equal """ if type(self)!=type(o): raise TypeError("Can't compare a cube with a non-cube.") else: return True if (self.side1 == o.side1) else False @staticmethod def euc_distance(point1:list,point2:list)->float: return ((point1[0]-point2[0])**2+(point1[1]-point2[1])**2+(point1[2]-point2[2])**2)**0.5 def corners(self)->list: """ calculating the coordinates of the corners of our cube since we will not be rotating any 3D shape, coordinates are simply center coordinate +/- width/2 we return the points in such a way that would make the plotting not miss any side of the cube nor plot unnecessary lines the points' coordinates will be used while plotting""" c1=[self.x+self.side1/2,self.y+self.side1/2,self.z+self.side1/2] c2=[self.x+self.side1/2,self.y-self.side1/2,self.z+self.side1/2] c3=[self.x+self.side1/2,self.y-self.side1/2,self.z-self.side1/2] c4=[self.x+self.side1/2,self.y+self.side1/2,self.z-self.side1/2] c5=[self.x-self.side1/2,self.y+self.side1/2,self.z+self.side1/2] c6=[self.x-self.side1/2,self.y-self.side1/2,self.z+self.side1/2] c7=[self.x-self.side1/2,self.y-self.side1/2,self.z-self.side1/2] c8=[self.x-self.side1/2,self.y+self.side1/2,self.z-self.side1/2] return [c1,c2,c3,c4,c1,c5,c6,c2,c6,c7,c3,c7,c8,c4,c8,c5] def __repr__(self)->str: return (f"Type: Cube\nCenter : ({self.x},{self.y},{self.z})\nWidth : {self.side1}") class Rec_Cuboid(Cube): def __init__(self,x:float,y:float,z:float,side1:float,side2:float,side3:float)->None: super().__init__(x,y,z,side1) self.side2=side2 self.side3=side3 @property def side2(self)->float: return self._side2 @property def side3(self)->float: return self._side3 @side2.setter def side2(self,value:float)->None: if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("Dimension of side 2 should be a valid number") if value==0: raise ValueError("Dimension of side 2 can't be 0") if value<0: raise ValueError("Dimension of side 2 can't be negative") self._side2=value @side3.setter def side3(self,value:float)->None : if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("Dimension of side 3 should be a valid number") if value==0: raise ValueError("Dimension of side 3 can't be 0") if value<0: raise ValueError("Dimension of side 3 can't be negative") self._side3=value def volume(self)->float: """ Calculating and returning the volume of the rectangular cuboid """ return self.side1*self.side2*self.side3 def circumference_surface(self)->float: """ Calculating and returning the circumference surface of the rectangular cuboid """ return self.side1*self.side2*2 + self.side1*self.side3*2 + self.side2*self.side3*2 def move(self,X:float,Y:float,Z:float)->'Rec_Cuboid': """ Moving the rectangular cuboid Input from the user : X,Y and Z translation distances function will move the rectangular cuboid by adding the distances to the X,Y and Z coordinates """ if not all([isinstance(i,(int,float)) for i in [X,Y,Z]]) or not all([not isinstance(i,bool) for i in [X,Y,Z]]): raise TypeError ("Distances must be valid numbers") self.x+=X self.y+=Y self.z+=Z return Rec_Cuboid(self.x,self.y,self.z,self.side1,self.side2,self.side3) def move_to(self,X:float,Y:float,Z:float)->'Rec_Cuboid': """ Moving the rectangular cuboid to an exact point Input from the user : X,Y and Z coordinates of the point function will move the rectangular cuboid by changing the center of the rectangular cuboid's coordinates to the coordinates given by the user """ if not all([isinstance(i,(int,float)) for i in [X,Y,Z]]) or not all([not isinstance(i,bool) for i in [X,Y,Z]]): raise TypeEßrror ("Distances must be valid numbers") self.x=X self.y=Y self.z=Z return Rec_Cuboid(self.x,self.y,self.z,self.side1,self.side2,self.side3) def scale(self,scaling_value:float)->'Rec_Cuboid': """ Scaling the rectangular cuboid input from the user : scaling value The method scales the rectangular cuboid by multiplying the width, height and depth by the scaling value """ if not isinstance(scaling_value,(int,float)) or isinstance(scaling_value,bool): raise TypeError("Scaling value must be a valid number") if scaling_value == 0: raise ValueError("Scaling value can't be 0") if scaling_value < 0 : raise ValueError("Scaling value can't be negative") self.side1*=scaling_value self.side2*=scaling_value self.side3*=scaling_value return Rec_Cuboid(self.x,self.y,self.z,self.side1,self.side2,self.side3) def change_size(self,new_side1:float,new_side2:float,new_side3:float)->'Rec_Cuboid': """ Changing the rectangular cuboid's size input from the user : new width, height and depth The method changes the rectangular cuboid's width, height and depth to the new values """ if not all([isinstance(i,(int,float)) for i in [new_side1,new_side2,new_side3]]) or not all([ not isinstance(i,bool) for i in [new_side1,new_side2,new_side3]]): raise TypeError("New sides values must be valid numbers") if new_side1== 0 or new_side2 == 0 or new_side3 == 0: raise ValueError("New sides values can't be 0") if new_side1< 0 or new_side2 < 0 or new_side3 < 0 : raise ValueError("New sides values can't be negative") self.side1=new_side1 self.side2=new_side2 self.side3=new_side3 return Rec_Cuboid(self.x,self.y,self.z,self.side1,self.side2,self.side3) def contains(self,X:float,Y:float,Z:float)->bool: """ Checking if the 3D rectangle contains a point input is the point's coordinates we check if all the coordinates are between the center coordinate +/- the height, width or depth divided by 2, depending on which coordinate we are checking """ if not all([isinstance(i,(int,float)) for i in [X,Y,Z]]) or not all([not isinstance(i,bool) for i in [X,Y,Z]]): raise TypeError ("Point coordinates must be valid numbers") return True if self.x-self.side1 <=X<= self.x+self.side1 and self.y-self.side2 <=Y<= self.y+self.side2 and self.z-self.side3 <=Z<= self.z+self.side3 else False def __eq__(self, o: object) -> bool: """ Comparing 2 rectangular cuboids if their height, width and depth are respectively or non-respectively equal, they will be considered equal""" if type(self)!=type(o): raise TypeError("Can't compare a rectangular cuboid shape with a non-rectangular cuboid shape.") else: return True if (self.side1 == o.side1 or self.side1 == o.side2 or self.side1 == o.side3) and (self.side2 == o.side1 or self.side2 == o.side2 or self.side2 == o.side3) and (self.side3 == o.side1 or self.side3 == o.side2 or self.side3 == o.side3) else False def corners(self)->list: """ calculating the coordinates of the corners of our 3D rectangle since we will not be rotating any 3D shape, coordinates are simply center coordinate +/- heigh, width or depth by 2, depending on what coordinate of the corner we are calculating we return the points in such a way that would make the plotting not miss any side of the 3D rectangle nor plot unnecessary lines the points' coordinates will be used while plotting""" c1=[self.x+self.side1/2,self.y+self.side2/2,self.z+self.side3/2] c2=[self.x+self.side1/2,self.y-self.side2/2,self.z+self.side3/2] c3=[self.x+self.side1/2,self.y-self.side2/2,self.z-self.side3/2] c4=[self.x+self.side1/2,self.y+self.side2/2,self.z-self.side3/2] c5=[self.x-self.side1/2,self.y+self.side2/2,self.z+self.side3/2] c6=[self.x-self.side1/2,self.y-self.side2/2,self.z+self.side3/2] c7=[self.x-self.side1/2,self.y-self.side2/2,self.z-self.side3/2] c8=[self.x-self.side1/2,self.y+self.side2/2,self.z-self.side3/2] return [c1,c2,c3,c4,c1,c5,c6,c2,c6,c7,c3,c7,c8,c4,c8,c5] def __repr__(self)->str: """ description of our rectangular cuboid """ return (f"Type: Rectangular cuboid\nCenter : ({self.x},{self.y},{self.z})\nWidth : {self.side1}\nHeight : {self.side2}\nDepth : {self.side3}") class Sphere(Shape_3D): def __init__(self,x:float,y:float,z:float,radius:float)->None: super().__init__(x,y,z) self.radius=radius @property def radius(self)->float: return self._radius @radius.setter def radius(self,value)->None: if not isinstance(value,(int,float)) or isinstance(value,bool): raise TypeError("Radius value must be a valid number") if value==0: raise ValueError("Radius can't be 0") if value<0: raise ValueError("Radius can't be negative") self._radius=value def volume(self)->float: """ Calculating and returning the volume of the sphere """ return 4 * math.pi*(self.radius**3)/3 def circumference_surface(self)->float: """ Calculating and returning the circumference surface of the sphere """ return 4*math.pi*(self.radius**2) def move(self,X:float,Y:float,Z:float)->'Sphere': """ Moving the sphere Input from the user : X,Y and Z translation distances function will move the sphere by adding the distances to the X,Y and Z coordinates """ if not all([isinstance(i,(int,float)) for i in [X,Y,Z]]) or not all([not isinstance(i,bool) for i in [X,Y,Z]]): raise TypeError ("Distances must be valid numbers") self.x +=X self.y +=Y self.z +=Z return Sphere(self.x,self.y,self.z,self.radius) def move_to(self,X:float,Y:float,Z:float)->'Sphere': """ Moving the sphere to an exact point Input from the user : X,Y and Z coordinates of the point function will move the sphere by changing the center of the sphere's coordinates to the coordinates given by the user """ if not all([isinstance(i,(int,float)) for i in [X,Y,Z]]) or not all([not isinstance(i,bool) for i in [X,Y,Z]]): raise TypeError ("Point coordinates must be valid numbers") self.x =X self.y =Y self.z =Z return Sphere(self.x,self.y,self.z,self.radius) def scale(self,scaling_value:float)->'Sphere': """ Scaling the sphere input from the user : scaling value The method scales the sphere by multiplying the radius by the scaling value """ if not isinstance(scaling_value,(int,float)) or isinstance(scaling_value,bool): raise TypeError("Scaling value must be a valid number") if scaling_value == 0: raise ValueError("Scaling value can't be 0") if scaling_value < 0 : raise ValueError("Scaling value can't be negative") self.radius *= scaling_value return Sphere(self.x,self.y,self.z,self.radius) def change_radius(self,new_radius_value:float)->'Sphere': """ Changing the spheres's radius input from the user : new radius The method changes the spheres's radius to the new value """ if not isinstance(new_radius_value,(int,float)) or isinstance(new_radius_value,bool): raise TypeError("New radius value must be a valid number") if new_radius_value == 0: raise ValueError("New radius value can't be 0") if new_radius_value < 0 : raise ValueError("New radius value can't be negative") self.radius = new_radius_value return Sphere(self.x,self.y,self.z,self.radius) def contains(self,X:float,Y:float,Z:float)->bool: """ Checking if our sphere contains a point by comparing the distance between the center and the point with the radius of our sphere """ if not all([isinstance(i,(int,float)) for i in [X,Y,Z]]) or not all([not isinstance(i,bool) for i in [X,Y,Z]]): raise TypeError ("Point coordinates must be valid numbers") return True if ((self.x-X)**2 + (self.y-Y)**2 + (self.z-Z)**2)**0.5 <= self.radius else False def __eq__(self, o: object) -> bool: """ Comparing 2 spheres, if they have the same radius we would consider them equal """ if type(self)!=type(o): raise TypeError("Can't compare a Sphere with a non-sphere.") else: return True if self.radius == o.radius else False def __repr__(self)->str: """ a short description of our sphere""" return (f"Type: Sphere\nCenter : ({self.x},{self.y},{self.z})\nRadius : {self.radius}")
ea96c085e2d906bc42fe62c5c399b26fd6ea40f9
ElYannu87/learnthehardway
/ex15.py
281
3.625
4
# import sys # from sys import argv # naming script # script, filename = argv # open the file filename = input("Filename?") txt = open(filename, 'w') line4 = input("Line4: ") # print and read file print(f"Here's your file {filename}") txt.write(line4) txt.write("\n") txt.close()
39d442135370452b86ee1a1fa0bfa5997620c83a
ElYannu87/learnthehardway
/ex19.py
1,095
3.796875
4
def cheese_and_crackers(cheese_count, boxes_of_crackers): print(f"Your have {cheese_count} cheeses!") print(f"You have {boxes_of_crackers} boxes of crakcers!") print("Man that's enough for a party!") print("Get a blanket. \n") def cookies_and_milk(cookie_count, milk_count): print(f"You have {cookie_count} cookies!") print(f"To go with this you also have {milk_count} ml of milk!") print("That means 'Netflix & Chill' for the whole week-end") print("We can just give the funktion numbers directly:") cheese_and_crackers(20, 30) print("OR, we can use variable from our script:") amount_of_cheese = 10 amount_of_crackers = 50 cheese_and_crackers(amount_of_cheese, amount_of_crackers) print("We can even do math inside too:") cheese_and_crackers(10 + 20, 5 + 6) print("And we can combine the two, variable and math:") cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) cookies_and_milk(25, 1000) cookies_and_milk("not enough", "no") cookie_amount = input() milk_amount = input() cookies_and_milk(int(cookie_amount), int(milk_amount)
d1c15339e17f6c7faf3666be0b62c4d55a311ac1
kshannon/dse-241
/exercise_2/utils/data_shape_ex2.py
1,030
3.6875
4
# coding: utf-8 # Was a .ipynb file that we converted to a .py. temp1.json can be renamed. # Import libraries import json import pandas as pd import numpy as np # Read json file into pandas data frame df = pd.read_json('exercise2-olympics.json') df.head(5) # Dataframe to take who are the top 10 countries by medal count df1 = df.groupby('Country').count().sort_values(['Medal'], ascending=False).head(10) # Get this country list country_list = df1.index.values print country_list # Change country list to list and extracting only elements from main data frame that matches to country list c_lst = country_list.tolist() df_new = df[df['Country'].isin(c_lst)] # with open('temp.json', 'w') as f: # f.write(df_new.to_json(orient='records', lines=True)) # Saving the processed data frame as json that will be later used in d3 code with open('temp1.json', 'w') as f: f.write(df_new.to_json(orient='records')) # code to check if json file written looks good df_after = pd.read_json('temp1.json') df_after.head(5)
ac2082c2807c70d039c3335abc5461b945ef1788
sathiiii/Hackerrank-Solutions
/Dynamic Programming/Equal.py
1,893
3.6875
4
''' Problem Statement: Christy is interning at HackerRank. One day she has to distribute some chocolates to her colleagues. She is biased towards her friends and plans to give them more than the others. One of the program managers hears of this and tells her to make sure everyone gets the same number. To make things difficult, she must equalize the number of chocolates in a series of operations. For each operation, she can give 1, 2 or 5 chocolates to all but one colleague. Everyone who gets chocolate in a round receives the same number of pieces. For example, assume the starting distribution is [1, 2, 5]. She can give 2 bars to the first two and the distribution will be [3, 3, 5]. On the next round, she gives the same two 2 bars each, and everyone has the same number: [5, 5, 5] Given a starting distribution, calculate the minimum number of operations needed so that every colleague has the same number of chocolates. ''' def equal(arr): # Aim for the minimum (Because that will consume the least number of operations). Try to get all values to the minimum. m = min(arr) result = float("inf") # But will the minimum always be the optimal solution? Therefore, guess the optimal solution between min and min - 4. for offset in range(5): operations = 0 for i in arr: # The value we need to subtract to reach the minimum t = i - (m - offset) # How many times do we have to subtract by 5 -> t //5 # After subtracting by 5, how many times do can we subtract by 2 -> (t % 5) // 2 # Finally, how many times do we have to subtract by 1 (or the remainder after subtracting 5s and 2s) -> t % 5 % 2 operations += t // 5 + (t % 5) // 2 + (t % 5) % 2 result = min(result, operations) # Select the optimal solution return result
6f189295fa8c97662f91d6482e330d33d379c51c
fenning-research-group/Python-Utilities
/FrgTools/frgtools/imageprocessing.py
8,248
3.578125
4
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Button from PIL import Image import affine6p from skimage.transform import resize as skim_resize import cv2 def adjust_brightness(img, value): ''' adjust image brightness on a 0-255 scale example: img_brighter = adjust_brightness(img, 25) img_darker = adjust_brightness(img, -20) img_completelyblownout = adjust_brightness(img, 255) ''' hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) h, s, v = cv2.split(hsv) v += value v[v > 255] = 255 v[v < 0] = 0 final_hsv = cv2.merge((h, s, v)) img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR) return img ## Affine transformation scripts def affine_transform(img, T, resample = Image.NEAREST, plot = False, adjustcenterofrotation = False, **kwargs): """ Performs an affine transformation on an array image, returns the transformed array img: Takes an input image in numpy array format T: 3x3 Affine transformation matrix in numpy array format resample: PIL resampling method plot: if True, displays original + transformed images side by side adjustcenterofrotation: Certain transformation matrices assume rotation from 0,0, others assume center of image. If transformation matrix assumes rotation axis in center of image, set adjustcenterofrotation = True """ img_ = Image.fromarray(img) if adjustcenterofrotation: t_translate = np.array([ #move (0,0) to center of image instead of corner [1, 0, -img_.size[0]/2], [0, 1, -img_.size[1]/2], [0,0,1] ]) t_translate_back = np.array([ #move (0,0) to back to corner [1, 0, img_.size[0]/2], [0, 1, img_.size[1]/2], [0,0,1] ]) else: t_translate = np.array([ [1,0,0], [0,1,0], [0,0,1] ]) t_translate_back = np.array([ [1,0,0], [0,1,0], [0,0,1] ]) T_composite = t_translate_back @ T @ t_translate T_inv = np.linalg.inv(T_composite) img_t = img_.transform( img_.size, Image.AFFINE, data = T_inv.flatten()[:6], resample = resample, ) img_t = np.array(img_t) if plot: fig, ax = plt.subplots(1,2) ax[0].imshow(img, **kwargs) ax[0].set_title('Original') ax[1].imshow(img_t, **kwargs) ax[1].set_title('Transformed') plt.show() return img_t def affine_calculate(p, p0): """ Takes two m x 2 lists or numpy arrays of points, calculated the affine transformation matrix to move p -> p0 """ p1 = np.array(p) p2 = np.array(p0) T = affine6p.estimate(p, p0).get_matrix() return T ## image imputing def impute_nearest(data, invalid = None): """ Replace the value of invalid 'data' cells (indicated by 'invalid') by the value of the nearest valid data cell Input: data: numpy array of any dimension invalid: a binary array of same shape as 'data'. True cells set where data value should be replaced. If None (default), use: invalid = np.isnan(data) Output: Return a filled array. """ #import numpy as np #import scipy.ndimage as nd if invalid is None: invalid = np.isnan(data) ind = nd.distance_transform_edt(invalid, return_distances=False, return_indices=True) #return indices of nearest coordinates to each invalid point return data[tuple(ind)] ## pick points on image class __ImgPicker(): def __init__(self, img, pts, markersize = 0.3, **kwargs): self.numPoints = pts self.currentPoint = 0 self.repeating = False self.finished = False self.markersize = markersize self.fig, self.ax = plt.subplots() self.ax.imshow(img, picker = True, **kwargs) self.fig.canvas.mpl_connect('pick_event', self.onpick) self.buttonAx = plt.axes([0.4, 0, 0.1, 0.075]) self.stopButton = Button(self.buttonAx, 'Done') self.stopButton.on_clicked(self.setFinished) self.pickedPoints = [] self.pointArtists = [] self.pointText = [] plt.show(block = True) def setFinished(self, event): self.finished = True if self.numPoints != np.inf: while len(self.pickedPoints) < self.numPoints: self.pickedPoints.append([np.nan, np.nan]) plt.close(self.fig) def onpick(self, event): if not self.finished: mevt = event.mouseevent idx = self.currentPoint if not self.repeating: #if this is our first pass through the points, add a slot in the list for the point self.pickedPoints.append(None) self.pointArtists.append(None) self.pointText.append(None) x = mevt.xdata y = mevt.ydata self.pickedPoints[idx] = [x,y] if self.pointArtists[idx] is not None: self.pointArtists[idx].remove() self.pointArtists[idx] = plt.Circle((x,y), self.markersize, color = [1,1,1]) self.ax.add_patch(self.pointArtists[idx]) if self.pointText[idx] is not None: self.pointText[idx].set_position((x,y)) else: self.pointText[idx] = self.ax.text(x,y, '{0}'.format(idx), color = [0,0,0], ha = 'center', va = 'center') self.ax.add_artist(self.pointText[idx]) self.fig.canvas.draw() self.fig.canvas.flush_events() self.currentPoint += 1 if self.currentPoint >= self.numPoints: self.currentPoint = 0 self.repeating = True class AffineTransformer: ''' Object to aid in manual image registration using affine transformations (rotation, translation, and rescaling). Usage: - initialize the object by inputting a reference image and the number of registration points. kwargs can be passed to the plt.plot() command to improve image plotting to aid in placement of registration points - a new reference image can be used with the .set_reference() command - fit the transform between a new image and the reference image by .fit(img = new_image) - the affine transformation matrix moving any image such that the new image would match the reference image can be applied by .apply(img = moving_image) NOTE: this object relies of interactive matplotlib widgets. Jupyter lab plot backends will not play nicely with this tool. Jupyter notebook, however, will work with the "%matplotlib notebook" magic command enabled. ''' def __init__(self, img, pts, **kwargs): self.set_reference(img, pts, **kwargs) def set_reference(self, img, pts, **kwargs): self.num_pts = pts self.reference_pts = pick_points(img, pts) self.reference_shape = img.shape def fit(self, img): if img.shape != self.reference_shape: print('Warning: moving image and reference image have different dimensions - look out for funny business') img_t = self._resize(img, order = 0) self.resize_default = True else: img_t = img self.resize_default = False self.moving_pts = pick_points(img_t, pts = self.num_pts) def apply(self, img, resample = Image.NEAREST, plot = False, fill = np.nan, adjustcenterofrotation = False, resize = None, order = 0, **kwargs): # Note: the affine_calculate() call would ideally be in .fit(), but this is a silly workaround that # makes the helper play nice with Jupyter notebook. Issue is that the plot is nonblocking in notebook, # so affine_calculate() gets called before the user has a chance to select points on the moving image. if resize is None: resize = self.resize_default self.T = affine_calculate(self.moving_pts, self.reference_pts) if resize: img_t = self._resize(img, order = order, cval = fill) else: img_t = img img_t = affine_transform(img_t, self.T, resample = resample, plot = plot, adjustcenterofrotation = adjustcenterofrotation, **kwargs) return img_t[:self.reference_shape[0], :self.reference_shape[1]] def _resize(self, img, order = 0, **kwargs): xratio = img.shape[1] / self.reference_shape[1] yratio = img.shape[0] / self.reference_shape[0] target_shape = np.round(img.shape / np.min([xratio, yratio])).astype(int) img_t = skim_resize(img, target_shape, order = order, **kwargs) return img_t def pick_points(img, pts = 4, **kwargs): """ Given an image and a number of points, allows the user to interactively select points on the image. These points are returned when the "Done" button is pressed. Useful to generate inputs for AffineCalculate. If <pts are clicked, remaining points will be filled with [np.nan, np.nan] Note - for infinite points, you can set pts = np.inf, and only the number of clicked points will be returned """ imgpicker = __ImgPicker(img, pts, **kwargs) return imgpicker.pickedPoints
28a3d57dc9f488b89e738b0e6717b6cdac4e1e23
aolovely/NguyenTienThanh-Fundamentals-c4e13
/Session05/HomeWork/Exercise2.py
337
3.921875
4
numbers = [1, 6, 8, 1, 2, 1, 5, 6] def TimeNumber(n): count = 0 for i in range(len(numbers)): if numbers[i] == n: count += 1 return count number = int(input("program to count number occurrences in a list \n enter a number? ")) print("{0} appears {1} times in my list".format(number, TimeNumber(number)))
3561e9569974ab7a02fddb59d62416fc1f223283
aolovely/NguyenTienThanh-Fundamentals-c4e13
/Session05/HomeWork/Exercise4.py
239
3.921875
4
def rabbit(month): if month == 0: return 1 if month == 1: return 2 else: return rabbit(month - 1) + rabbit(month - 2) for i in range(5): print("month {0}: {1} pairs of rabbit".format(i, rabbit(i)))
481c1694ddaa1e5c99c1fd2d7f6b64a5c0ca6293
aolovely/NguyenTienThanh-Fundamentals-c4e13
/Session03/Game1.py
218
3.59375
4
n = int(input("enter: ")) count = 1 while True: if (n//10) != 0: count +=1 n //=10 else: break print(count) # while True: # count +=1 # n //=10 # if n == 0: # break
f93ea5e58432cda7ea42779f8ce1ecf0b018f8a6
aolovely/NguyenTienThanh-Fundamentals-c4e13
/Session05/HomeWork/Exercise2WithFunctionCount.py
205
4.09375
4
numbers = [1, 6, 8, 1, 2, 1, 5, 6] number = int(input("program to count number occurrences in a list \n enter a number? ")) print("{0} appears {1} times in my list".format(number, numbers.count(number)))
5ac518feb75960ec562952e50027cbd7c1fb8746
DiogoRibeiro7/Data-Cleaning
/convert_cat2num.py
233
3.5625
4
def convert_cat2num(df): # Convert categorical variable to numerical variable num_encode = {'col_1' : {'YES':1, 'NO':0}, 'col_2' : {'WON':1, 'LOSE':0, 'DRAW':0}} df.replace(num_encode, inplace=True)
30cb891b8e30026399bef6f9dc4db0d3ea021487
henryneu/pycharm
/cn/edu/modu/iter_tool.py
540
3.8125
4
# -*- coding:utf-8 -*- #Author: Henry import itertools natuals = itertools.count(1) ns = itertools.takewhile(lambda x: x <= 10, natuals) for n in ns: print(n) # cs = itertools.cycle('ABC') # for c in cs: # print(c) # 重复输出10个A np = itertools.repeat("A", 10) for p in np: print(p) # 把一组迭代对象串联起来 for c in itertools.chain('ABC', 'XYZ'): print(c) # 迭代器中相同元素分组放在一起 for key, group in itertools.groupby('AaaBBbccCAAaA', lambda c:c.upper()): print(key, list(group))