blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
421db14161fffc2155c0475266c70154b9acf0c8
gabriellaec/desoft-analise-exercicios
/backup/user_298/ch16_2020_09_09_11_45_22_713719.py
164
3.84375
4
val= input("Qual o valor da conta? ") val= float(val) def conta(val): fin = 1.1*val return fin print("Valor da conta com 10%: R${0:.2f}".format(conta(val)))
db64bb47b9db2c6c48e2af39df78609ccb15769f
Karls-Darwin/kreck
/lab7/rev2.py
225
4.25
4
def reverse(string): x="" i=-1 while abs(i)<len(string)+1: x+=string[i] i-=1 return x def main(): x=input('Enter a string: ') print(reverse(x)) if __name__ == '__main__': main()
a4933426e475c8d8d34bc7ea7ca00f9706836202
stanwar-bhupendra/LetsLearnGit
/snum.py
411
4.1875
4
#python program to find smallest number among three numbers #taking input from user num1 = int(input("Enter 1st number: ")) num2 = int(input("Enter 2nd number: ")) num3 = int(input("Enter 3rd number: ")) if(num1 <= num2) and (num1 <= num3): snum = num1 elif(num2 <=num1) and (num2 <=num3): snum = num2 else: snum = num3 print("The smallest number among ", num1,",", num2,",", num3 ,"is :", snum)
b3835c22508ecb68d116d03f7365cf1157e552e2
potentia/University-Projects
/Simple-Pentest-Tool/pentest.py
8,438
3.75
4
import socket import pycurl from io import BytesIO import os def showBanner(): """ Prints the logo of the program """ print(" _____ _ ____ ____ ") print(" |_ _| / \ |_ || _| ") print(" | | / _ \ | |__| | ") print(" _ | | / ___ \ | __ | ") print("| |__' | _/ / \ \_ _| | | |_ ") print("`.____.'|____| |____||____||____| ") def checkPort(target, portnum): """ Checks port numbers with the socket module. Takes 2 arguments 1 for the IP the other for port number""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creating an object of socket called sock with the # first parameter designating what type of address you can interface with. # The second is designating that we are going to be using tcp print("Testing port " + str(portnum)) # Outputs the port that is being tested try: # If a successful connection is made then True is returned if not False is returned sock.connect((target, portnum)) print("Port" + str(portnum) + " is open") return True except: return False def setTarget(): """ Sets the target IP by asking for user input then returns it""" return input("Enter target IP/URL: ") def fastPortScan(target): """ Fast port scanner(Common Ports) that calls the checkPort function and takes 1 argument which is the target """ print("Scanning...") openPorts = [] # Creating an empty list for the open ports for ports in [7, 19, 20, 21, 22, 23, 25, 42, 43, 49, 53, 67, 68, 69, 70, 79, 80, 88, 102, 110, 113, 119, 123, 135, 137, 139, 143, 161, 162, 177, 179, 201, 264, 318, 381, 383, 389, 411, 412, 443, 445, 464, 465, 497, 500, 512, 513, 514, 515, 520, 521, 540, 554, 546, 547, 560, 563, 587, 591, 593, 631, 636, 639, 646, 691, 860, 873, 902, 989, 990, 993, 995, 1025, 1026, 1029, 1080, 1194, 1214, 1241, 1311, 1337, 1433, 1434, 1512, 1589, 1701, 1723, 1725, 1741, 1755, 1812, 1813, 1863, 1985, 2000, 2002, 2049, 2082, 2083, 2100, 2222, 2302, 2483, 2484, 2745, 2967, 3050, 3074, 3124, 3127, 3128, 3222, 3260, 3306, 3389, 3689, 3690, 3724, 3784, 3785, 4333, 4444, 4664, 4672, 4899, 5000, 5001, 5004, 5005, 5050, 5060, 5190, 5222, 5223, 5432, 5500, 5554, 5631, 5632, 5800, 5900, 6000, 6001, 6112, 6129, 6257, 6436, 6347, 6500, 6566, 6588, 6665, 6669, 6679, 6697, 6699, 6881, 6891, 6970, 6999, 7212, 7648, 7649, 8000, 8080, 8086, 8087, 8118, 8200, 8500, 8767, 8866, 9100, 9101, 9103, 9119, 9800, 9898, 9988, 9999, 10000, 10113, 10116, 11371, 12035, 12036, 12345, 13720, 13721, 14567, 15118, 19226, 19638, 20000, 24800, 25999, 27015, 27374, 28960, 31337, 33434]: # Iterates through this lit of common ports if checkPort(target, ports) is True: # If checkPort returns true it adds the port to the openPorts list openPorts.append(str(ports)) return openPorts # When every port has been iterated through the loop breaks and the openPorts list is returned def deepPortScan(target): """ Port scanner that checks every port. calls the checkPort function and takes 1 argument which is the target """ print("Scanning...") openPorts = [] # Creating an empty list for the open ports for ports in range(0, 65535): # Iterates through all ports from 0 to 65535 if checkPort(target, ports) is True: # If checkPort returns true it adds the port to the openPorts list openPorts.append(str(ports)) return openPorts # When every port has been iterated through the loop breaks and the openPorts list is returned def checkURL(url): """ Return if the code is not 404 from the web server, False if no success at all """ buffer = BytesIO() # BytesIO function called to create an amount of binary digits this is set to a buffer c = pycurl.Curl() # Creating an instance of pycurl.Curl() called "c" c.setopt(c.URL, url) # Setting the url we want to check c.setopt(c.WRITEDATA, buffer) # Setting a buffer to WRITEDATA to suppress the output of the perform() method c.perform() # Performs the operations above code = c.getinfo(c.HTTP_CODE) # Using getinfo to check the HTTP_CODE and setting it to code if code != 404: # If the code is anything but 404 then return true and let the user know what code it was print("Request for %s gives a code of %d" % (url, code)) return True print("Request for %s gives a code of %d" % (url, code)) return False # Returns false if code is 404 meaning nothing is there def urlDirForce(root): """ Tries a standard list of common web directories to see if any exist on the target from the given root URL """ directorys = [] # Holds possible Directory's dirs = ["admin", "administrator", "backup", "config", "cpanel", "data", "images", "panel", "proxy", "staff", "uploads", "upload", "user", "users", "webmaster"] # List of dirs to try root = root.strip() # Take off any white space from the root given if not root.lower().startswith("http://"): # Check the root starts with http:// root = "http://" + root if root[-1] != "/": # Make sure it ends with / root = root + "/" for i in dirs: # Now run the check for every dir if checkURL(root + i) is True: directorys.append("/" + i) # Adds possible directory's to the list return directorys # list is returned after loop def checkAnonFTP(target, port=21): """ Returns True if the target appears to be running an anonymous FTP service. False otherwise. Defaults to checking on port 21 """ s = socket.socket() # Create a new instance of socket s.connect((target, port)) # The variables target and port are passed in data = s.recv(100) s.send(b"USER anonymous\n") # Sends the user name as "anonymous" as bytes data = s.recv(100) s.send(b"PASS anonymous\n") # Sends the password as "anonymous" as bytes data = s.recv(100) s.close() if data.startswith(b"230"): # Checks for the code 230 which means a connection was made print("Anonymous FTP enabled") return True return False def enumLocalUsers(): """ Checks the /etc/passwd which contains information about the users of the target""" with open("/etc/passwd") as f: # Opening the file and assigning it to f for l in f: # Iterating through every line in the file print(l.split(":")[0]) # Spiting the file at ":" and print only the first item in the list def findSetUID(): """ Find programs in the executable folders that have the Setuid bit """ print("These are the files that have Setuid \n") os.system("find /bin /sbin /usr/bin -perm /4000") # Makes use of the of the os module to run the command # Looks for the "-perm /4000" which means that the program has a Setuid bit if __name__ == "__main__": option = " " target = None showBanner() while not option[0] in ["q", "Q"]: print("\nTarget: " + str(target)) print("\n1. Set target") if target is not None: print("2. Port scan target - Fast Scan(Common Ports)") print("3. Port scan target - Deep Scan(All Ports)") print("4. URL directory brute-force") print("5. Test for anonymous FTP") print("6. Enumerate local users") print("7. Find local setuid files") print("Q. Quit") option = input("\nChoose an option: ") if option[0] == "1": target = setTarget() elif option[0] == "2": print("Open Ports !!! \n\n" + str(fastPortScan(target))) # Prints the open ports for fast scan elif option[0] == "3": print("Open Ports !!! \n\n" + str(deepPortScan(target))) # Prints the open ports for deep scan elif option[0] == "4": print("Possible Directory's \n\n" + str(urlDirForce(target))) # Prints possible directory's from web server elif option[0] == "5": checkAnonFTP(target) elif option[0] == "6": enumLocalUsers() elif option[0] == "7": findSetUID() elif option[0] in ["Q", "q"]: break else: print("Unknown option\n\n")
be17cada4dd9933904eae9fcb7e2ae52e990ca87
rutuja1302/Login-Signup_System
/Main/LoginSystem.py
4,198
4.3125
4
from tkinter import * import sqlite3 #create an object to create a window window = Tk() #Actions on Pressing Login Button def login(): def login_database(): conn = sqlite3.connect("1.db") cur = conn.cursor() cur.execute("SELECT * FROM test WHERE email=? AND password=?",(e1.get(),e2.get())) row=cur.fetchall() conn.close() print(row) if row!=[]: user_name=row[0][1] l3.config(text="user name found with name: "+user_name) else: l3.config(text="user not found") window.destroy() #closes the previous window login_window = Tk() #creates a new window for loging in login_window.title("LogIn") #set title to the window login_window.geometry("400x250") #set dimensions to the window #add 2 Labels to the window l1 = Label(login_window,text="email: ",font="times 20") l1.grid(row=1,column=0) l2 = Label(login_window,text="Password: ",font="times 20") l2.grid(row=2,column=0) l3 = Label(login_window,font="times 20") l3.grid(row=5,column=1) #creating 2 adjacent text entries email_text = StringVar() #stores string e1 = Entry(login_window,textvariable=email_text) e1.grid(row=1,column=1) password_text = StringVar() e2 = Entry(login_window,textvariable=password_text,show='*') e2.grid(row=2,column=1) #create 1 button to login b = Button(login_window,text="login",width=20,command=login_database) b.grid(row=4,column=1) login_window.mainloop() #Actions on Pressing Signup button def signup(): #Database action on pressing signup button def signup_database(): conn = sqlite3.connect("1.db") #create an object to call sqlite3 module & connect to a database 1.db #once you have a connection, you can create a cursor object and call its execute() method to perform SQL commands cur = conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS test(id INTEGER PRIMARY KEY,name text,email text,password text)") cur.execute("INSERT INTO test Values(Null,?,?,?)",(e1.get(),e2.get(),e3.get())) #execute message after account successfully created l4 = Label(signup_window,text="account created",font="times 15") l4.grid(row=6,column=2) conn.commit() #save the changes conn.close() #close the connection window.destroy() #closes the previous window signup_window = Tk() #creates a new window for signup process signup_window.geometry("400x250") #dimensions for new window signup_window.title("Sign Up") #title for the window #create 3 Labels l1 = Label(signup_window,text="User Name: ",font="times 20") l1.grid(row=1,column=1) l2 = Label(signup_window,text="User email: ",font="times 20") l2.grid(row=2,column=1) l3 = Label(signup_window,text="Password: ",font="times 20") l3.grid(row=3,column=1) #create 3 adjacent text entries name_text = StringVar() #declaring string variable for storing name and password e1 = Entry(signup_window,textvariable=name_text) e1.grid(row=1,column=2) email_text = StringVar() e2 = Entry(signup_window,textvariable=email_text) e2.grid(row=2,column=2) password_text = StringVar() e3 = Entry(signup_window,textvariable=password_text,show='*') e3.grid(row=3,column=2) #create 1 button to signup b1 = Button(signup_window,text="signup",width=20,command=signup_database) b1.grid(row=4,column=2) signup_window.mainloop() #main window code and driver code #give dimensions to the window window.geometry("300x150") #add title to the window window.title("Login and Signup system") #adding the label "Register Here" label1 = Label(window, text="Register Here!",font="times 20") label1.grid(row=1,column=2,columnspan=2) #adding two buttons - login and signup button1 = Button(window,text="Login",width=20,command=login) button1.grid(row=2,column=2) button2 = Button(window,text="Signup",width=20,command=signup) button2.grid(row=2,column=3) #calling mainloop method which is used when your application is ready to run and it tells the code to keep displaying window.mainloop()
aacccdbd244dd21b31268344bc4a6cbcd31fa597
Ang3l1t0/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-number_of_lines.py
311
3.703125
4
#!/usr/bin/python3 """Number of Lines """ def number_of_lines(filename=""): """number_of_lines Keyword Arguments: filename {str} -- file name or path (default: {""}) """ count = 0 with open(filename) as f: for _ in f: count += 1 f.closed return(count)
c44c924d65e1eb4e3739d64405527eed272686a2
Aurel37/Mopti-SA
/page_ranking.py
3,178
3.515625
4
import numpy as np def soustraction(u0, u1): """ u0, u1, two vectors return the vector (u0-u1) """ n = len(u0) res = [] for i in range(n): res.append(u0[i] - u1[i]) return res def copie_vect(u): """ copy the vector u """ res = [] for i in u: res.append(i) return res def norme(u): """ return the norm of the vector u """ res = 0 n = len(u) for i in range(n): res += u[i]**2 return res**(1/2) def somme_colonne_i(A, i): """ return the sum of the i-th line of A """ res = 0 n = len(A) for k in range(n): res += A[k, i] return res def normalisation(A): """ normalisation of the matrix A """ n = len(A) RES = np.zeros((n, n)) for i in range(n): for j in range(n): somme = somme_colonne_i(A, j) if somme != 0: RES[i, j] = A[i, j]/somme return RES def page_ranking(Link_mat, people_vac, X_vac, seuil=0.1): """ DESCRIPTION Perform the PageRanking algorithm on the adjacency matrix Link_mat, return the new adjacency matrix VARIABLES Link_mat : a square matrix representing a graph people_vac : number of people to remove from the graph X_vac : a vector of True, if the edge i is removed from the graph, the vertex i turns to False seuil : a float mesure """ n = len(Link_mat) u0 = [1 for i in range(n)] u1 = [0 for i in range(n)] Link_mat_n = normalisation(Link_mat) compteur = 0 while (norme(soustraction(u0, u1)) > seuil and compteur < 10 ): u1 = copie_vect(u0) u0 = np.dot(Link_mat_n, u0) if norme(u0) != 0: u0 = u0/norme(u0) print(u0) compteur += 1 indice = [] propre_indice = [] for i in range(n): propre_indice.append((abs(u0[i]), i)) propre_indice = sorted(propre_indice, key=lambda colonnes: colonnes[0]) vacc = [] for i in range(n-1, n-people_vac-1, -1): indice = propre_indice[i][1] vacc.append(indice) X_vac[indice] = False for j in range(n): Link_mat[indice][j] = 0 Link_mat[j][indice] = 0 def plus_grand_degres(Link_mat, people_vac, X_vac): n = len(Link_mat) deg = [0 for _ in range(n)] for i in range(n): for j in range(n): if Link_mat[i][j] > 0: deg[i] += 1 vacc = [] while(len(vacc) < people_vac): maxi = - 1 imax = - 1 for i in range(n): if i not in vacc: if deg[i] > maxi: imax = i maxi = deg[i] vacc.append(imax) for j in range(n): X_vac[imax] = False Link_mat[imax][j] = 0 Link_mat[j][imax] = 0 deg = [0 for _ in range(n)] for i in range(n): for j in range(n): if Link_mat[i][j] > 0: deg[i] += 1 def vaccine(Link_mat, i, X_vac): n = len(Link_mat) for j in range(n): X_vac[i] = False Link_mat[i][j] = 0 Link_mat[j][i] = 0
f7b2b3c9f8fe48602f870cd21dce8c2016117d27
git4lhe/lhe-algorithm
/Stack_and_Queue/프린터.py
769
3.609375
4
from collections import deque def solution(priorities, location): # 위치에 대한 값 저장 priorities = deque(priorities) loc_arr = deque([i for i in range(len(priorities))]) answer = [] for i in range(len(priorities)): max_value = max(priorities) while priorities: if priorities[0] == max_value: answer.append((priorities[0],loc_arr[0])) priorities.popleft() loc_arr.popleft() break front, loc = priorities.popleft(), loc_arr.popleft() priorities.append(front) loc_arr.append(loc) for n,(v, loc) in enumerate(answer): if loc == location: return n+1 print(solution([1, 1, 9, 1, 1, 1],0))
930cc1f5374e122e3cce84074554f163cd0d2474
DrAlbertCruz/5210-programming-fundamentals
/ch1-expressions.py
1,159
3.640625
4
import random NUM_QUESTIONS = 10 def createExpression(): startedPar = False string = str(random.randint(1,5)) + " "; for x in range(random.randint(1,3)): # Append a random connective op = random.randint(1,5) if op == 1: string += "+" elif op == 2: string += "-" elif op == 3: string += "*" elif op == 4: string += "//" elif op == 5: string += "**" string += " " + str(random.randint(1,10)) + " " return string CHAPTER = "ch1" TOPIC = "expression-evaluation" FILENAME = "bin/" + CHAPTER + "-" + TOPIC + ".txt" f = open( FILENAME, "w" ) # Preamble f.write( "$CATEGORY: " + CHAPTER + "/" + TOPIC + "\n\n" ) for x in range (NUM_QUESTIONS): result = 10000 while result > 1000 or result < 0: # Dont give out questions where the result is some insanely large number question = createExpression() result = eval(question) f.write( "::Question " + str(x) + "::[html]<p>What is the result of the following Python expression\: " + question + "? <em>Evaluate these by hand first, then confirm their correctness by inputting the expression into the Python interpreter</em></p>{#" + str(result) + "}\n\n" ) f.close()
696c2e57eca36e0a719d5c16b0a283019d91b684
Anri-Lombard/python
/GeeksForGeeks/27_06_2021_merge_sort.py
599
4.21875
4
def merge ( list1, list2 ): """Merge 2 sorted lists.""" new_list = [] while len(list1)>0 and len(list2)>0: if list1[0] < list2[0]: new_list.append (list1[0]) del list1[0] else: new_list.append (list2[0]) del list2[0] return new_list + list1 + list2 def merge_sort ( values ): """Sort values using merge sort algorithm.""" if len(values)>1: sorted1 = merge_sort (values[:len(values)//2]) sorted2 = merge_sort (values[len(values)//2:]) return merge (sorted1, sorted2) else: return values
de9750eb85195f3808650e24557627833051fd66
github-2643/Password-Generator-using-python
/password.py
767
4.03125
4
import random print("\t**********PASSWORD GENERATOR**********\t") print("\t___________________________________________\t\n") name: str=input("Enter your Name:") #user name chars = 'abcdefghijklmnopqrstuvwxyz@#$&' #small letter and special symbol chars1: str ='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'#capital letter and numeric value lenght =input ('how many password u have to generate\t') #number of password generate lenght =int(lenght) lenght1 =input('Enter your password lenght\t') lenght1 =int(lenght1) for p in range(lenght): password ='' for c in range(lenght1): password +=random.choice(chars+chars1) print(password) print('__________________________________') print('Thank you see u Mr.' + name) print('__________________________________')
ffe37d31a5c756843797b525f977c4e881dd2078
ai-kmu/etc
/algorithm/2022/0405_1038_Binary Search Tree to Greater Sum Tree/Joohye.py
1,430
3.5625
4
''' # 오른쪽검사->값업데이트->왼쪽검사->위쪽노드로 이동 # 위의 과정 반복 후 더 이상 탐색할 노드가 없을 경우 종료 ex)Example 1 으로 설명. 4(root.val)시작. 4(root.right) -> 6(root.right) -> 7(root.right) -> 8(root.right) = null -> score : 8 = 0 + 8 7(root.right) = 8 -> score : 15 = 7 + 8 6(root.right) = 15 -> score : 21 = 6 + 15 6(root.left) = 5 -> score : 26 = 5 + 21 4(root.right) -> score : 30 = 4 + 26 -> 4(root.left)로 넘어간다. 4(root.left) -> 1(root.right) -> 2(root.right) -> 3(root.right) = null -> score : 33 = 3 + 33 2(root.right) = 33 -> score : 35 = 2 + 33 1(root.right) = 35 -> score : 36 = 1 + 35 1(root.left) = 0 -> score : 36 = 0 + 36 4(root.left) -> 왼쪽 검사 끝났으므로, 종료. ''' class Solution: # score 초기화 def __init__(self): self.score = 0 def bstToGst(self, root: TreeNode) -> TreeNode: if root is not None: # 오른쪽 검사 self.bstToGst(root.right) # 값 업데이트(반드시 오른쪽과 왼쪽 검사 사이에만 값을 업데이트해줘야함) self.score += root.val # 해당 노드에 값 저장(example1, 파란색 숫자) root.val = self.score # 왼쪽 검사 self.bstToGst(root.left) # 올라간다 return root
a48356b956325a7e162cc345c556b8c855f218c9
shivhudda/python
/24_Functions_And_Docstrings.py
398
3.796875
4
# built-in function a=10 b=34 c = sum((a,b)) print(c) # user-defined function def function1(a,b): return a+b print(function1(10,34)) # using docstring def function2(a,b): """ this function returns average of a and b. this function does not work for three digits. """ average = (a+b)/2 return average print(function2(22,25)) # print a docstring print(function2.__doc__)
abb4c9d01d6634e9ba6bade1e6333b817dfc4cf1
ojhaanshu87/LeetCode
/314_vertical_tree_traversal.py
2,117
4.3125
4
''' Given the root of a binary tree, return the vertical order traversal of its nodes' values. (i.e., from top to bottom, column by column). If two nodes are in the same row and column, the order should be from left to right. ''' # Pre-order traversal # need a col and level variable to indicate which column and level is it # left, right and res lists to store, and combine three together for final result #Complexity Analysis ''' Time Complexity: (W⋅HlogH)) where WW is the width of the binary tree (i.e. the number of columns in the result) and HH is the height of the tree. In the first part of the algorithm, we traverse the tree in DFS, which results in \mathcal{O}(N)O(N) time complexity. Space Complexity: \mathcal{O}(N)O(N) where NN is the number of nodes in the tree. ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def driver_dfs(self, root, left, right, res, col, level): if not root: return if col < 0: if len(left) < -col: left.append([(root.val, level)]) else: left[-col - 1].append((root.val, level)) elif col > 0: if len(right) < col: right.append([(root.val, level)]) else: right[col - 1].append((root.val, level)) else: res[0].append((root.val, level)) self.driver_dfs(root.left, left, right, res, col - 1, level + 1) self.driver_dfs(root.right, left, right, res, col + 1, level + 1) def verticalOrder(self, root): if not root: return [] left, right, res = [], [], [[]] self.driver_dfs(root, left, right, res, 0, 0) left = left[::-1] for ls in [left, res, right]: for i in range(len(ls)): ls[i].sort(key=lambda x: x[1]) ls[i] = [val for val, _ in ls[i]] return left + res + right
5a499d9cab6afefe0fb05c39ca25c5560edbab40
Majician13/magic-man
/dateTime.py
1,140
4.65625
5
import datetime #Print todays date. currentDate = datetime.date.today() print(currentDate.strftime("%b %d, %Y")) #Print today's date in Python format, Just the month, just the Year. print(currentDate) print(currentDate.month) print(currentDate.year) #Print a special sentence including different aspects of the date. print(currentDate.strftime("Please attend our event %A, %B %d in the year %Y")) #Ask for and print someone's b-day #Please uncomment lines 17, 18, 23, 25, 26 to use this section birthday = input("What's your birthday? mm/dd/yyyy \n") birthdate = datetime.datetime.strptime(birthday, "%m/%d/%Y").date() #Why did we list datetime twice? #because we are calling the strptime function #Which is part of the datetime class #which is in the datetime module print("Your birth month is " + birthdate.strftime("%B")) difference = (currentDate - birthdate) print(difference.days) #Time from here on currentTime = datetime.datetime.now() print(datetime.datetime.strftime(currentTime, "%I:%M %p")) print(currentTime) print(currentTime.hour) print(currentTime.minute) print(currentTime.second)
d31f7b0b80aa7c8d7659a1ea3ca5022756030b1c
Lfritze/cs-module-project-algorithms
/moving_zeroes/moving_zeroes.py
1,299
4.4375
4
''' Input: a List of integers Returns: a List of integers ''' def moving_zeroes(arr): # Your code here # x is the index for x, i in enumerate(arr): # enumerate accepts arguments like -for c, value in enumerate(my_list, 1): print(c, value) # and creates a counter [(1, 'apple') (2, 'banana')...] if arr[x] != 0: #if x does not equal 0 arr.pop(x) # pop x arr.insert(0, i) # insert it at the beginning return arr # The pop() method removes the item at the given index from the list and returns the removed item. if __name__ == '__main__': # Use the main function here to test out your implementation arr = [0, 1, 3, 0, -2] print(f"The resulting of moving_zeroes is: {moving_zeroes(arr)}") ''' Write a function that takes an array of integers and moves each non-zero integer to the left side of the array, then returns the altered array. The order of the non-zero integers does not matter in the mutated array. Examples Sample input: [0, 3, 1, 0, -2] Expected output: 3 Expected output array state: [3, 1, -2, 0, 0] Sample input: [4, 2, 1, 5] Expected output: 4 Expected output array state: [4, 2, 1, 5] Can you do this in a single pass through the input array with O(1) space? '''
5842a3c5d619c9d6317aedd07b53493c03e6019b
Miracle1111/Diplomchik
/Fur.py
3,825
3.71875
4
import random # class Cafe_type: # def __init___(self, spendings, max_entrance): # self.spendings = spendings # self.max_entrance = max_entrance # # def get_type(self, id): # if id == 0: # self.spendings = 25000 # self.max_entrance = 15 # elif id == 1: # self.spendings = 50000 # self.max_entrance = 30 # elif id == 2: # self.spendings = 100000 # self.max_entrance = 60 # else: # print('There is no such type') # return (self.spendings, self.max_entrance) # # # cafe_1 = Cafe_type() # # # class Cafe: # def __init__(self, x, y, type): # self.x = x # self.y = y # self.owner = "Computer" # self.type = type # self.price = random.randint(25, 30) # # def start(self): # self.point = (self.x, self.y) # return self.point, self.owner, self.type, self.price # # # i = random.randint(1, 5) # cafe = [] # for i in range(0, i+1): # cafe.append(Cafe(1, 2, cafe_1.get_type(2)).start()) # print(cafe) class Object: def __init__(self, value = 0,object_type = 0): self.value = value self.type = object_type class Mapper: def __init__(self,size, computer_objects = 3): self.matrix = [] for _ in range(size): row = [] for _ in range(size): row.append(Object()) self.matrix.append(row) self.size = size self.computer_objects = computer_objects def addObject(self,Object): if(self.computer_objects == 0): print("No free space for you, cowboy") return while True: x = random.randint(0,self.size) y = random.randint(0,self.size) if (self.matrix[x][y].value == 0): #NOTE: 0 stands for no owner self.matrix[x][y].value = 1 #NOTE: 1 stands for computer owner self.matrix[x][y].type = Object.type self.computer_objects-=1 break Object.x = x Object.y = y def addUserObject(self,Object,x,y): if (self.matrix[x][y].value == 0): self.matrix[x][y].value = 2 #NOTE: 2 stands for user owner self.matrix[x][y].type = Object.type Object.x = x Object.y = y else: print("This space is ocupied") class Cafe: cafe_count = 0 @staticmethod def get_type(id): if id == 0: spendings = 2800 max_entrance = 15 elif id == 1: spendings = 5000 max_entrance = 30 elif id == 2: spendings = 10000 max_entrance = 50 else: print('There is no such type') return (spendings, max_entrance) def start(self, id, price , owner = "Computer"): print('Cafe is opened!') self.type = id self.owner = owner self.price = price self.x = 0 self.y = 0 self.spendings,self.max_entrance = Cafe.get_type(id) print(self.owner, id, self.price) Cafe.cafe_count +=1 # def draw(Object): # if Object.val == 1: # #TODO draw compture building # if Object.type == 0: # #TODO draw computer small # if Object.val == 2: # #TODO draw user building cafes_a = [Cafe() for i in range(random.randint(0, 3))] for i in cafes_a: i.start(1, random.randint(25, 35)) print(cafes_a) cafe_b = Cafe() cafe_b.start(0, random.randint(15, 25)) print(cafe_b.cafe_count) cafe_с = Cafe() cafe_с.start(2, random.randint(30, 45)) print(cafe_с.cafe_count) map = Mapper(4) map.addObject(cafe_b) # for i in range(map.size): # for j in range(map.size): # draw(map[i][j])
a107364f9889554937b500e5bb437250cc64b26f
AJAkil/catch-the-ghost-game
/Main.py
991
3.671875
4
from Game import Game import pprint from Coordinate import Coordinate if __name__ == '__main__': game = Game(9) game.initiate_board() game.print_board() while True: print('1. Advance Time 2. Scan 3. Bust The Ghost') choice = input('choose: ') if choice == '1': game.update_board_with_time() game.print_board() elif choice == '2': scan_x, scan_y = input('Enter coordinate for scanning: ').split(',') game.update_with_sense(Coordinate(int(scan_x), int(scan_y))) elif choice == '3': scan_x, scan_y = input('Enter coordinate for Busting: ').split(',') if int(scan_x) == game.ghost_position.x and int(scan_y) == game.ghost_position.y: print('Ghost is busted!!') break else: print('Could not bust ghost! Rescanning the cell.') game.update_with_sense(Coordinate(int(scan_x), int(scan_y)))
1de01b107f583200b06f986b41693ca747984088
wj1224/algorithm_solve
/leetcode/python/problem_117.py
1,133
4.0625
4
""" # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """ class Solution: def connect(self, root: 'Node') -> 'Node': if root is None: return root def search_nNode(node): while node.next is not None: node = node.next if node.left is not None: return node.left elif node.right is not None: return node.right else: pass return None lNode = root.left rNode = root.right if lNode is not None: if rNode is not None: lNode.next = rNode else: lNode.next = search_nNode(root) if rNode is not None: rNode.next = search_nNode(root) self.connect(rNode) self.connect(lNode) return root
65468261597ea27874ca6e17e2646b710f6ce8a4
litoos11/cursoMasterPython
/17-poo-constructor/main.py
580
3.6875
4
from coche import Coche carro = Coche("Rojo", "Chevrolet", "Corsa", 250, 240, 4) carro1 = Coche("Gris", "Chevrolet", "Atos", 250, 240, 4) carro2 = Coche("Verde", "Chevrolet", "Camaro", 250, 240, 4) carro3 = Coche("Rojo", "Renault", "Rio", 250, 240, 4) """ print(carro.getInfo()) print(carro1.getInfo()) print(carro2.getInfo()) print(carro3.getInfo()) """ #Detectar tipado carro3 = "str" if type(carro3) == Coche: print("Es un objeto correcto ") else: print("NO es un coche") #Visibilidad (Público o provado) """ print(carro.soy_publico) print(carro.getPrivado()) """
8fe4cf5bd53f0cfa47751e6f918cc1d942539241
devmetalbr/card_identifier
/card_identifier/card_type.py
1,462
3.546875
4
# Card name constants AMEX = 'AMEX' DISCOVER = 'Discover' MASTERCARD = 'MasterCard' VISA = 'Visa' UNKNOWN = 'Unknown' # Card number constants AMEX_2 = ('34', '37') MASTERCARD_2 = ('51', '52', '53', '54', '55') DISCOVER_2 = '65', DISCOVER_4 = '6011', VISA_1 = '4', def identify_card_type(card_num): """ Identifies the card type based on the card number. This information is provided through the first 6 digits of the card number. Input: Card number, int or string Output: Card type, string >>> identify_card_type('370000000000002') 'AMEX' >>> identify_card_type('6011000000000012') 'Discover' >>> identify_card_type('5424000000000015') 'MasterCard' >>> identify_card_type('4007000000027') 'Visa' >>> identify_card_type('400700000002') 'Unknown' """ card_type = UNKNOWN card_num = str(card_num) # AMEX if len(card_num) == 15 and card_num[:2] in AMEX_2: card_type = AMEX # MasterCard, Visa, and Discover elif len(card_num) == 16: # MasterCard if card_num[:2] in MASTERCARD_2: card_type = MASTERCARD # Discover elif (card_num[:2] in DISCOVER_2) or (card_num[:4] in DISCOVER_4): card_type = DISCOVER # Visa elif card_num[:1] in VISA_1: card_type = VISA # VISA elif (len(card_num) == 13) and (card_num[:1] in VISA_1): card_type = VISA return card_type
bbed1d3c352570590322a3e37dcddd03c858ae00
nac0n/AoC2019
/day1/1b.py
924
4.125
4
# Day 1 # The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values. # What is the sum of the fuel requirements for all of the modules on your spacecraft? def get_raw_mass_input(): File_object = open("input.txt","r+") file_content = File_object.read() file_content = file_content.split('\n') return file_content def calc_module_fuel_amount(module_mass): if(int(int(module_mass)/3 - 2) > 0): fuel = int(int(module_mass)/3 - 2) fuel += calc_module_fuel_amount(fuel) return fuel else: return 0 def fuel_sum(): fuel_total = 0 module_array = get_raw_mass_input() for module in range(0, len(module_array)): fuel_total += calc_module_fuel_amount(module_array[module]) return fuel_total print(fuel_sum())
45b4b4e1a7aff51e2d00d9168cfd4679d9d98edb
HerbertSu/PrincetonAlgorithms
/Part 1/geometric-applications-of-bsts/intervalST.py
1,131
3.59375
4
class IntervalST: def __init__(self): self.root = None return class Node: def __init__(self, key, val): self.key = key self.val = val self.left = None self.right = None self.count = 0 def contains(self, key): node = self.root while node != None: if key < node.key: node = node.left elif key > node.key: node = node.right else: return True return False def put(self, lo, hi, val): return def get(self, lo, hi): return def delete(self, lo, hi): return def intersects(self, lo, hi): return def intervalSearch(self, lo ,hi): x = self.root while x != None: if x.interval.intersects(lo, hi): return x.interval elif x.left == None: x = x.right elif x.left.max < lo: x = x.right else: x = x.left return None
1c8cfe4eff336b230f111045a2c66a0879645e01
nikkirethyo/CS61A
/lab07.py
2,468
4
4
# List Mutation def reverse(lst): """Reverses lst using mutation. >>> original_list = [5, -1, 29, 0] >>> reverse(original_list) >>> original_list [0, 29, -1, 5] """ lst.reverse() def map(fn, lst): """Maps fn onto lst using mutation. >>> original_list = [5, -1, 2, 0] >>> map(lambda x: x * x, original_list) >>> original_list [25, 1, 4, 0] """ for i in range(len(lst)): lst[i] = fn(lst[i]) # # filter is optional -- finish other non-optional problems first # def filter(pred, lst): # """Filters lst with pred using mutation. # >>> original_list = [5, -1, 2, 0] # >>> filter(lambda x: x % 2 == 0, original_list) # >>> original_list # [2, 0] # >>> original_list2 = ['cool', 'nice', 'rad'] # >>> filter(lambda x: len(x) == 4, original_list2) # >>> original_list2 # ['cool', 'nice'] # """ # "*** YOUR CODE HERE ***" # Dictionaries def counter(message): """ Returns a dictionary of each word in message mapped to the number of times it appears in the input string. >>> x = counter("to be or not to be") >>> x["to"] 2 >>> x["be"] 2 >>> x["not"] 1 >>> y = counter("run forrest run") >>> y["run"] 2 >>> y["forrest"] 1 """ word_list = message.split() num_times_word = {} for word in word_list: if word not in num_times_word: num_times_word[(word)] = 1 else: num_times_word[(word)] = num_times_word[(word)] + 1 return num_times_word # Adding in Nonlocal cs61a = { "Homework": 2, "Lab": 1, "Exam": 50, "Final": 80, "PJ1": 20, "PJ2": 15, "PJ3": 25, "PJ4": 30, "Extra credit": 0 } def make_glookup(class_assignments): """ Returns a function which calculates and returns the current grade out of what assignments have been entered so far. >>> student1 = make_glookup(cs61a) #cs61a is the above dictionary >>> student1("Homework", 1.5) 0.75 >>> student1("Lab", 1) 0.8333333333333334 >>> student1("PJ1", 18) 0.8913043478260869 >>> student2 = make_glookup(cs61a) >>> student2("Homework", 2) 1.0 """ grade = 0 perfect = 0 def current_grade(key, points): nonlocal grade nonlocal perfect grade += points perfect += class_assignments[(key)] return grade / perfect return current_grade
72465470daef4346055c1c2c028109d3888ab7eb
Grrw/RobCo-Terminal
/robchar.py
485
3.890625
4
""" File for char class is length one chars are made and decided by the templates used in charword for each char """ class robchar(): def __init__(self, char, owner): """ char is the character that is owner is the charword or False """ self.char = char self.owner = owner def ownedby(self): return self.owner def __str__(self): return self.char def string(self): return str(self.char) __repr__ = __str__
d1836477827a04f153f70878f72f61b7801206bb
Kanchan528/assignment1
/function/fun_10.py
227
4.28125
4
#Write a Python program to print the even numbers from a given list. def even_num(n): enum = [] for i in n: if i % 2 == 0: enum.append(i) return enum print(even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))
ecc42457d998d669bd1a9cbc2263bfa40a3d1aad
dalaAM/month-01
/day07_all/day07/exercise01.py
549
3.859375
4
""" 练习1:将两个列表,合并为一个字典 姓名列表["张无忌","赵敏","周芷若"] 房间列表[101,102,103] 练习2:颠倒练习1字典键值 """ names = ["张无忌", "赵敏", "周芷若"] rooms = [101, 102, 103] dict01 = {names[i]: rooms[i] for i in range(len(names))} dict02 = {value: key for key, value in dict01.items()} print(dict02) # 需求: 根据值查找键 # 解决方案1: 键值对颠倒 # 解决方案2: for key, value in dict01.items(): if value == 103: print(key)
27502803dfc4067d2e3010b7d0f887c036c07e11
Ran500/Python
/Github-python/variables.py
1,213
4.34375
4
# -------------------------------------- # -- Variables -- # --------------- # Syntax => [Variable Name] [Assignment Operator] [Value] # # Name Convention and Rules # [1] Can Start With (a-z A-Z) Or Underscore # [2] You Cannot With Num Or Special Characters # [3] Can Include (0-9) Or Underscore # [4] Cannot Include Special Characters # [5] Name is Not Like name [ Case Sensitive ] # -------------------------------------- name = "Rayan" # Single Word => Normal myName = "Rayan" # Two Words => camelCase my_name = "Rayan" # Two Words => snake_case print(name) print(myName) print(my_name) # --------------- # -- Variables -- # --------------- # Source Code : Original Code You Write it in Computer # Translation : Converting Source Code Into Machine Language # Compilation : Translate Code Before Run Time # Run-Time : Period App Take To Executing Commands # Interpreted : Code Translated On The Fly During Execution # -------------------------------------------------------- # Reserved Words الكلمات المحجوزهه في اللغة help("keywords") a, b, c = 1, 2, 3 print(a) print(b) print(c) var1, var2, var3 = "Rayan", "Ahmad", "sara" print(var1) print(var2) print(var3)
b78874e7c462baee6082f8864b96fbf986d4ff26
ameymahadik1997/amudi97
/Studentclass.py
464
3.875
4
#Student name and course joined class Student: def __init__(self): self.__sname=input('Enter The Student Name=>') self.__course=input('Enter The course joined=>') def showinfo(self): print('Student Name=',self.__sname,',Thanks for joining course= ',self.__course) def __del__(self): print('Thanks for using destructor :).') def main(): s1=Student() s2=Student() s1.showinfo() del s1 s2.showinfo() del s2 if __name__=='__main__': main()
2bb64adbdd9edb6a3bc71b4c0ffcc34328b5bea8
joshlevin91/Project-Euler
/p26.py
834
3.703125
4
from math import sqrt def find_period(n, d): z = x = n * 9 k = 1 while z % d: z = z * 10 + x k += 1 digits = f"{z // d:0{k}}" return k, digits def skip(n): i = 1 while i <= sqrt(n): if (n % i == 0): if (n / i == i): if i == 2 or i == 5: return True else: if i == 2 or i == 5 or n/i == 2 or n/i == 5: return True i = i + 1 return False def main(): longest_period = 0 d_longest_period = 0 for d in range(2,1000): if skip(d): continue period, cycle = find_period(1, d) if period > longest_period: longest_period = period d_longest_period = d print(d_longest_period) main()
f3abc1dfe41efd3952a4fa529933c09e6b6640b5
santiagoahc/coderbyte-solutions
/members/soduko_checkers.py
2,864
4.46875
4
""" Using the Python language, have the function SudokuQuadrantChecker(strArr) read the strArr parameter being passed which will represent a 9x9 Sudoku board of integers ranging from 1 to 9. The rules of Sudoku are to place each of the 9 integers integer in every row and column and not have any integers repeat in the respective row, column, or 3x3 sub-grid. The input strArr will represent a Sudoku board and it will be structured in the following format: ["(N,N,N,N,N,x,x,x,x)","(...)","(...)",...)] where N stands for an integer between 1 and 9 and x will stand for an empty cell. Your program will determine if the board is legal; the board also does not necessarily have to be finished. If the board is legal, your program should return the string legal but if it isn't legal, it should return the 3x3 quadrants (separated by commas) where the errors exist. The 3x3 quadrants are numbered from 1 to 9 starting from top-left going to bottom-right. For example, if strArr is: ["(1,2,3,4,5,6,7,8,1)", "(x,x,x,x,x,x,x,x,x)", "(x,x,x,x,x,x,x,x,x)", "(1,x,x,x,x,x,x,x,x)", "(x,x,x,x,x,x,x,x,x)", "(x,x,x,x,x,x,x,x,x)", "(x,x,x,x,x,x,x,x,x)", "(x,x,x,x,x,x,x,x,x)", "(x,x,x,x,x,x,x,x,x)"] then your program should return 1,3,4 since the errors are in quadrants 1, 3 and 4 because of the repeating integer 1. Another example, if strArr is: ["(1,2,3,4,5,6,7,8,9)" ,"(x,x,x,x,x,x,x,x,x)", "(6,x,5,x,3,x,x,4,x)", "(2,x,1,1,x,x,x,x,x)", "(x,x,x,x,x,x,x,x,x)", "(x,x,x,x,x,x,x,x,x)", "(x,x,x,x,x,x,x,x,x)", "(x,x,x,x,x,x,x,x,x)", "(x,x,x,x,x,x,x,x,9)"] then your program should return 3,4,5,9. """ def SudokuQuadrantChecker(strArr): soduko_mat = [[c for c in r.strip('()').split(",")] for r in strArr] quadrants = set() def get_quadrant(i, j): i_start = (i / 3) * 3 j_start = (j / 3) * 3 for m in range(i_start, i_start+3): for n in range(j_start, j_start+3): cell = soduko_mat[m][n] if cell == 'x' or (m == i and n == j): continue yield cell def is_valid(i, j): cell = soduko_mat[i][j] if cell == 'x': return True # check row if any((cell == soduko_mat[i][k] for k in range(9) if k != j)): return False # check col if any((cell == soduko_mat[k][j] for k in range(9) if k != i)): return False # check quadrant if any((cell == o for o in get_quadrant(i, j))): return False return True for i in range(9): for j in range(9): if not is_valid(i, j): quadrants.add(get_quadrant_label(i, j)) if not quadrants: return "legal" else: return ",".join(sorted(list(quadrants))) def get_quadrant_label(i, j): return "%s" % ((j / 3) + 3 * (i / 3) + 1)
003af195e424fb4a78ba60cc34519129420b72dd
adarshSrivastava01/GUI-CALCULATOR-TK
/guiapp.py
4,056
3.90625
4
from tkinter import * window = Tk() # Creating Window window.geometry('354x460') # Defining Size window.title('GUI CALCULATOR') label = Label(window,text='CALCULATOR',bg='#2C3335',fg='#ffffff',font=('Monotype Corsiva',28,'bold')) label.pack(side=TOP) window.config(background = '#2C3335') text = StringVar() # Variable to store text. operator = '' def button_click(num): """ Takes an operator as input attach that operator with text. """ global operator operator += str(num) text.set(operator) def equal_button(): """ Works on hitting equal button evaluate the string passed there """ global operator add = str(eval(operator)) text.set(add) operator = '' def clear_button(): """ Works on hitting C Button sets the string 'text' as an empty string. """ global operator text.set('') operator='' """ Section of formatting the Texts. """ boxtext = Entry(window, font=('Courier New',16,'bold'),textvar = text,width=25,bd=0,bg='#586776',fg='#ffffff') boxtext.pack() button_1 = Button(window,padx=17,pady=14,bd=4,bg='#758AA2',fg='#ffffff',command=lambda:button_click(1),text='1',font=('Arial',16,'bold')) button_1.place(x=10,y=100) button_4 = Button(window,padx=17,pady=14,bd=4,bg='#758AA2',fg='#ffffff',command=lambda:button_click(4),text='4',font=('Arial',16,'bold')) button_4.place(x=10,y=170) button_7 = Button(window,padx=17,pady=14,bd=4,bg='#758AA2',fg='#ffffff',command=lambda:button_click(7),text='7',font=('Arial',16,'bold')) button_7.place(x=10,y=240) button_2 = Button(window,padx=17,pady=14,bd=4,bg='#758AA2',fg='#ffffff',command=lambda:button_click(2),text='2',font=('Arial',16,'bold')) button_2.place(x=75,y=100) button_5 = Button(window,padx=17,pady=14,bd=4,bg='#758AA2',fg='#ffffff',command=lambda:button_click(5),text='5',font=('Arial',16,'bold')) button_5.place(x=75,y=170) button_8 = Button(window,padx=17,pady=14,bd=4,bg='#758AA2',fg='#ffffff',command=lambda:button_click(8),text='8',font=('Arial',16,'bold')) button_8.place(x=75,y=240) button_3 = Button(window,padx=17,pady=14,bd=4,bg='#758AA2',fg='#ffffff',command=lambda:button_click(3),text='3',font=('Arial',16,'bold')) button_3.place(x=140,y=100) button_6 = Button(window,padx=17,pady=14,bd=4,bg='#758AA2',fg='#ffffff',command=lambda:button_click(6),text='6',font=('Arial',16,'bold')) button_6.place(x=140,y=170) button_9 = Button(window,padx=17,pady=14,bd=4,bg='#758AA2',fg='#ffffff',command=lambda:button_click(9),text='9',font=('Arial',16,'bold')) button_9.place(x=140,y=240) button_0 = Button(window,padx=49,pady=14,bd=4,bg='#758AA2',fg='#ffffff',command=lambda:button_click(0),text='0',font=('Arial',16,'bold')) button_0.place(x=10,y=310) button_dec = Button(window,padx=20,pady=14,bd=4,bg='#758AA2',fg='#ffffff',command=lambda:button_click('.'),text='.',font=('Arial',16,'bold')) button_dec.place(x=140,y=310) button_plus = Button(window,padx=17,pady=14,bd=4,bg='#2B2B52',fg='#ffffff',command=lambda:button_click('+'),text='+',font=('Arial',16,'bold')) button_plus.place(x=205,y=100) button_sub = Button(window,padx=19,pady=14,bd=4,bg='#2B2B52',fg='#ffffff',command=lambda:button_click('-'),text='-',font=('Arial',16,'bold')) button_sub.place(x=205,y=170) button_mul = Button(window,padx=18.5,pady=14,bd=4,bg='#2B2B52',fg='#ffffff',command=lambda:button_click('*'),text='*',font=('Arial',16,'bold')) button_mul.place(x=205,y=240) button_div = Button(window,padx=19.5,pady=14,bd=4,bg='#2B2B52',fg='#ffffff',command=lambda:button_click('/'),text='/',font=('Arial',16,'bold')) button_div.place(x=205,y=310) button_clear = Button(window,padx=21,pady=119,bd=4,bg='#2B2B52',fg='#ffffff',command=lambda:clear_button(),text='C',font=('Arial',16,'bold')) button_clear.place(x=270,y=100) button_equal = Button(window,padx=152,pady=14,bd=4,bg='#2B2B52',fg='#ffffff',command=lambda:equal_button(),text='=',font=('Arial',16,'bold')) button_equal.place(x=10,y=380) window.mainloop()
20a95acf4f462ca30aeef9827fbb7b472e54a85c
smarthimawari/hi
/hi.py
58
3.5
4
name = input('Please enter your name') print('Hi,', name)
dba6d19e22a9dba78cae8546981b0f073ccea453
TCReaper/Computing
/Computing Revision/Computing Quizzes/Computing Quiz 1/A4.py
1,663
3.59375
4
debug_mode = True n = input("positive integer: ") tempPermutations = [["",n]] finalPermutations = [] output = [] itr = 1 while len(tempPermutations) > 0: print(str(itr)) currentPermutations = tempPermutations[0] if debug_mode: print("\tRemoving: [" + currentPermutations[0] + "," + currentPermutations[1] + "]") tempPermutations = tempPermutations[1:] for i in range(len(currentPermutations[1])): if len(currentPermutations[1][:i]+currentPermutations[1][i+1:])>0: if debug_mode: print("\tAdding to temp: [" + currentPermutations[0]+currentPermutations[1][i] + "," \ + currentPermutations[1][:i]+currentPermutations[1][i+1:] + "]") tempPermutations.append([currentPermutations[0]+currentPermutations[1][i] , \ currentPermutations[1][:i]+currentPermutations[1][i+1:]]) else: if debug_mode: print("\tAdding to final: [" + currentPermutations[0]+currentPermutations[1][i] + "," \ + currentPermutations[1][:i]+currentPermutations[1][i+1:] + "]") finalPermutations.append([currentPermutations[0]+currentPermutations[1][i] , \ currentPermutations[1][:i]+currentPermutations[1][i+1:]]) itr += 1 for i in finalPermutations: output.append(i[0]) print("\n") print("\n") print("\n") print(output)
855f3d7c51e53c4ad9cf0d1880f23be9ea368020
usako1124/teach-yourself-python
/chap06/set_union.py
416
3.515625
4
sets1 = {1, 20, 30, 60, 10, 15} sets2 = {10, 15, 30} sets3 = {20, 40, 60} print(sets1.union(sets2)) # ??? print(sets1.union(sets2, sets3)) # ??? print(sets1.intersection(sets2)) # {10, 30, 15} ??? print(sets1.intersection(sets2, sets3)) # set() print(sets1.difference(sets3)) # {1, 30, 10, 15} ??? print(sets1.difference(sets2, sets3)) # {1} print(sets1.symmetric_difference(sets3)) # ??? # 順番が謎い
20a70f2b45eb79a284674ac5aa10266dc99f6172
Wrangler416/afs210
/week6/shuffle/shuffle.py
566
4
4
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] n = len(list) # I used the fisher yates algo which is O(n) time complexity # this algo starts from the last list item and swaps it with # a randomly assigned index position and keeps doing so until all items are swapped # it is O(n) because it is swapping in place, linear time import random def shuffle(list, n): for i in range(n-1, 0, -1): a = random.randint(0, i +1) list[i], list[a] = list[a], list[i] return list print(list) print(shuffle(list, n)) print(shuffle(list,n)) print(shuffle(list,n))
ab43217649313b0894c131a1a55be8d07ebdac18
GaloMago/URI_Answers_py
/uri_1071.py
474
3.78125
4
def main() # entrada x = int(input()) y = int(input()) # processamento impares_bet(x,y) def impares_bet(x,y): impar = 0 soma = 0 if x > y: while x > y: if x % 2 !=0: impar += x print(impar) impares_bet(x-1,y) elif y > x: while y > x: if y % 2 !=0: impar += y print(impar) impares_bet(x,y-1)
d4400cb01e6d557eee6d96b18f642329f8d81c05
Polin-Tsenova/Python-Fundamentals
/Nikulden's meals.py
1,062
4
4
likes = {} unlikes = {} count = 0 while True: commands = input() if commands == "Stop": break tokens = commands.split("-") action = tokens[0] guest = tokens[1] meal = tokens[2] if action == "Like": if guest not in likes and guest not in unlikes: likes[guest] = [] unlikes[guest] = [] if meal in likes[guest] or meal in unlikes[guest]: continue likes[guest] += [meal] if action == "Unlike": if guest not in likes and guest not in unlikes: print(f"{guest} is not at the party.") continue if meal not in likes[guest]: print(f"{guest} doesn't have the {meal} in his/her collection.") continue print(f"{guest} doesn't like the {meal}.") likes[guest].remove(meal) count += 1 likes = dict(sorted(likes.items(), key=lambda x: (-len(x[1]),x[0]))) for k, v in likes.items(): print(f"{k}: {', '.join(v)}") print(f"Unliked meals: {count}")
b5ea91ec4dbf2bfcbb263c7e8fdfe8bc0f43a93e
nathramk/fp
/keny.py
194
3.53125
4
#a un areunion asistieron n persona, cuatos apretones de mano hubieron? #entrada a=input("ingrese valor: ") #proceso r=a*(a-1)/2 #salida print "la cnatidad de apretones es: %s"%r
96e3502eab78a7f72d660cccb4d2780cbecf5d21
airrain/Algorithm-questions-and-answers
/LeetCode-python/N-Queens.py
826
3.8125
4
""" 经典的八皇后问题的一般情况,用Python怎样来快速地解决呢? 8-queens 注意点: 皇后用"Q"表示,空白用"."表示 例子: 输入: n = 4 输出: [ ['.Q..', '...Q', 'Q...', '..Q.'], ['..Q.', 'Q...', '...Q', '.Q..']] 解题思路 用三个数组来表示列、正反对角线的占用情况。一行行的遍历,如果没有冲突就把相应的位置置为占用,继续处理下一行,并记录改行的皇后放在了哪一列,当皇后都放完后,根据记录的列号来拼出结果。进行回溯时要把占用的位置还回去。对角线位置的计算要小心(尤其是反对角线),可以把顶点带进去计算验证一下。 """ class Solution(object): def solveNQueens(self,n): self.col = [False] *
f9fb309830d35b918b0a6c097cdf3ddeee40a0f6
slottwo/rpg-dpc
/calculator/old.py
3,020
3.78125
4
# The next step for optimization is using the sample space with maybe: # faces if amount == 1 # faces**2 if amount == 2 # ??? if amount > 2 # ;-;=b # if amount == 3: if faces is even: 2* (mid*(min+mid)/2); elif faces == 3: (faces+1)**2; elif faces==5: (faces+2)**2... # I think... def sums_counter(amount: int, faces: int): result_min = amount # * 1 (minor face); The minimum scrollable result result_max = amount * faces # The maximum scrollable result results = dict() # The count will be allocated in a dictionary listing how many times each hit occurs even = amount % 2 != 0 and faces % 2 == 0 # No, no is wrong! This "even" meas if the length counts is even, # and it will be important in the line 18 result_mid = (result_max + result_min) // 2 # Similar to the Pascal sequence, it is mirrored in its midst if amount == 1: # In the case, we have a equiprobable sample space, so all the results occur once for result in range(result_min, result_max+1): results[result] = 1 else: # If you tab the possible results, you will see that a "pyramidal" pattern to the values with a arithmetic # ratio of the 1 for result in range(result_min, result_max+1): if result == result_min: results[result] = 1 elif result <= result_mid: results[result] = results[result - 1] + 1 elif result == result_mid + 1 and even: results[result] = results[result - 1] else: results[result] = results[result-1] - 1 return results def sums_probabilities(amount: int, faces: int, percentage=False): # With the count values it is possible to calculate the probability by dividing by the sample space, which would # be the sum of this count. sums_counts = sums_counter(amount, faces) results = dict() counts = sums_counts.values() sample_space = sum(counts) for r, c in sums_counts.items(): probability = c/sample_space if percentage: probability *= 100 results[r] = probability return results # Tester dice_ex = input("<#DADOS>d<#FACES>: ") n, f = map(int, dice_ex.split('d')) # n: amount of dices, f: amount of faces show_percent = input("Mostrar em porcentagem? [Sn]") in "Ss" f_max = f del f for f in range(2, f_max + 1): # 2: Coin; But it work with 1... print("="*30 + f" {n}d{f} " + "="*30) sums_n_counts = sums_counter(n, f) sums_n_probs = sums_probabilities(n, f, show_percent) probabilities = list(map(round, sums_n_probs.values(), [2 for x in sums_n_probs])) for soma in sums_n_counts.keys(): print(str(soma).center(9), end= '| ') print() for count in sums_n_counts.values(): print(str(count).center(9), end='| ') print("=" + str(sum(sums_n_counts.values())).center(9)) for probability in probabilities: print((str(probability) + ("%" if show_percent else "")).center(9), end='| ') print() print("="*65)
d47e48bbcc52eff5adebcd9a9a9ead0bb8089f49
rlashdk2341/91907_Quiz-Game
/04_game_gui_v.2.py
7,298
3.859375
4
from tkinter import * import csv import random class Start: def __init__(self): # Start GUI self.start_frame = Frame(padx=10, pady=10) self.start_frame.grid() # Heading row 0 self.director_label = Label (self.start_frame, text="Movies and Directors Quiz", font= "Helvetica 20 bold") self.director_label.grid(row=0) # to_game button row 1 self.play_button = Button(text="Play", command= self.to_game) self.play_button.grid(row=1) def to_game(self): Game() class Game: def __init__(self): # Import the csv file, name of csv file goes here... with open('movies-directors.csv', 'r') as f: file = csv.reader(f) next(f) my_list = list(file) # Inital Score self.score = 0 # Amounts of games played self.played = 0 question_ans = random.choice(my_list) yes = random.choice(my_list) no= random.choice(my_list) ok = random.choice(my_list) self.question = question_ans[1] self.answer = question_ans[0] incorrect1 = yes[0] incorrect2 = no[0] incorrect3 = ok[0] print(question_ans) button_list = [self.answer, incorrect1, incorrect2, incorrect3] random.shuffle(button_list) self.top_left=button_list[0] self.top_right=button_list[1] self.bottom_left=button_list[2] self.bottom_right=button_list[3] # GUI Setup self.game_box = Toplevel() self.game_frame = Frame(self.game_box) self.game_frame.grid(padx=10, pady=10) # Director Label row 0 self.director_label = Label(self.game_frame, text=self.question, font="Helvetica 15 bold") self.director_label.grid(row=0) # Label showing correct or incorrect row 1 self.answer_box = Label(self.game_frame, text="", font="Helvetica 14 italic", width=35, wrap=300) self.answer_box.grid(row=1) # Setup grid for answer buttons row 2 self.top_answers_frame = Frame(self.game_box, width=50, height=50) self.top_answers_frame.grid(row=2, padx=5) # width, wrap, font height for buttons wt=15 ht=2 wr=170 ft="Helvetica 15" # Top level answers buttons row 2.0 self.top_left_answer_button = Button(self.top_answers_frame, text=self.top_left, font=ft, padx=5, pady=5,width=wt,height=ht,wrap=wr, command=lambda: self.reveal_answer(self.top_left)) self.top_left_answer_button.grid(column=0, row=0,padx=5,pady=5) self.top_right_answer_button = Button(self.top_answers_frame, text=self.top_right, font=ft, padx=5,pady=5,width=wt,height=ht,wrap=wr, command=lambda: self.reveal_answer(self.top_right)) self.top_right_answer_button.grid(column=1, row=0,padx=5,pady=5) # Bottom level answers buttons row 2.1 self.bottom_left_answer_button = Button(self.top_answers_frame, text=self.bottom_left, font=ft, padx=5, pady=5,width=wt,height=ht,wrap=wr, command=lambda: self.reveal_answer(self.bottom_left)) self.bottom_left_answer_button.grid(column=0, row=1,padx=5,pady=5) self.bottom_right_answer_button = Button(self.top_answers_frame, text=self.bottom_right, font=ft, padx=5, pady=5,width=wt,height=ht,wrap=wr, command=lambda: self.reveal_answer(self.bottom_right)) self.bottom_right_answer_button.grid(column=1, row=1,padx=5,pady=5) # Label for the score and games played row 3 self.score_label = Label(self.game_box, text="{} correct, {} rounds played".format(self.score,self.played)) self.score_label.grid(row=3) # The Next button to proceed to the next round row 4 self.next_button = Button(self.game_box, text="Next", command=lambda:self.to_next(my_list)) self.next_button.grid(row=4) # Disable the next button initially, self.next_button.config(state=DISABLED) def reveal_answer(self, location): # Disable all the buttons self.top_left_answer_button.config(state=DISABLED) self.top_right_answer_button.config(state=DISABLED) self.bottom_left_answer_button.config(state=DISABLED) self.bottom_right_answer_button.config(state=DISABLED) # Enable the next_button self.next_button.config(state=NORMAL) # Increase total rounds played by 1 self.played += 1 # Check if button is correct. if location == self.answer: self.answer_box.config(text="Correct!", fg="green") self.score += 1 else: self.answer_box.config(text="Incorrect, correct Movie was {}".format(self.answer), fg="red") # Update the score that the user has self.score_label.config(text="{} correct / {} rounds played".format(self.score, self.played)) def to_next(self,list): self.top_left_answer_button.config(state=NORMAL) self.top_right_answer_button.config(state=NORMAL) self.bottom_left_answer_button.config(state=NORMAL) self.bottom_right_answer_button.config(state=NORMAL) self.next_button.config(state=DISABLED) self.answer_box.config(text="") question_ans = random.choice(list) yes = random.choice(list) no = random.choice(list) ok = random.choice(list) self.question = question_ans[1] self.answer = question_ans[0] incorrect1 = yes[0] incorrect2 = no[0] incorrect3 = ok[0] print(question_ans) self.director_label.config(text=self.question) button_list = [self.answer, incorrect1, incorrect2, incorrect3] random.shuffle(button_list) self.top_left = button_list[0] self.top_right = button_list[1] self.bottom_left = button_list[2] self.bottom_right = button_list[3] # Defining the randomized list to their corresponding buttons self.top_left_answer_button.config(text=self.top_left, command=lambda: self.reveal_answer(self.top_left)) self.top_right_answer_button.config(text=self.top_right, command=lambda: self.reveal_answer(self.top_right)) self.bottom_left_answer_button.config(text=self.bottom_left, command=lambda: self.reveal_answer(self.bottom_left)) self.bottom_right_answer_button.config(text=self.bottom_right, command=lambda: self.reveal_answer(self.bottom_right)) # main routine if __name__ == "__main__": root = Tk() root.title("Movies and Directors Quiz") something = Start() root.mainloop() random.shuffle(button_list)
c0fa16ccd4fda578289323b2f03360b3004f568c
luizhuaman/platzi_python
/p6_prueba.py
637
3.765625
4
OPCION = "-abcdefghijklm" #RECORRER STRING for letra in OPCION: print ("Opcion {} ".format(letra.upper())) entrada = input('Ingresa tu opcion : ') print("El indice de la opcion que elegiste, es el siguiente: {}".format(OPCION.rfind(entrada.lower()))) #RFIND() PARA TRAER EL INDICE DE INPUT if OPCION.rfind(entrada.lower()) == 13: print('Lo logre, entro a la condicion, marcaste M') #CONTINUE AND BREAK for i in range(1,14): if entrada == OPCION[i]: break if OPCION[i] == OPCION[2]: continue print(OPCION[i].upper()) cadenda_texto = "Luis" cadenda_texto = cadenda_texto*2 print(cadenda_texto)
e075818681b7dd48701ad5520e003e5652e149b1
nflondo/myprog
/python/hardwaybook/ex40-first-class.py
1,113
3.796875
4
class Song(object): def __init__(self, lyrics, title): self.lyrics = lyrics self.title = title def sing_me_a_song(self): # for line in self.lyrics: # print line print self.lyrics def __str__(self): return self.title #happy_bday = Song(["Happy birthday to you", # "I don't want to get sued.", # "So I'll stop right there"]) #bulls_on_parade = Song(["They rally around the family", # "With pockets full of shells"]) # put lyrics in a var, then pass the var #twinkle_lyrics = ['Twinkle twinle little star', 'how I wonder where you are'] twinkle_lyrics = ("Twinkle twinle little star, how I wonder where you are") twinkle = Song(twinkle_lyrics, "Twinkle Song") #happy_bday.sing_me_a_song() #bulls_on_parade.sing_me_a_song() twinkle.sing_me_a_song() print '-' * 10 print "Will print object" print twinkle
c3f88a3ba356ab1be000c8a4d133b691b7cbd062
Danieloliver11/Python
/Impacta/semana 10,11,12/teste marco.py
955
4.21875
4
#AC 4 Lógica de programação n = int(input('Digite a quantidade de nomes que irá digitar:')) list = [] #Digitar números entre 3 e 10. while n <3 or n>10: n = int(input('Digite um número entre 3 e 10:')) #lista de n elemento. for x in range(1,n): valor = input('Digite um nome:') list.append(valor) print('Nomes digitados pelo usuario:',list) #Inserir "teste" no indice 3. list.insert(3,'Teste') print('lista depois de inserir teste:',list) #excluir elemento no indice 2. del list[2] print('Lista depois de excluir indice 2:',list) #Verifique quantas vezes você digitou o nome 'Ana'. Se for maior que 0, mostre o índice da primeira ocorrência, #Se for 0, mostre uma frase informando que o nome Ana não existe na lista. r = list.count('Ana') if r >0: print('O indice da primeira ocorrência do nome Ana:',list.index('Ana')) else: print('O nome Ana não exite na lista.') #No final, mostre a lista ordenada. list.sort() print(list)
bf84d3cbaa398008632649a14114369c33c05063
gilsonaureliano/Python-aulas
/python_aulas/desaf033_if_numeromaioremenor.py
1,126
4.125
4
n1 = int(input('Digite um numero ')) n2 = int(input('Digite o segundo numero: ')) n3 = int(input('Digite o terceiro numero: ')) if n1 > n2 > n3: print('{} é o maior numero1'.format(n1)) print('{} é o menor numero'.format(n3)) if n1 < n2 < n3: print('{} é o maior numero2'.format(n3)) print('{} é o menor numero'.format(n1)) if n1 < n2 > n3 > n1: print('{} é o maior numero3'.format(n2)) print('{} é o menor numero'.format(n1)) if n1 < n2 > n3 < n1: print('{} é o maior numero4'.format(n2)) print('{} é o menor numero'.format(n3)) if n1 > n2 < n3 > n1: print('{} é o maior numero5'.format(n3)) print('{} é o menor numero'.format(n2)) if n1 > n2 < n3 < n1: print('{} é o maior numero6'.format(n1)) print('{} é o menor numero'.format(n2)) print('='*100) print('') # Para escolher o menor menor = n1 if n2 < n1 and n2 < n3: menor = n2 if n3 < n1 and n3 < n2: menor = n3 # para escolher o maior maior = n1 if n2 > n1 and n2 > n3: maior = n2 if n3 > n1 and n3 > n2: maior = n3 print('Valor maior {}'. format(maior)) print('Valor MENOR {}'. format(menor))
90e9c911d923a95741323a41673607e07fd564ba
ajayvenkat10/geek-trust
/geektrust.py
1,062
3.59375
4
import sys from GoldenCrown import * MIN_REQUIRED_TO_BE_RULER = 3 RULER = "SPACE" def solveGoldenCrown(input_file): kingdoms_list = ["SPACE", "LAND", "WATER", "ICE", "AIR", "FIRE"] animals_list = ["GORILLA", "PANDA", "OCTOPUS", "MAMMOTH", "OWL", "DRAGON"] goldenCrown = GoldenCrown(kingdoms_list, animals_list) kingdoms_captured = [] with open(input_file) as in_file: inputs = in_file.readlines() for input in inputs: input = input.split() kingdom_name = input[0] message = ''.join(input[1:]) if(goldenCrown.isCaptureSuccessful(kingdom_name, message)): kingdoms_captured.append(kingdom_name) in_file.close() if(len(kingdoms_captured) >= MIN_REQUIRED_TO_BE_RULER): kingdoms_captured.insert(0, RULER) else: kingdoms_captured = ["NONE"] return kingdoms_captured def main(): ruled_kingdoms = solveGoldenCrown(sys.argv[1]) print(* ruled_kingdoms) if __name__ == "__main__": main()
efbcabca3514d4cf2b7cbac91a3c6a0f142d7662
jonathanjaimes/python
/3_primos.py
359
3.859375
4
num = int(input("Ingrese un numero: ")) def primo(num): for n in range(2, num): if num % n == 0: return False else: return True resultado = primo(num) if resultado is True: print("El número es primo") else: print("El numero no es primo") primo(num)
dec03f49d8a4e4f5028a64c4d47661a4b7a43f10
ksteinfe/decodes_examples
/106 - Lines and Planes/1.06.E03 - Solar Incidence/1.06.E03a.py
921
3.609375
4
''' 1.06.E03a required: result: ''' """ Angle of Incidence Between Ray and Plane This function does not return the actual angle, but rather the cosine of the angle of incidence between a given plane and vector. If the vector is "behind" the plane, a value of 0.0 is returned, thereby constraining the result to a range of [0-\>1] """ def aoi(pln,vec): return max(0, vec.dot(pln.normal)) """ Color by Angle of Incidence A given Plane is assigned a color by its angle of incidence to a given Vec. Planes oriented perpendicular to the Vec are red, those parallel to it are blue, and those in-between are colored by interpolation. Planes facing away from the Vec are assigned black. """ def color_by_angle(tar_plane,src_vec): ang = aoi(tar_plane,src_vec)**2 clr = Color.interpolate( blue, red, ang ) if ang == 0: clr = black tar_plane.set_color(clr) return clr color_by_angle(pln,sun_vec)
425d46fd323d0860c1df9bcf20a64c950773418b
EzraKatzman/Algo-Sandbox
/sarcasticText.py
186
3.71875
4
import random def sarcastify(your_string): return "".join(x.upper() if random.randint(0,1) else x for x in your_string) print(sarcastify("well what are you going to do about it?"))
a623e5322002ee54b00f9485464c2cb80f8fb12b
asterinwl/2021-K-Digital-Training_selfstudy
/5.24/09_Tuple/Homework.py
984
3.984375
4
my_variable=() print(type(my_variable)) #t = (1, 2, 3) #t[0] = 'a' #tuble에는 새로운 요소를 집어넣을 수 없어서 오류가 생긴다. hi=tuple() hi=(1,) print(type(hi)) print(*hi) # num = tuple() # list(num) # num.append(1) # num=tuple(num) # tuple(num) t=1,2,3,4 print(type(t)) t=('a','b','c') tl=list(t) tl[0]='A' t=tuple(tl) print(t) print(type(t)) interest=('삼성전자','LG전자','SK Hynix') interestl=list(interest) print(interestl) print(type(interestl)) interest=['삼성전자','LG전자','SK Hynix'] interestt=tuple(interest) print(interestt) print(type(interestt)) partyA={"Park","Kim","Lee"} partyB={"Park","길동","몽룡"} print("1)파티에 참석한 모든 사람은?" , *(partyA | partyB)) print("2)2개의 파티에 모두 참석한 사람은?" , *(partyA&partyB)) print("3)파티 A에만 참석한 사람", *(partyA-partyB)) print("4)파티 B에만 참석한 사람" , *(partyB-partyA))
89ea588542582981e9730733d80bbf37838017fe
GalinaLopez/data-analytics-portfolio
/car_test.py
5,206
3.5
4
import unittest from car import Car, EngineCar, PetrolCar, DieselCar, ElectricCar, HybridCar # Car test suite # tests the car functionality class TestCar(unittest.TestCase): def setUp(self): self.car = Car() # this tests the default constructors def test_car_default_constructors(self): self.assertEqual('', self.car.reg) self.assertEqual('', self.car.make) self.assertEqual('', self.car.model) self.assertEqual('', self.car.colour) self.assertEqual(0, self.car.mileage) self.assertEqual(-1, self.car.type) # this tests the getters functionality def test_car_getters(self): self.assertEqual('', self.car.getReg()) self.assertEqual('', self.car.getMake()) self.assertEqual('', self.car.getModel()) self.assertEqual('', self.car.getColour()) self.assertEqual(0, self.car.getMileage()) self.assertEqual(-1, self.car.getType()) # this tests the setters functionality def test_car_setters(self): self.car.setReg('151 D 10257') self.car.setMake('Mercedes') self.car.setModel('e230') self.car.setColour('silver') self.car.setMileage(10000) self.car.setType(0) self.assertEqual('151 D 10257', self.car.getReg()) self.assertEqual('Mercedes', self.car.getMake()) self.assertEqual('e230', self.car.getModel()) self.assertEqual('silver', self.car.getColour()) self.assertEqual(10000, self.car.getMileage()) self.assertEqual(0, self.car.getType()) # this tests the move car functionality def test_car_move_car_method(self): self.assertEqual(0, self.car.getMileage()) self.car.moveCar(500) self.assertEqual(500, self.car.getMileage()) # tests the engine car functionality class TestEngineCar(TestCar): def setUp(self): self.car = EngineCar() # this tests the default constructor def test_engine_default_constructor(self): self.assertEqual(0, self.car.engine_size) # this tests the getter functionality def test_engine_getter(self): self.assertEqual(0, self.car.engine_size) # this tests the setter functionality def test_engine_setter(self): self.car.setEngine(1400) self.assertEqual(1400, self.car.getEngine()) # tests the petrol car functionality class TestPetrolCar(TestEngineCar): def setUp(self): self.car = PetrolCar() # this tests the default constructor def test_petrol_default_constructor(self): self.assertEqual('', self.car.petrol_type) # this tests the getter functionality def test_petrol_getter(self): self.assertEqual('', self.car.getPetrol()) # this tests the setter functionality def test_petrol_setter(self): self.car.setPetrol('unleaded') self.assertEqual('unleaded', self.car.getPetrol()) # tests the diesel car functionality class TestDieselCar(TestEngineCar): def setUp(self): self.car = DieselCar() # this tests the default constructor def test_diesel_default_constructor(self): self.assertEqual(False, self.car.has_turbo_enabled) # this tests the getter functionality def test_diesel_getter(self): self.assertEqual(False, self.car.has_turbo_enabled) # this tests the setter functionality def test_diesel_setter(self): self.car.setTurbo(True) self.assertEqual(True, self.car.getTurbo()) # tests the electric car functionality class TestElectricCar(TestCar): def setUp(self): self.car = ElectricCar() # this tests the default constructor def test_electric_default_constructor(self): self.assertEqual(0, self.car.fuel_cells) # this tests the getter functionality def test_electric_getter(self): self.assertEqual(0, self.car.fuel_cells) # this tests the setter functionality def test_electric_setter(self): self.car.setFuelCells(2) self.assertEqual(2, self.car.getFuelCells()) # tests the hybrid car functionality class TestHybridCar(TestPetrolCar,TestElectricCar): def setUp(self): self.car = HybridCar() # this tests the default constructor def test_hybrid_default_constructor(self): self.assertEqual(False, self.car.electric_brake_regeneration) # this tests the getter functionality def test_hybrid_getter(self): self.assertEqual(False, self.car.electric_brake_regeneration) # this tests the setter functionality def test_hybrid_setter(self): self.car.setBrake(True) self.assertEqual(True, self.car.getBrake()) if __name__ == '__main__': unittest.main()
7dfab631ae6616dc1c5b51706e2276016cf69a2d
WillOsoc/CursoPython
/10_Condicionales.py
301
3.796875
4
print("Programa de Evaluación") nota_alumno=input("Introduce la nota: ") #todo input es considerado un string def evaluacion(nota): val01="Aprobado" #variables pertenecen solo a su ámbito if nota<5: val01="Reprobado" return val01 print("El alumno ha sido: " + evaluacion(int(nota_alumno)))
4d0b91940897d697178551f4624909f7ea4336fb
chloesheen/NSW-classifier
/NSW.py
2,957
4.28125
4
# Name: Chloe Sheen # CMSC208 Assignment 5 # Fall 2017 # Example text as a string. mytext = """NSWs must be classified for phonetic analysis. This is especially important in the case of numbers, which differ in their pronunciation depending on their category. For example, it is necessary to distinguish a year like 1849 from a PIN like 3269. Phone numbers come in variable forms like 234-6529 or 492-499-1349 or (203)893-5938. Zip codes can also vary between 29481 or 49381-2395. Below shouldn't be a PHONE NUMBER (818)279-59021. Below is a ZIP CODE 19010. Below is a YEAR 1996. PASSED ALL TESTS.""" # Strips periods from sentence-final words. def remove_punctuation(text): return [w[:-1] if w[-1] == '.' else w for w in text] # Returns true iff string c is a single digit def is_digit(c): return c in '0123456789' # Returns true iff string w consists of all digits. def is_string_of_digits(w): for c in w: if not is_digit(c): return False return True # Returns true iff string w is of the form XXXXX or XXXXX-XXXX where X is a digit. def is_zip(w): if len(w) == 5 or len(w) == 10: if len(w) == 10: zlist = [] for i in enumerate(w): zlist.append(i) zdict = dict(zlist) if zdict[5] == '-': return True return is_string_of_digits(w) return False # Identify phone numbers. def is_phone(w): if len(w) >= 8 and len(w)<13: plist = [] numlist = ['0','1','2','3','4','5','6','7','8','9'] for i in enumerate(w): plist.append(i) pdict = dict(plist) if pdict[1] in numlist and pdict[3] not in numlist or pdict[0] is '(': return True return is_string_of_digits(w) return False # Suggested approach to distinguishing years from PINs. # Returns true iff string word is found in list wordlist within scan_range positions (left or right) of start_pos. def scan(w, wordlist, word, start_pos, scan_range): numlist = ['0','1','2','3','4','5','6','7','8','9'] if len(w) == 4: if is_string_of_digits(w) is True: idx = (i for i,w in enumerate(wordlist) if w==word) neighbors = [] for i in idx: neighbors.append(wordlist[start_pos-scan_range:start_pos] + wordlist[start_pos+1:start_pos+scan_range]) for j in range(0,scan_range): if neighbors[0][j] == word: return True return False # Takes a text t as a list of words with sentence-final punctuation removed and returns that text with markup for the following NSW categories: zip codes, phone numbers, years, and PINs. def NSW_markup(t): markedup = [] i = 0 while i < len(t): if is_zip(t[i]): print '<zip>', t[i], '</zip>' elif is_phone(t[i]): print '<phone>', t[i], '</phone>' elif scan(t[i], t, "PIN", i, 2): print '<pin>', t[i], '</pin>' elif scan(t[i], t, "PIN", i, 2) is False and is_string_of_digits(t[i]) is True: print '<year>', t[i], '</year>' else: print t[i] i+=1 return markedup def demo(): print NSW_markup(remove_punctuation(mytext.split())) if __name__ == '__main__': demo()
822092290af328d26c9e097e83f0048f7e09d226
CatalinMB/Python-work
/files.py
1,944
3.703125
4
import time # Open a file try: # line = fHandle.readline() # for line in fHandle.readlines(): # print(line.rstrip("\n")) # allLines = fHandle.readlines() # print(len(allLines)) # allLinesAsAString = fHandle.read() # print(type(allLinesAsAString)) # print(fHandle.readline()) # print(next(fHandle)) # fHandle = open("test.txt","w") with open("test.txt","a") as handle: while True: newLine = input(":") if newLine != "\q": handle.write(newLine+"\n") if newLine == "\q": break # linenr = 1 # # for line in fHandle.readlines(): # print("[" + str(linenr) +"]", line.rstrip()) # startTime = time.time() # # for i in range (100): # fHandle.write(str(i) + "\n") # # print("Time elapsed: ", time.time() - startTime) # while True: # # # print("Awsome file Reader") # print("......................") # print("1) Read 1 line") # print("2) Read all lines") # print("3) Search for word") # print("4) quit") # # i = input("Please choose an option: "); # # if i== "1": # fHandle = open("test.txt") # print(fHandle.readline()) # fHandle.close() # elif i== "2": # print(fHandle.readlines()) # elif i== "3": # # # Linear search # word = input("Please input a word to search for:") # fHandle = open("test.txt") # for line in fHandle.readline(): # if word in line: # print("We found your word: ", "["+line+"]") # fHandle.close() # # elif i== "4": # print("Quitting...") # break # else: # print("Invalid choice") except FileNotFoundError: print("File does not exist")
6618d400dd80fe182ed305dbc06969154fbcb945
sayalipawade/Python-Programs
/encapsulation.py
647
3.90625
4
<<<<<<< HEAD #If you want to access and change the private variables, accessor (getter) methods #and mutators(setter methods) should be used, as they are part of Class. ======= >>>>>>> Swap_Nibbles class Person: def __init__(self, name, age): self.name = name self.__age = age def display(self): print(self.name) print(self.__age) def setAge(self, age): self.__age = age def getAge(self): print(self.__age) #Creating object of class person = Person('sayali', 23) #accessing using class method person.display() #changing age using setter person.setAge(24) person.getAge()
f9c980ee8e90bf1b89cab106e99859b441418c61
try-your-best/leetcode_py
/string_pkg/valid-palindrome-ii.py
821
3.5625
4
class Solution: def validPalindrome(self, s: str) -> bool: i = 0 j = len(s) - 1 # print(len(s)) # print(s[0:22]) # print(s[80:len(s)]) while i < j: if s[i] == s[j]: i += 1 j -= 1 else: return self.isValid(s, i+1, j) or self.isValid(s, i, j-1) return True def isValid(self, s, left, right): while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True if __name__ == '__main__': sl =Solution() print(sl.validPalindrome('aba')) print(sl.validPalindrome('abca')) print(sl.validPalindrome('abcaca')) print(sl.validPalindrome('abcbaca')) s = "aguokepatgbnvfqmgmlcupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupuculmgmqfvnbgtapekouga" print(sl.validPalindrome(s)) # print(s[19:82]) # print(sl.validPalindrome(s[19:82]))
1c4a001b9ead976e0300907bc55642bba2b061ac
morphatic/isat252s20_04
/python/fizzbuzz/fizzbuzz.py
1,190
4.125
4
"""A FizzBuzz program""" # import necessary supporting libraries from numbers import Number def fizz(x): """ Checks to see if the input `x` is numeric and a multiple of 3. If it is, it outputs 'Fizz'. Otherwise, it outputs the input. """ return 'Fizz' if isinstance(x, Number) and x % 3 == 0 else x def buzz(x): """ Checks to see if the input `x` is numeric and a multiple of 5. If it is, it outputs 'Buzz'. Otherwise, it outputs the input. """ return 'Buzz' if isinstance(x, Number) and x % 5 == 0 else x def fibu(x): """ Checks to see if the input `x` is numeric and a multiple of 15. If it is, it outputs 'FizzBuzz'. Otherwise, it outputs the input. """ return 'FizzBuzz' if isinstance(x, Number) and x % 15 == 0 else x def play(start, end): """ Given a start number and an end number, play FizzBuzz starting at `start` and ending at `end` and output the results as a list (array). """ # initialize an empty collection to hold our output output = [] # loop through the numbers from start to end for x in range(start, end + 1): output.append(buzz(fizz(fibu(x)))) # return the output return output
ad182e23cbcc4830d54daee57791e02f24a9199d
fplucas/exercicios-python
/estrutura-de-repeticao/1.py
224
4.0625
4
valor_invalido = True while(valor_invalido): nota = float(input('Entre com uma nota de zero a dez: ')) if(nota > 0 and nota < 10): valor_invalido = False else: print('Entre com um valor válido!')
24827a07f9f799c8dc0ac5d34c77a6db88a1dc61
OmkarPatkar/Python-Matplotlib
/2 - bar graph/csv file/count.py
1,015
3.796875
4
import csv import numpy as np from collections import Counter from matplotlib import pyplot as plt #styling the graph plt.style.use('seaborn') #read csv file with open('data.csv') as csv_file: csv_reader = csv.DictReader(csv_file) #to count the itteration of each item language_counter = Counter() for row in csv_reader: language_counter.update(row['LanguagesWorkedWith'].split(';')) #print most common languages print(language_counter.most_common(15)) languages = [] popularity = [] for item in language_counter.most_common(15): languages.append(item[0]) popularity.append(item[1]) print(languages) print(popularity) #to get the most used programming language on top languages.reverse() popularity.reverse() #barh - to get the horizontal bar graph plt.barh(languages, popularity) plt.title("Most Popular Programming Languages") plt.xlabel("Number of People") plt.ylabel("Programming Languages") plt.tight_layout() plt.savefig('count.png') plt.show()
7f408900b5306a4648dc815dff719ef13adf9b06
catchonme/algorithm
/Python/026.remove-duplicates-from-soted-array.py
423
3.53125
4
#!/usr/bin/python3 class Solution(object): def removeDumlicates(self, nums): """ :type nums: List[int] :rtype: int """ i = 0 while i < len(nums) - 1: if nums[i] == nums[i+1]: nums.pop(i) else: i += 1 return len(nums) sol = Solution() res = sol.removeDumlicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]) print(res)
ad708394ce6288656199c86d22daeb4f282c279e
kaelinh/csc211
/hw/hw1/hw1.py
24,804
3.921875
4
#---------------------------------------------------------------------- # Problem 204 #---------------------------------------------------------------------- # # Create a function named myfunc with two parameters: x and y. # # It should: # # 1. Add the parameters # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function myfunc goes BELOW here #------------- def myfunc(x, y): z = x + y return z #------------- # Your code for the function myfunc goes ABOVE here # # Below are some tests for your function myfunc. All of these # tests should pass. You don't need to change this test code. assert myfunc(7,1) == 8 assert myfunc(7,3) == 10 assert myfunc(11,8) == 19 assert myfunc(11,11) == 22 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 205 #---------------------------------------------------------------------- # # Create a function named func with two parameters: x and y. # # It should: # # 1. Subtract the first parameter from the second # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function func goes BELOW here #------------- def func(x, y): z = y - x return z #------------- # Your code for the function func goes ABOVE here # # Below are some tests for your function func. All of these # tests should pass. You don't need to change this test code. assert func(14,10) == -4 assert func(14,1) == -13 assert func(3,16) == 13 assert func(3,15) == 12 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 206 #---------------------------------------------------------------------- # # Create a function named myfunc with two parameters: a and y. # # It should: # # 1. Subtract the second parameter from the first # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function myfunc goes BELOW here #------------- def myfunc(a, y): z = a - y return z #------------- # Your code for the function myfunc goes ABOVE here # # Below are some tests for your function myfunc. All of these # tests should pass. You don't need to change this test code. assert myfunc(18,2) == 16 assert myfunc(18,19) == -1 assert myfunc(8,8) == 0 assert myfunc(8,1) == 7 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 207 #---------------------------------------------------------------------- # # Create a function named myfunc with two parameters: a and y. # # It should: # # 1. Divide the first parameter by the second # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function myfunc goes BELOW here #------------- def myfunc(a, y): z = a / y return z #------------- # Your code for the function myfunc goes ABOVE here # # Below are some tests for your function myfunc. All of these # tests should pass. You don't need to change this test code. assert myfunc(1,9) == 0.1111111111111111 assert myfunc(1,5) == 0.2 assert myfunc(5,16) == 0.3125 assert myfunc(5,11) == 0.45454545454545453 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 208 #---------------------------------------------------------------------- # # Create a function named myfunc with two parameters: a and y. # # It should: # # 1. Multiply the parameters # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function myfunc goes BELOW here #------------- def myfunc(a, y): z = a * y return z #------------- # Your code for the function myfunc goes ABOVE here # # Below are some tests for your function myfunc. All of these # tests should pass. You don't need to change this test code. assert myfunc(14,3) == 42 assert myfunc(14,12) == 168 assert myfunc(6,19) == 114 assert myfunc(6,14) == 84 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 209 #---------------------------------------------------------------------- # # Create a function named this_function with two parameters: a and y. # # It should: # # 1. Add the parameters # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function this_function goes BELOW here #------------- def this_function(a, y): z = a + y return z #------------- # Your code for the function this_function goes ABOVE here # # Below are some tests for your function this_function. All of these # tests should pass. You don't need to change this test code. assert this_function(9,17) == 26 assert this_function(9,19) == 28 assert this_function(1,3) == 4 assert this_function(1,18) == 19 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 210 #---------------------------------------------------------------------- # # Create a function named this_function with two parameters: a and y. # # It should: # # 1. Divide the second parameter by the first # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function this_function goes BELOW here #------------- def this_function(a, y): z = y / a return z #------------- # Your code for the function this_function goes ABOVE here # # Below are some tests for your function this_function. All of these # tests should pass. You don't need to change this test code. assert this_function(2,7) == 3.5 assert this_function(2,16) == 8.0 assert this_function(12,17) == 1.4166666666666667 assert this_function(12,16) == 1.3333333333333333 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 211 #---------------------------------------------------------------------- # # Create a function named this_function with two parameters: a and y. # # It should: # # 1. Divide the first parameter by the second # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function this_function goes BELOW here #------------- def this_function(a, y): z = a / y return z #------------- # Your code for the function this_function goes ABOVE here # # Below are some tests for your function this_function. All of these # tests should pass. You don't need to change this test code. assert this_function(12,6) == 2.0 assert this_function(12,12) == 1.0 assert this_function(1,15) == 0.06666666666666667 assert this_function(1,5) == 0.2 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 212 #---------------------------------------------------------------------- # # Create a function named g with two parameters: a and y. # # It should: # # 1. Divide the first parameter by the second # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function g goes BELOW here #------------- def g(a, y): z = a / y return z #------------- # Your code for the function g goes ABOVE here # # Below are some tests for your function g. All of these # tests should pass. You don't need to change this test code. assert g(2,6) == 0.3333333333333333 assert g(2,10) == 0.2 assert g(10,10) == 1.0 assert g(10,7) == 1.4285714285714286 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 213 #---------------------------------------------------------------------- # # Create a function named g with two parameters: a and y. # # It should: # # 1. Subtract the second parameter from the first # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function g goes BELOW here #------------- def g(a, y): z = a - y return z #------------- # Your code for the function g goes ABOVE here # # Below are some tests for your function g. All of these # tests should pass. You don't need to change this test code. assert g(17,6) == 11 assert g(17,5) == 12 assert g(6,19) == -13 assert g(6,12) == -6 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 214 #---------------------------------------------------------------------- # # Create a function named g with two parameters: a and y. # # It should: # # 1. Divide the second parameter by the first # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function g goes BELOW here #------------- def g(a, y): z = y / a return z #------------- # Your code for the function g goes ABOVE here # # Below are some tests for your function g. All of these # tests should pass. You don't need to change this test code. assert g(10,4) == 0.4 assert g(10,18) == 1.8 assert g(9,16) == 1.7777777777777777 assert g(9,13) == 1.4444444444444444 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 215 #---------------------------------------------------------------------- # # Create a function named func with two parameters: b and z. # # It should: # # 1. Subtract the second parameter from the first # # 2. Save that value in a variable count # # 3. Return the variable count # # Your code for the function func goes BELOW here #------------- def func(b, z): x = b - z return x #------------- # Your code for the function func goes ABOVE here # # Below are some tests for your function func. All of these # tests should pass. You don't need to change this test code. assert func(2,18) == -16 assert func(2,11) == -9 assert func(13,4) == 9 assert func(13,8) == 5 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 216 #---------------------------------------------------------------------- # # Create a function named func with two parameters: b and z. # # It should: # # 1. Subtract the first parameter from the second # # 2. Save that value in a variable count # # 3. Return the variable count # # Your code for the function func goes BELOW here #------------- def func(b, z): r = z - b return r #------------- # Your code for the function func goes ABOVE here # # Below are some tests for your function func. All of these # tests should pass. You don't need to change this test code. assert func(13,4) == -9 assert func(13,14) == 1 assert func(19,14) == -5 assert func(19,15) == -4 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 217 #---------------------------------------------------------------------- # # Create a function named func with two parameters: b and z. # # It should: # # 1. Divide the second parameter by the first # # 2. Save that value in a variable count # # 3. Return the variable count # # Your code for the function func goes BELOW here #------------- def func(b, z): u = z / b return u #------------- # Your code for the function func goes ABOVE here # # Below are some tests for your function func. All of these # tests should pass. You don't need to change this test code. assert func(13,6) == 0.46153846153846156 assert func(13,16) == 1.2307692307692308 assert func(8,1) == 0.125 assert func(8,13) == 1.625 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 218 #---------------------------------------------------------------------- # # Create a function named g with two parameters: b and z. # # It should: # # 1. Divide the first parameter by the second # # 2. Save that value in a variable count # # 3. Return the variable count # # Your code for the function g goes BELOW here #------------- def g(b, z): p = b / z return p #------------- # Your code for the function g goes ABOVE here # # Below are some tests for your function g. All of these # tests should pass. You don't need to change this test code. assert g(5,7) == 0.7142857142857143 assert g(5,19) == 0.2631578947368421 assert g(17,12) == 1.4166666666666667 assert g(17,6) == 2.8333333333333335 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 219 #---------------------------------------------------------------------- # # Create a function named g with two parameters: b and z. # # It should: # # 1. Add the parameters # # 2. Save that value in a variable count # # 3. Return the variable count # # Your code for the function g goes BELOW here #------------- def g(b, z): w = b + z return w #------------- # Your code for the function g goes ABOVE here # # Below are some tests for your function g. All of these # tests should pass. You don't need to change this test code. assert g(1,9) == 10 assert g(1,11) == 12 assert g(16,9) == 25 assert g(16,2) == 18 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 220 #---------------------------------------------------------------------- # # Create a function named g with two parameters: b and z. # # It should: # # 1. Subtract the first parameter from the second # # 2. Save that value in a variable count # # 3. Return the variable count # # Your code for the function g goes BELOW here #------------- def g(b, z): t = z - b return t #------------- # Your code for the function g goes ABOVE here # # Below are some tests for your function g. All of these # tests should pass. You don't need to change this test code. assert g(16,11) == -5 assert g(16,5) == -11 assert g(19,2) == -17 assert g(19,18) == -1 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 221 #---------------------------------------------------------------------- # # Create a function named a_function with two parameters: b and z. # # It should: # # 1. Divide the second parameter by the first # # 2. Save that value in a variable count # # 3. Return the variable count # # Your code for the function a_function goes BELOW here #------------- def a_function(b, z): g = z / b return g #------------- # Your code for the function a_function goes ABOVE here # # Below are some tests for your function a_function. All of these # tests should pass. You don't need to change this test code. assert a_function(19,13) == 0.6842105263157895 assert a_function(19,11) == 0.5789473684210527 assert a_function(4,9) == 2.25 assert a_function(4,18) == 4.5 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 222 #---------------------------------------------------------------------- # # Create a function named a_function with two parameters: b and z. # # It should: # # 1. Add the parameters # # 2. Save that value in a variable count # # 3. Return the variable count # # Your code for the function a_function goes BELOW here #------------- def a_function(b, z): y = b + z return y #------------- # Your code for the function a_function goes ABOVE here # # Below are some tests for your function a_function. All of these # tests should pass. You don't need to change this test code. assert a_function(9,8) == 17 assert a_function(9,4) == 13 assert a_function(11,18) == 29 assert a_function(11,15) == 26 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 223 #---------------------------------------------------------------------- # # Create a function named a_function with two parameters: b and z. # # It should: # # 1. Subtract the second parameter from the first # # 2. Save that value in a variable count # # 3. Return the variable count # # Your code for the function a_function goes BELOW here #------------- def a_function(b, z): i = b - z return i #------------- # Your code for the function a_function goes ABOVE here # # Below are some tests for your function a_function. All of these # tests should pass. You don't need to change this test code. assert a_function(2,10) == -8 assert a_function(2,6) == -4 assert a_function(19,3) == 16 assert a_function(19,11) == 8 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 224 #---------------------------------------------------------------------- # # Create a function named myfunc with two parameters: c and y. # # It should: # # 1. Subtract the second parameter from the first # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function myfunc goes BELOW here #------------- def myfunc(c, y): z = c - y return z #------------- # Your code for the function myfunc goes ABOVE here # # Below are some tests for your function myfunc. All of these # tests should pass. You don't need to change this test code. assert myfunc(9,1) == 8 assert myfunc(9,6) == 3 assert myfunc(5,6) == -1 assert myfunc(5,17) == -12 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 225 #---------------------------------------------------------------------- # # Create a function named myfunc with two parameters: c and y. # # It should: # # 1. Divide the first parameter by the second # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function myfunc goes BELOW here #------------- def myfunc(c, y): z = c / y return z #------------- # Your code for the function myfunc goes ABOVE here # # Below are some tests for your function myfunc. All of these # tests should pass. You don't need to change this test code. assert myfunc(18,6) == 3.0 assert myfunc(18,18) == 1.0 assert myfunc(10,3) == 3.3333333333333335 assert myfunc(10,7) == 1.4285714285714286 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 226 #---------------------------------------------------------------------- # # Create a function named myfunc with two parameters: c and y. # # It should: # # 1. Subtract the first parameter from the second # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function myfunc goes BELOW here #------------- def myfunc(c, y): z = y - c return z #------------- # Your code for the function myfunc goes ABOVE here # # Below are some tests for your function myfunc. All of these # tests should pass. You don't need to change this test code. assert myfunc(6,3) == -3 assert myfunc(6,7) == 1 assert myfunc(5,9) == 4 assert myfunc(5,8) == 3 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 227 #---------------------------------------------------------------------- # # Create a function named my_function with two parameters: c and y. # # It should: # # 1. Subtract the first parameter from the second # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function my_function goes BELOW here #------------- def my_function(c, y): z = y - c return z #------------- # Your code for the function my_function goes ABOVE here # # Below are some tests for your function my_function. All of these # tests should pass. You don't need to change this test code. assert my_function(17,6) == -11 assert my_function(17,16) == -1 assert my_function(8,18) == 10 assert my_function(8,4) == -4 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 228 #---------------------------------------------------------------------- # # Create a function named my_function with two parameters: c and y. # # It should: # # 1. Subtract the second parameter from the first # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function my_function goes BELOW here #------------- def my_function(c, y): z = c - y return z #------------- # Your code for the function my_function goes ABOVE here # # Below are some tests for your function my_function. All of these # tests should pass. You don't need to change this test code. assert my_function(1,16) == -15 assert my_function(1,18) == -17 assert my_function(3,16) == -13 assert my_function(3,8) == -5 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 229 #---------------------------------------------------------------------- # # Create a function named my_function with two parameters: c and y. # # It should: # # 1. Divide the second parameter by the first # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function my_function goes BELOW here #------------- def my_function(c, y): z = y / c return z #------------- # Your code for the function my_function goes ABOVE here # # Below are some tests for your function my_function. All of these # tests should pass. You don't need to change this test code. assert my_function(6,19) == 3.1666666666666665 assert my_function(6,9) == 1.5 assert my_function(19,17) == 0.8947368421052632 assert my_function(19,9) == 0.47368421052631576 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 230 #---------------------------------------------------------------------- # # Create a function named g with two parameters: c and y. # # It should: # # 1. Divide the second parameter by the first # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function g goes BELOW here #------------- def g(c, y): z = y /c return z #------------- # Your code for the function g goes ABOVE here # # Below are some tests for your function g. All of these # tests should pass. You don't need to change this test code. assert g(12,19) == 1.5833333333333333 assert g(12,10) == 0.8333333333333334 assert g(14,1) == 0.07142857142857142 assert g(14,7) == 0.5 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 231 #---------------------------------------------------------------------- # # Create a function named g with two parameters: c and y. # # It should: # # 1. Subtract the second parameter from the first # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function g goes BELOW here #------------- def g(c, y): z = c - y return z #------------- # Your code for the function g goes ABOVE here # # Below are some tests for your function g. All of these # tests should pass. You don't need to change this test code. assert g(18,8) == 10 assert g(18,4) == 14 assert g(16,4) == 12 assert g(16,14) == 2 #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Problem 232 #---------------------------------------------------------------------- # # Create a function named g with two parameters: c and y. # # It should: # # 1. Multiply the parameters # # 2. Save that value in a variable z # # 3. Return the variable z # # Your code for the function g goes BELOW here #------------- def g(c, y): z = c * y return z #------------- # Your code for the function g goes ABOVE here # # Below are some tests for your function g. All of these # tests should pass. You don't need to change this test code. assert g(2,12) == 24 assert g(2,8) == 16 assert g(8,8) == 64 assert g(8,15) == 120 #---------------------------------------------------------------------- 232
1a9980b2cc417f18e46362b1962ee0ebd3e792ff
unaiz123/luminarpython
/Collections/introduction/listdemo/binarysearch.py
377
3.765625
4
lst=[10,11,12,13,15,2,3,5,6] lst.sort() print(lst) low=0 upp=len(lst)-1 element=int(input("enter found element : ")) flg=0 while(low<=upp): mid=(low+upp)//2 if(element>lst[mid]): low=mid+1 elif(element<lst[mid]): upp=mid-1 elif(element==lst[mid]): flg+=1 break if(flg>0): print("element found") else: print("not found")
47b8b34ad9cafd5584dd65615929c31a7edaa585
floydchenchen/leetcode
/905-sort-array-by-parity.py
649
3.96875
4
# 905. Sort Array By Parity # Given an array A of non-negative integers, return an array consisting of all the even elements of A, # followed by all the odd elements of A. # # You may return any answer array that satisfies this condition. class Solution: def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ # even and orr pointers for the array l, r = 0, len(A) - 1 while l < r: while A[l] % 2 == 0 and l < r: l += 1 while A[r] % 2 == 1 and l < r: r -= 1 A[l], A[r] = A[r], A[l] return A
51e464bc81504db4b8e556a8a4b6327a0e1c40b3
BennoStaub/CodingInterview
/Sort/insertionsort.py
513
3.859375
4
class InsertionSort(): def __init__(self, input_list): self.list = input_list def sort(self): for i in xrange(1, len(self.list)): next_element = self.list[i] while self.list[i-1] > next_element and i-1 >= 0: self.list[i] = self.list[i-1] self.list[i-1] = next_element i -= 1 print(self.list) list = [1,7,3,5,89,4,3,2,4,5,6,7,9,78,6,3,2,56,67,4] Sort = InsertionSort(list) Sort.sort()
b2281bd55f219cc20e15450af09a517534de42eb
DostonKayimov/learnpython
/assignment#3_dostonkay.py
799
3.796875
4
#Yearly expenses($) to study in dream University total_fees = 28000 my_yearly_income = 2000 if_I_rob_bank = 25000 if total_fees > my_yearly_income: print("Not that bad! Keep working and you will be applying with your children") if total_fees < my_yearly_income: print("Congrats! pack your stuff right away") if total_fees > if_I_rob_bank: print("You almost had ti! Welcome to prison") if total_fees < if_I_rob_bank: print("Ok, you have 24 hours to leave the country") if_I_rob_bank += 5000 if total_fees >= if_I_rob_bank: print("You almost had ti! Welcome to prison") if total_fees <= if_I_rob_bank: print("Ok, you have 24 hours to leave the country") if total_fees == if_I_rob_bank: print("Be quick, you dont have much time to leave")
464ae45926da454c084e780c7ae20d0521f70b7a
kyeongminlee/python-mannaEdu
/source/ex02.py
177
3.5625
4
import sys args = sys.argv[1:] for i in args: print(i.upper(), end=' ') # 명령 프롬프트를 실행한 후 아래 명령어를 실행한다. # python ex02.py i love you
c8aa9c40d811e7c302711f32edb49a742f4963cb
arinablake/python-selenium-automation
/hw_algorithms_5/hw_5_2.py
794
4.3125
4
# Вводится ненормированная строка, у которой могут быть пробелы в начале, в конце и между словами более одного пробела. # Привести ее к нормированному виду, т.е. удалить все пробелы в начале и конце, а между словами оставить только один пробел. ' Enter some abnormal string ' def clean_string(string): clean_beg_end = string.strip(' ') array = clean_beg_end.split(' ') result = [] for item in array: if not item == '': result.append(item) return ' '.join(result) print(clean_string(' Enter some abnormal string '))
4f8d3055121c128f2df83d72d864184608b328e0
s-markov/geekbrains-python-level1
/les05/task05_04/task05_04.py
1,240
3.5
4
# Создать (не программно) текстовый файл со следующим содержимым: # # One — 1 # Two — 2 # Three — 3 # Four — 4 # Необходимо написать программу, открывающую файл на чтение # и считывающую построчно данные. При этом английские числительные # должны заменяться на русские. # Новый блок строк должен записываться в новый текстовый файл. my_en_ru_dict = {'One': 'Один', 'Two': 'Два', 'Three': 'Три', 'Four': 'Четыре'} output_file_dict={} my_file = open(r"task05_04.txt", 'r') output_file = open(r"out05_04.txt", 'w') my_file_dict = {str_word.split()[0]: str_word.strip('\n').split()[2] for str_word in my_file.readlines()} print(my_file_dict) for en_key, en_value in my_file_dict.items(): for en_ru_key, ru_value in my_en_ru_dict.items(): if en_key == en_ru_key: output_file_dict[ru_value] = en_value print(output_file_dict) for ru_key, ru_value in output_file_dict.items(): output_file.write(f'{ru_key} - {ru_value}\n') my_file.close() output_file.close()
a55f66b451d4871e6625b0d756c788543a9557d9
nileshpandit009/practice
/BE/Part-I/Python/BE_A_55/assignment1_3.py
222
4.0625
4
my_list = input("Enter numbers separated by spaces\n").split(" ") try: my_list = [int(x) for x in my_list] print("Max number is %f" % max(my_list)) except ValueError: print("Not all items are numbers")
595b01d91230e09d202ffd8fa378f814c1725852
bs980201/leetcode
/173_Binary_Search_Tree_Iterator.py
1,038
3.890625
4
"""173_Binary_Search_Tree_Iterator.py.""" class TreeNode: """Definition for a binary tree node.""" def __init__(self, x): """Init.""" self.val = x self.left = None self.right = None class Stack: """Stack.""" def __init__(self): """Init.""" self.items = [] def isEmpty(self): """IsEmpty.""" return self.items == [] def push(self, item): """Push.""" self.items.append(item) def pop(self): """Pop.""" self.items.pop() class BSTIterator: """BSTIterator.""" def __init__(self, root): """Init.""" self.s = Stack() self._putall(root) def hasNext(self): """Hasnext.""" return not self.s.isEmpty() def next(self): """Next.""" tempnode = self.s.pop() self._putall(tempnode.right) return tempnode.val def _putall(self, node): while node is not None: self.s.push(node) node = node.left
22c960e9eacb7cc3a380ced45d4aca6bcce1d800
fedgut/daily-challenge
/Hackerrank/python3 cavity_map.py
482
3.578125
4
def cavityMap(grid): import math n = int(math.sqrt(len(grid))) for indx in range (n , len(grid)-n): if indx % n != 0 and (indx % n) +1 != n: if grid[indx - n] and grid[indx - 1] != 'X': if grid[indx] > grid[indx-n] and grid[indx] > grid[indx+n] and grid[indx] > grid[indx-1] and grid[indx] > grid[indx+1]: grid[indx] = 'X' return grid print(cavityMap([1, 1, 1, 2, 1, 9, 1, 2, 1, 8, 9, 2, 1, 2, 3, 4]))
a8fdd47794ce6ef9b99e63fcc8b4659ac2587c0e
SoloMessiah/LA-2
/stamp_program.py
420
3.59375
4
""" Start Get numbers of sheets Sheets / 5 Round answer to next number Output to user End """ def calculate(sheet): answer = sheet / 5 rounded_answer = round(answer) print("Sheet is: ", sheet) print("The answer is: ", answer) print("Rounded is: ", rounded_answer) print("=====================") return rounded_answer output = calculate(1000) print("The return statement is: ", output)
8ee3398b03f58d1026d0118681228908c1ebeb93
lukamanitta/Coding-Challenges
/PolarCoordinates/solution.py
1,029
3.78125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT from math import * from test_cases.py import tests, answers #compNumber = input() def main(compNumber): #Needs to deal with negative numbers - turn string into negative number if(compNumber.find('+')): compNumber = compNumber.split('+') compNumber[1] = compNumber[1].replace('j','') elif(compNumber.find('-')): compNumber = compNumber.split('-') compNumber[1] = compNumber[1].replace('j','') re = int(compNumber[0]) im = int(compNumber[1]) mag = sqrt(re**2 + im**2) arg = atan2(im, re) if(arg > pi): arg = -1 * arg - pi return mag, arg #print(mag) #print(arg) for index, test in enumerate(tests): main(test) if main(test) == answers[index]: print(f'Passed test {index}: {main(test)}') if main(test) != answers[index]: print(f'Failed test {index}\nExpected answer: {answers[index]}\nGiven answer: {main(test)}')
192a68d25e4f12529e3a61b7982ad831ddced1ab
Koyter/geekbrains_hw
/lesson_4/lesson_1_3.py
74
3.5
4
print([item for item in range(20, 241) if item % 20 ==0 or item % 21 ==0])
6829749ba551965e77f6554aa347b200b514888d
katefranks/python_hangman_game
/hangman.py
1,761
3.984375
4
def hangman(): word = "dulce" word_list = ["d", "u", "l", "c", "e"] word_list2 = ["_", "_", "_", "_", "_"] guesses = "" turns = 10 failed = 0 while turns > 0: guess = input("Guess a letter! ") if guess in word: failed = 0 turns -= 1 guesses += guess print(f"Good guess! You have {turns} guesses left. Current guesses: {guesses}") # print(word_list2) for index, char in enumerate(word_list): # if the char is the guess # then update the index in the word_list2 to be that char if char == guess: word_list2[index] = guess print(word_list2) elif guess not in word: failed += 1 turns -= 1 guesses += guess print(f"Wrong! Guess again! You have {turns} guesses left. Current guesses: {guesses}") print(word_list2) if word_list2 == word_list: print("You won the game! \U0001F929") if turns < 1: print("You are out of guesses! Game over! \U0001F622") # if turns != 0 and failed == 0: # print("You win!") hangman() #figure out all of the places that the char exists in the word #find all of the positiions of where it's in the word #update the correct position in the list to be that guess #IDEAS WHEN REFACTORING: # def play(): # hangman = 'boolean' # blank = ['_'] * len(hangman) # elif guessed_word in blank: # print('Sorry you already guessed that letter') # word = input('Player1: Please enter a lowercase word: ') *use method to convert to lowercase just incase user does not follow directions! #
ae3640987a6674be2e785ab9f70a8c0d944e0e98
RichieSong/algorithm
/算法/数组/有序数组中找到指定的值.py
654
3.75
4
# -*- coding: utf-8 -*- """ 如何在有序数组中指定的元素的第一个位置? 1、直接变量一遍 时间复杂度O(n) 2、二分查找 O(logn) """ def binarySearch(nums, value): l, r = 0, len(nums) - 1 while l <= r: mid = l + ((r - l) >> 1) if nums[mid] > value: r = mid - 1 elif nums[mid] < value: l = mid + 1 else: while mid != -1: if nums[mid - 1] != value: return mid mid -= 1 return -1 if __name__ == '__main__': nums = [1, 2, 3, 4, 5, 6, 90, 90, 90, 90, 100] print binarySearch(nums, 90)
3d03712b8c94137f5b40640e3cb1b5ab00fa8963
jimlawton/euler
/007.py
370
3.625
4
""" Project Euler Problem 7 ======================= By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? """ from utils import isprime INDEX = 10001 nprimes = 0 i = 1 while True: if isprime(i): nprimes += 1 if nprimes == INDEX + 1: break i += 1 print i
e1ca60e880dea8181cc49a35688f6b2f86acb8c9
return007/computer-vision-basics
/Tutorial2.py
566
3.671875
4
# Tutorial 2 : Video capture and display using webcam import cv2 import numpy as np import matplotlib.pyplot as plt cap = cv2.VideoCapture(0) # 0 means attached webcam # 1 means USB camera while True : ret, frame = cap.read() # ret is True or False, depending on the state of the frame read cv2.imshow('Video capture', frame) # display the image captured from the webcam key = cv2.waitKey(1) if key & 0xFF == ord('q') : # exit capturing mode when q is pressed break cap.release() #release the capture cv2.destroyAllWindows() # destroy all windows
9e0d4c925679521fd36c1b6f9e4882add0e8e0a6
antoniorcn/fatec-2019-1s
/djd-prog2/noite/aula4/teste_decisao_temp.py
231
4.09375
4
temp = int(input('Digite a temperatura')) if temp > 30: print("Esta muito quente") elif temp > 25: print("Esta quente") elif temp > 15: print("Agradavel") elif temp >= 0: print("Frio") else: print("Muito Frio")
c72b9b52c9b7bac493dff96b262c208005ec25cc
ConceptCodes/CS101-labs
/test.py
1,854
3.875
4
__author__ = 'dojo' # Import turtle graphics library import turtle from math import * from random import * def random_color(turtle): screen = turtle.Screen() screen.colormode(255) r, g, b = randint(0, 255), randint(0, 255), randint(0, 255) turtle.pencolor((r,g,b)) def drawConstellation(turtle, size, height,radius,star): drawStar(turtle,size,height) for i in range(star): distance = radius turtle.fd(distance) random_color(turtle) drawStar(turtle, size/2, height/2) turtle.bk(distance) turtle.rt(45) def drawStar(turtle, size, height): drawSquareFromCenter(turtle, size) distance = size / 2 turtle.bk(distance) turtle.lt(90) turtle.bk(distance) turtle.rt(90) for i in range(4): drawIsoTriangle(turtle, size, -height) turtle.fd(size) turtle.lt(90) turtle.fd(distance) turtle.lt(90) turtle.fd(distance) turtle.rt(90) def drawIsoTriangle(turtle, base, height): side = sqrt((base / 2)**2 + height**2) angle = degrees(atan2(height, base / 2)) turtle.pendown() turtle.forward(base) turtle.left(180 - angle) turtle.forward(side) turtle.left(angle * 2) turtle.forward(side) turtle.left(180 - angle) turtle.penup() def drawSquareFromCenter(turtle, x): turtle.penup() turtle.forward(-x / 2) turtle.right(90) turtle.forward(x / 2) turtle.left(90) for i in range(4): turtle.pendown() turtle.forward(x) turtle.left(90) turtle.penup() turtle.forward(x / 2) turtle.left(90) turtle.forward(x / 2) turtle.right(90) def main(): bob = turtle.Turtle() drawConstellation(turtle,30,40) bob.speed(7) main()
89fee5740f827b783d38a119457b3ef5f0d283d3
HaroldCA/ExamenDeFP
/EjercicioN°001HTCA.py
499
3.65625
4
import os #Calcular nota final del curso de FP PU = float (input ('Ingrese nota de la primera unidad: ')) SU = float (input ('Ingrese nota de la segunda unidad: ')) TU = float (input ('Ingrese nota de la tercera unidad: ')) TF = float (input ('Ingrese nota del trabajo final:')) final=(PU * .20) + (SU * .15) + (TU * .15) + (TF * .50) if final>20: print ("Ingrese notas menores a 20") else: if final<=20: print ('El promedio final del curso de Fundamentos de programacion: ',final) print ()
60ffc0b6aaaf91cbef4b2cb28e7652f5b78aaffc
bporcel/DataStructures
/dataStructures/trees/classBinarySearchTree.py
5,832
3.796875
4
# 9 # 4 20 # 1 6 15 170 class Node: def __init__(self, value): self.value = value self.left = None self.right = None def __str__(self): string = 'value: {}\nleft: {}\nright: {}'.format( self.value, self.left, self.right) return string class BinarySearchTree: def __init__(self): self.root = None def insert(self, value): newNode = Node(value) if self.root is None: self.root = newNode else: isRemove = False currentNode = self.root previousNode = self._getPreviousNode(currentNode, value, isRemove) if value < previousNode.value: previousNode.left = newNode elif value > previousNode.value: previousNode.right = newNode def lookup(self, value): currentNode = self.root while currentNode is not None: if value == currentNode.value: return currentNode elif value < currentNode.value: currentNode = currentNode.left else: currentNode = currentNode.right return None def remove(self, value): isRemove = True previousNode = self._getPreviousNode(self.root, value, isRemove) currentNode = self.root if previousNode is None else self._getCurrentNode( value, previousNode) isLeaf = False onlyLeft = False onlyRight = False bothChilds = False if currentNode.left is None and currentNode.right is None: isLeaf = True elif currentNode.left is not None and currentNode.right is None: onlyLeft = True elif currentNode.right is not None and currentNode.left is None: onlyRight = True elif currentNode.right is not None and currentNode.left is not None: bothChilds = True if isLeaf: self._removeLeaf(previousNode, currentNode) elif onlyLeft: self._removeLeft(previousNode, currentNode) elif onlyRight: self._removeRight(previousNode, currentNode) elif bothChilds: self._removeTraversing(previousNode, currentNode) def _removeLeaf(self, previousNode, currentNode): if currentNode.value < previousNode.value: previousNode.left = None else: previousNode.right = None def _removeLeft(self, previousNode, currentNode): if currentNode.value < previousNode.value: previousNode.left = currentNode.left else: previousNode.right = currentNode.left def _removeRight(self, previousNode, currentNode): if currentNode.value < previousNode.value: previousNode.left = currentNode.right else: previousNode.right = currentNode.right def _removeTraversing(self, previousNode, currentNode): currentNodePointer = currentNode currentNode = currentNode.right left = True parentNode = None while currentNode is not None and left: if currentNode.left is None: left = False else: parentNode = currentNode currentNode = currentNode.left if currentNode.value < previousNode.value: if not left: if parentNode is not None: if parentNode.left is not None: parentNode.left = currentNode.right if currentNodePointer.left is not None: currentNode.left = currentNodePointer.left if currentNodePointer.right is not None: currentNode.right = currentNodePointer.right previousNode.left = currentNode else: if not left: if parentNode is not None: if parentNode.left is not None: parentNode.left = currentNode.right if currentNodePointer.left is not None: currentNode.left = currentNodePointer.left if currentNodePointer.right is not None: if currentNode.value != currentNodePointer.right.value: currentNode.right = currentNodePointer.right previousNode.right = currentNode def _getCurrentNode(self, value, previousNode): if previousNode is not None: if value < previousNode.value: return previousNode.left if value > previousNode.value: return previousNode.right def _getPreviousNode(self, node, value, isRemove): while node is not None: previousNode = node if value < node.value: node = node.left elif value > node.value: node = node.right if isRemove: if value == self.root.value: return None if value == node.value: return previousNode return previousNode def traverse(self, node): if node is not None: tree = {'value': node.value, 'left': None, 'right': None} tree['left'] = None if node.left == None else self.traverse( node.left) tree['right'] = None if node.right == None else self.traverse( node.right) return tree tree = BinarySearchTree() tree.insert(9) tree.insert(4) tree.insert(20) tree.insert(1) tree.insert(6) tree.insert(15) tree.insert(170) tree.insert(150) # print('LookUp -> ', tree.lookup(0)) # print('Before Remove', tree.traverse(tree.root)) tree.remove(9) print('LookUp -> ', tree.lookup(20)) print('After Remove', tree.traverse(tree.root))
efc729a75b8f59a2d0a63b66582cd6ac03980715
gauriindalkar/more-exercise
/acending order.py
160
3.828125
4
list1=[1,5,10,12,16,20] list2=[1,2,10,13,16] i=0 while i<len(list2): m=list2[i] if m not in list1: list1.append(m) i+=1 print(sorted(list1))
bbad9e85b28b7aa9eccd3050f65dede04ddc7764
kqxu1992/linux_python_learning
/python_work/cvs_json/highs_lows.py
1,069
3.53125
4
import csv from datetime import datetime from matplotlib import pyplot as plt #filename = "sitka_weather_07-2014.csv" filename = "death_valley_2014.csv" with open(filename) as f: reader = csv.reader(f) header_row = next(reader) print(header_row) for index1, column_header in enumerate(header_row): print(index1, column_header) dates, highs, lows = [], [], [] for row in reader: try: date = datetime.strptime(row[0], "%Y-%m-%d") high = int(row[1]) low = int(row[2]) except ValueError: print(date, "missing date") else: dates.append(date) highs.append(high) lows.append(low) print(highs) fig = plt.figure(dpi=128,figsize=(10,6)) #plt.figure(dpi=128,figsize=(5,3)) plt.plot(dates, highs, c="red", alpha=0.5) plt.plot(dates, lows, c="blue", alpha=0.5) plt.fill_between(dates, highs, lows, facecolor="blue", alpha=0.1) plt.title("Daily high temperatures", fontsize = 24) plt.xlabel("", fontsize =16) fig.autofmt_xdate() plt.ylabel("Temperature", fontsize = 16) plt.tick_params(axis="both",which="major",labelsize=16) plt.show()
1f3968e8762831e13b703e59dbb8503eef1debc3
synergie-asso/jeu-videal
/src/square.py
711
3.78125
4
class Square: def __init__(self, v): self.value = v self.fusion = False def __int__(self): return self.value def __add__(self, other): return self.value + other def __mul__(self, other): return self.value * other def __float__(self): return float(self.value) def ___le__(self, other): return self.value <= other def __eq__(self, other): return self.value == other def __ne__(self, other): return self.value != other def __gt__(self, other): return self.value > other def __ge__(self, other): return self.value >= other def __str__(self): return str(self.value)
728d89e9653c071263de646aa0a89808bb65545f
Abhirvalandge/Python-Practice-Programs
/Loop's/Q.37.py
108
4.1875
4
# What is the output of the following i=0 while i<3: print(i,end="") i+=1 else: print(0,end="")
6ec81376ebc2ad9fb23c1d7e97befd591d06528e
kwm94/PythonP
/Practical 2/kitwm_p02/kitwm_p02/kitwm_p02q05.py
1,237
4.53125
5
# File Name: days_in_month.py # Name: Kit Wei Min # Description: Displays the number of days in the month of a year entered by the user. # Prompts user to input the month and year. yr = int(input("Enter a year: ")) mth = int(input("Enter the month: ")) # Determines the number of days in the month of the year entered and displays the result. if mth == 1: print("January " + str(yr) + " has 31 days.") elif mth == 2: if yr % 4 == 0 and yr % 100 != 0 or yr % 400 == 0: print("February " + str(yr) + " has 29 days.") else: print("February " + str(yr) + " has 28 days.") elif mth == 3: print("March " + str(yr) + " has 31 days.") elif mth == 4: print("April" + str(yr) + "has 30 days.") elif mth == 5: print("May " + str(yr) + " has 31 days.") elif mth == 6: print("June " + str(yr) + "has 30 days.") elif mth == 7: print("July" , yr , "has 31 days.") elif mth == 8: print("August" , yr , "has 31 days.") elif mth == 9: print("September" , yr , "has 30 days.") elif mth == 10: print("October" , yr , "has 31 days.") elif mth == 11: print("November" , yr , "has 30 days.") elif mth == 12: print("December" , yr , "has 31 days.")
b0361dff570abc72b26cd13e8fc12ff2dbc55ff4
sunliuxun/repo-eulerproj
/euler_util.py
379
3.984375
4
def is_prime(x): if x < 2: return False for i in range(2, x): if x % i == 0: return False return True def sqrt(x): if x < 0: raise ValueError("sqrt func input invalid") i = 1 while i * i <= x: i *= 2 y = 0 while i > 0: if (y + i)**2 <= x: y += i i //= 2 return y
88a3687b53318c80ce56b908758c9f88d5637c22
JRHyc/Python
/Practice/compare_lists.py
708
4.0625
4
list_one = [1,2,5,6,2] list_two = [1,2,5,6,2] # list_one = [1,2,5,6,5] # list_two = [1,2,5,6,5,3] # list_one = [1,2,5,6,5,16] # list_two = [1,2,5,6,5] # list_one = ['celery','carrots','bread','milk'] # list_two = ['celery','carrots','bread','cream'] list_length = len(list_one) final_answer = "" def compare(one, two): for x in range(0, list_length): if(len(one) != len(two)): final_answer = "The two lists are not the same length" break if(one[x] != two[x]): final_answer = "The two lists are not the same" break else: final_answer = "The lists are the same" print final_answer compare(list_one, list_two)
94b9808f46c14b5d8b8f61b30d0d1c2efc469d40
yhs3434/Algorithms
/baekjun/exercise/2020DEC/6378.py
281
3.71875
4
def getAnswer(num): numStr = str(num) val = 0 for nStr in numStr: n = int(nStr) val += n if val >= 10: val = getAnswer(val) return val; while True: n = int(input()) if n == 0: break val = getAnswer(n) print(val)
27cf6807fa97fb2020f6cc393899c88fee6364e9
Aasthaengg/IBMdataset
/Python_codes/p02262/s728236013.py
671
3.578125
4
import sys def insert_sort(A, n, g): global cnt # 指定値のgからリストの大きさまで繰り返す for i in range(g, n, 1): # print(f"bef{A=}") # 最初にヒットした数値 v = A[i] j = i - g # print(f"{j=}") while 0 <= j and v < A[j]: A[j+g] = A[j] j = j - g cnt += 1 A[j+g] = v # print(f"aft{A=}") n = int(input()) A = [x for x in map(int, sys.stdin)] cnt = 0 G = [1] while n >= 3*G[-1] + 1: G.append(3*G[-1] + 1) for g in G[::-1]: insert_sort(A, n, g) print(len(G)) G.reverse() print(*G) print(cnt) for a in A: print(a)
2f3b5e65ff6211e1c4783fda4ab2b2885eecc040
dclouzada/python-520
/aula_1/main.py
669
4.0625
4
usuario = { 'nome': input('Digite seu nome'), 'idade': input('Digite sua idade'), 'email': input('Digite seu email'), } nome = usuario['nome'] print('Usuario {} cadastrado com sucesso!'.format(usuario)) exit() GRAVIDADE = 9.8 primeiro_nome = 'David' segundo_nome = 'Castro' ultimo_nome = 'Louzada' idade = '25' idade = 25 professor = True variavel = 'string' print(type(variavel)) variavel = 121 print(type(variavel)) variavel = True print(type(variavel)) exit() print('hello, word') condicao = 'David Castro Louzada' print(type(condicao)) condicao = 25 print(type(condicao)) condicao = True print(type(condicao)) if condicao: print('verdade') else: erro
fecde979f3065aaf8a86ad5ad6101751885c9104
NikhilVarghese21/AI-ML
/Python_AIML/Q9_MostRepeatedWord.py
815
4.34375
4
count = 0 word = "" maxCount = 0 words = [] # Opening Text file in read mode file = open("Text", "r") # Gets each line till end of file is reached for line in file: # Splits each line into words string = line.split(" ") # Appending each word in string to words. for s in string: words.append(s) # Checking the most repeated word in a file for i in range(0, len(words)): count = 1 # Checks for the count of ith word in the file. for j in range(i + 1, len(words)): if words[i] == words[j]: count = count + 1 # If maxCount is less than count then storing value of count in maxCount and corresponding word to variable word if count > maxCount: maxCount = count word = words[i] print("Most Repeated Word is : ", word) file.close()
b3bdb73b4addcda03ee4096b505689eee0e8fcfd
dallasmcgroarty/python
/DataStructures_Algorithms/graphs/dfs.py
922
4.1875
4
# depth first search: # algorithm to traverse a graph by going down each branch and visiting all children # before backtracking # method: # 1. make the current vertex as visited # 2. explore each adjacent vertex that is not included in the visited set class Node: def __init__(self,value): self.value = value self.adjacentNodes = [] a = Node(1) b = Node(3) c = Node(5) d = Node(6) a.adjacentNodes.append(b) a.adjacentNodes.append(d) b.adjacentNodes.append(c) c.adjacentNodes.append(d) def dfs(start, target): visitedNodes = set() stack = [start] while len(stack) > 0: node = stack.pop() if node in visitedNodes: continue visitedNodes.add(node) if node.value == target: return True for n in node.adjacentNodes: if n not in visitedNodes: stack.append(n) return False print(dfs(a,5))
97e062d4f973163917d2e3d3d548088b36019f1e
AdamBures/Machine-Learning-Projects
/linear_regression.py
638
3.78125
4
import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression #Here creating arrays of x, y time_studied = np.array([5, 15, 25, 35, 45, 55]).reshape(-1,1) scores = np.array([5, 20, 28, 40, 22, 38]).reshape(-1,1) #Precreated model from Sklearn module model = LinearRegression() #Fit x,y to model model.fit(time_studied, scores) #Matplotlib scatter for x,y then drawing the red line of the predicted values in red color plt.scatter(time_studied, scores) plt.plot(np.linspace(0,60,100).reshape(-1,1), model.predict(np.linspace(0,60,100).reshape(-1,1)), "r") plt.ylim(0,100) plt.show()
28c3e6b5963cd90dde626acab2880823c33e2a5c
rizquadnan/codeForces
/3_wayTooLongWords.py
297
3.65625
4
n = int(input()) words = [] for i in range(n): words.append(input()) for word in words: if len(word) > 10: first = word[0] last = word[-1] between = str(len(word[1:-1])) output = first + between + last print(output) else: print(word)
3860f0ea6ce99ecd994fadd7c2f6262e22f73a44
SDRLurker/starbucks
/20160823/20160823_1.py
244
3.703125
4
words = [] for N in range(int(input())): words.append(input()) words.sort() for Q in range(int(input())): word = input() rank = words.index(word) + 1 score = 0 for c in word: score += ord(c) - ord('A') + 1 score *= rank print(score)
e60e841fe236aebc85ff3a03067ea5b004de5c73
ipacharapold/sennalabs-test-candidate
/quiz2.py
400
3.625
4
import csv import os def read_csv(file): output = "" people = {} file = open(file, 'r') render = csv.reader(file) for row in render: people[row[1]] = row[0] for lname, fname in sorted(people.items()): output += "{first}{last}\n".format(first=fname, last=lname) file.close() return output if __name__ == '__main__': print(read_csv('quiz2.csv'))
a2bcfb99672ee1580bf3f0f6fff062756df7cd9d
idreesdb/Tutorials
/python/Zetcode/Python Tutorial/09 - Functions/types.py
219
3.578125
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- # types.py from math import sqrt def cube(x): return x * x * x # built in function print abs(-1) # defined function print cube(9) # external function print sqrt(81)