blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3ddd465a7ddfddba1f4bf0d987b36f7022dbeac4
x-ider/a3200-2015-algs
/lab5/Evtushenko/quicksort.py
794
3.578125
4
from sys import stdin, stdout import random def quick_sort(a, l, r): if l < r: t = partition(a, l, r) left_border, right_border = t quick_sort(a, l, left_border) quick_sort(a, right_border, r) def partition(a, l, r): pivot_id = random.randint(l, r) a[l], a[pivot_id] = a[pivot_id], a[l] j = l for i in range(l + 1, r + 1): if a[i] <= a[l]: j += 1 a[i], a[j] = a[j], a[i] a[l], a[j] = a[j], a[l] k = j for i in range(l, k - 1): if a[i] == a[j]: k -= 1 a[i], a[k] = a[k], a[i] return k - 1, j + 1 if __name__ == '__main__': a = [int(i) for i in stdin.readline().split()] quick_sort(a, 0, len(a) - 1) for i in a: stdout.write(str(i) + ' ')
a8f267d620c607b021cea16fc2613e2f9c1692a7
objectfox/bottle_talk
/api-gevent/9.py
1,722
3.65625
4
#!/usr/bin/env python # We can also use gevent to stream content to our users, or output # it as we generate it or recieve it from a database or other service. from gevent import monkey, sleep; monkey.patch_all() from bottle import route, run, request, HTTPResponse, redirect from time import sleep @route("/old/") def new_home(): redirect("/") @route("/") def hello(): """ Simple welcome message. """ sleep(0.5) return "Hello client!\n" @route("/multiply/:a/:b") def multiply(a=0,b=0): """ Multiplies two variables together. """ if not is_int(a) or not is_int(b): raise HTTPResponse(output='We only support integers.', status=400, header=None) return str(int(a)*int(b)) @route("/echo", method='POST') @route("/echo/", method='POST') def echo(): """ Prints out what we post to it. """ # To do that, we're going to turn our echo function into a generator. # Generators are a really powerful feature of python, that you should # look up if you have time. The unique feature about generators is # that they don't return all at once, they yield one thing, and can # then be run again, yielding another, until they're done. This # function returns one character from the text you give it, sleeps for # 5/100ths of a second, then prints another. for char in request.body.read(): sleep(0.05) yield char def is_int(a=''): """ Determines if we have an integer, else false. """ try: int(a) except ValueError: return False return True run(port=8080, debug=True, server="gevent") # Run with: # # python 9.py # # Test with: # # curl -N -d "This is some text we will echo." http://127.0.0.1:8080/echo # # Note the -N tells curl not to buffer the output, so we see it as it # comes in. #
c5ad9c3bbb44c3441e1a06af9077684cce121d69
juanhurtado4/CS-2-Tweet-Generator
/rearrange.py
583
3.953125
4
import sys import random words = sys.argv[1:] # Command line arguments def random_python_quote(): ''' Functions scrambles the order of the elements in the list "words" Returns a set of strings which is a scrambled version of words list. ''' scramble_words = [] if len(words) == 0: return 'No words were given' while len(words) > 0: rand_index = random.randint(0, len(words) - 1) scramble_words.append(words.pop(rand_index)) return scramble_words if __name__ == '__main__': quote = random_python_quote() print(quote)
da9590d5f866483b96babe81cc8674867501f72c
aniamirjanyan/Python-Basics
/basic_lists.py
1,973
4.34375
4
courses = ["History", "Math", "Physics", "CompSci"] print(courses[0]) print(courses[:2]) print(len(courses)) courses.append("Art") # adding item to the list courses.insert(0, "Art") # inserting at position 0 courses_2 = ["Art", "Education"] courses.insert(0, courses_2) # will add the list to the list courses.extend(courses_2) # adds items from list_2 to the list courses.remove("Math") # will remove the item Math courses.pop() # will remove the LAST item and return ut courses.reverse() # prints in reverse #courses.sort() # sorted list nums = [1, 4, 9, 3, 6, 2] nums.sort() # sorts in ascending order nums.sort(reverse=True) # sorts in descending order print(min(nums)) # or max print(sum(nums)) # prints the sum courses.index("CompSci") # index where the item is found print("Art" in courses) # boolean for item in courses: print(item) # will print every item for index, course in enumerate(courses): # prints items with indeces print(index, course) course_str = " - ".join(courses_2) # Art - Education new_list = course_str.split("-") # split and create list empty_list = [] empty_list = list() # - - - - - - - - - - - TUPLES - - - - - - - - - - - - - - - # If you want unmutable list use tuple tuple = ('history', 'math', 'physics', 'compsci') # it is immuatble # everything else is same as list # - - - - - - - - - - - SETS - - - - - - - - - - - - - - - - # prints in sorted order # don't care about order # helps to throw away duplicates set = {'history', 'math', 'physics', 'compsci', 'art'} set_2 = {'design', 'art', 'history'} print(set.intersection(set_2)) # shows common courses print(set.difference(set_2)) # items that were not in set_2 print(set.union(set_2)) # all of the items in both sets
6c4871f0a93dfb5d3d8a18c806d33de5b2537fc5
dopqob/Python
/Python学习笔记/基础练习/hello.py
617
3.671875
4
# coding=UTF-8 # def fun(args): # print (args,type(args)) # # phone = ('13098765432', '16602700006', '18502799989') # fun(phone) # dict1 = {'name':'荸荠', 'age':30, 'work':'测试工程师'} # print ('我的姓名是{name},我{age}岁,我是{work}'.format(**dict1)) # a = lambda a,b:a+b # print (a(3,5)) # # b = 1 # name = 'Bilon' if b == 1 else 'Foolish' # print name # import random # li = [] # for i in range(6): # r = random.randrange(65, 91) # print chr(r) # li.append(chr(r)) # print (''.join(li)) li = [1, 2, 3, 4, 5, 6, 7, 8, 9] result = map(lambda a: a + 10, li) print(list(result))
a7a9f37fa98cf6fc72cebe85d9f187e802ebe8c9
GuilhermeAntony14/Estudando-Python
/ex040.py
317
3.84375
4
print('vamos descobrir a sua nota!') n = float(input('Digite sua primeira nota: ')) n1 = float(input('Digite o segundo valor: ')) n2 = float((n+n1)/2) print(f'A media e {n2}!') if n2 <= 4: print('Reprovado!') elif n2 >= 5 and n2 < 7: print('Recuperação!') elif n2 >= 7: print('\033[32mAprovado!\033[m')
ee8f5d997683dfb1853cbf9fc0468454bcc79574
Tyrna/adventofcode
/3/sol3.py
605
3.703125
4
f = open("input.txt", "r+") i = 0 two = False twoNum = 0 three = False threeNum = 0 map = {} for line in f.readlines(): #Fill the map for char in line: if char in map: map[char] = map[char] + 1 else: map[char] = 1 #Check the map for char in map: if map[char] == 2: two = True if map[char] == 3: three = True #Save the info if (two): twoNum = twoNum + 1 if (three): threeNum = threeNum + 1 map = {} two = False three = False print("Checksum: " , twoNum * threeNum)
88742ce49f07c1b09f4970738a849673a9477c5b
helenaj18/Gagnaskipan
/Tímadæmi/Tímadæmi15/15. MoreTrees/AlphabetTreeBase/alphabet_tree_student_program.py
1,431
3.828125
4
import sys class TreeNode: def __init__(self, word = ""): self.word = word self.children = [] class AlphabetTree: def __init__(self): self.root = TreeNode('') def add_word(self, word): if word == '': return self.root node = self.add_word(word[:-1]) for child_node in self.root.children: if child_node.word == word: return child_node new_node = TreeNode(word) self.root.children.append(new_node) def print_all(self): self.print_preorder_recur(self.root) print('') def print_preorder_recur(self, node): if node == None: return print(str(node.word)) for child_node in node.children: self.print_preorder_recur(child_node) def print_leaves(self): return self.print_leaves_recur(self.root) def print_leaves_recur(self, node): if node.children == []: print(node.word) for child_node in node.children: self.print_leaves_recur(child_node) if __name__ == "__main__": file = open(sys.path[0] + "/alphabet_words.txt") tree = AlphabetTree() for line in file: tree.add_word(line.strip()) tree.print_all() tree.print_leaves() file.close()
e8222c6f5cfc3680991139065e79c07c2e64abc2
fatrujilloa/BootCampJ00
/count.py
723
3.9375
4
import sys, string def text_analyzer(*args): if len(args) == 0: T = input('What is the text to analyze?: ') elif len(args) > 1: print ("Too many arguments") return else: T = args[0] l, u, s, p = 0, 0, 0, 0 for i in range(0, len(T)): if T[i] in string.ascii_lowercase: l = l + 1 elif T[i] in string.ascii_uppercase: u = u + 1 elif T[i] in string.whitespace: s = s + 1 elif T[i] in string.punctuation: p = p + 1 print ("The text contains", len(T), "characters:\n\n", "- ", u, "upper letters\n\n", "- ", l, "lower letters\n\n", "- ", p, "punctuation marks\n\n", "- ", s, "spaces")
5ce4dc12fe1ba247d570fd32be21a030ba12096a
Jpocas3212/whatsapp-play
/wplay/locationfinder.py
324
3.53125
4
import os from bs4 import BeatifulSoup def locationfinder(name): """ # to find location by ip address print('Get you ipinfo token from https://ipinfo.io/account') ip_address = '*' token = str(input("Enter your ipinfo token: ")) ip_string = 'curl ipinfo.io/'+ip_address+'?token='+token+'' os.system(ip_string) """
2d16de2ebd39074c1e2dc80e4a43688f04fa4677
rafathossain/Encrypt-Decrypt
/main.py
1,193
4.25
4
import string # Alphabet List alphabet = list(string.ascii_uppercase) # Encrypted List encrypted = ['Z', 'A', 'Y', 'B', 'X', 'Z', 'A', 'Y', 'B', 'X', 'Z', 'A', 'Y', 'B', 'X', 'Z', 'A', 'Y', 'B', 'X', 'Z', 'A', 'Y', 'B', 'X', 'R'] # Python code to convert string to list character-wise def Convert(data): list1 = [] list1[:0] = data return list1 # Data encryption def encryptData(data): encrypted_value = "" for alpha in Convert(data.upper()): encrypted_value += encrypted[alphabet.index(alpha)] return encrypted_value # Data decryption def decryptData(data): decrypted_value = "" for alpha in Convert(data.upper()): decrypted_value += alphabet[encrypted.index(alpha)] return decrypted_value # Run the script if __name__ == '__main__': option = input("Select Option:\n1. Encrypt\n2. Decrypt\n>>>") try: if int(option) == 1: print(encryptData(input("Enter data to encrypt: "))) elif int(option) == 2: print(decryptData(input("Enter data to decrypt: "))) else: print("Invalid input detected!") except Exception: print("Invalid data to encrypt/decrypt!")
d8ef18c3ad837ed058a8926b506ece04c3e0782d
fcortesj/AssistMe
/gui/linkers/getEvents.py
1,601
3.859375
4
""" Script used to store the events in a local text file """ # Import dependencies to access to the data import sys # Get data sent from the client to store all the events nombres = sys.argv[1] lugares = sys.argv[2] fechas = sys.argv[3] # Check if there's at least one event to be downloaded if nombres is not "": # Open file where all the events are locally stored and erase everything on it file = open("eventos.txt","r+") file.truncate(0) file.close() # Open file where all the events will be locally stored file = open("eventos.txt","a") # Get a list of names, places and dates from each event lista_nombres = nombres.split(",") lista_lugares = lugares.split(",") lista_fechas = fechas.split(",") lon = len(lista_nombres) # For each event add to the text file the event information for evento in range(lon): file.write(lista_nombres[evento]+","+lista_lugares[evento]+","+lista_fechas[evento]) file.write("\n") # Create the file where the registered people will be locally stored archivo_registro = "Asistentes_"+lista_nombres[evento]+".txt" with open(archivo_registro,"a") as f: pass # Create the file where the assistants to the event will be locally stored archivo_asistentes = lista_nombres[evento]+"_asistentes.txt" with open(archivo_asistentes,"a") as f: pass # Create the file where the statistics will be locally stored archivo_estadistcas = "Estadisticas_"+lista_nombres[evento]+".txt" with open(archivo_estadistcas,"a") as f: pass print("Eventos añadidos exitosamente") file.close()
c9e967ee6461b1ef5a0b00eca30793b9c8a0388d
sahands/coroutine-generation
/combgen/helpers/permutations/move.py
633
3.640625
4
from .transpose import transpose # Movement directions LEFT = -1 RIGHT = 1 def move(pi, inv, x, d, poset=None): # Move x in permutation pi in the direction given by d, while maintaining # inv as pi's inverse. If a poset is given, x is only moved if pi will # continue to be a linear extension of the poset with x moved. True is # returned if move is successful. if inv[x] + d >= len(pi) or inv[x] + d < 1: return False y = pi[inv[x] + d] if poset and ((d == LEFT and poset(y, x)) or (d == RIGHT and poset(x, y))): return False transpose(pi, inv, x, pi[inv[x] + d]) return True
abe6f9571793c64ee261ffc001080030cfb0a8b2
AntonZykov85/python
/task2.py
280
3.53125
4
my_list_str = (input('введите переменные через пробел')) my_list = my_list_str.split( ) print(my_list) print(type(my_list)) k = len(my_list) - 1 i = 0 while i < k: my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i] i += 2 print(my_list)
ea6e300dfc7ba4b0d6b74ca24380fa9658f0911f
ZJXzjx78/lease-of-land
/python/ten/c3.py
187
3.671875
4
import re s = "A83C72D1D8E67" def convert(value): matched = value.group() if int(matched) >= 6: return'9' else: return'0' r = re.sub('\d',convert,s) print(r)
c1dde2f2b6b987d308e5b9ff18166297016ba35c
vespinoza0/grader
/grader.py
10,755
3.609375
4
import csv import tkinter from tkinter import filedialog import os import datetime import config myTAlist = config.TAlist avgDict = [] b = ['Assignment','AvgScore','Sub_Rate', 'Sub_Avg'] avgDict.append(b) JScolumn = 0 pyColumn = 0 #### Get a single Canvas CSV file to update! ############# print("##################################################################################################################") print("Welcome to grader.py!!") print("Please Select Canvas CSV file") root = tkinter.Tk() root.withdraw() Ca = filedialog.askopenfilename(title = "Select canvas file",filetypes = (("CSV files","*.csv"),("all files","*.*"))) # get directory +filename.csv head, tail = os.path.split(Ca) print("You are now editing canvas file: ",tail) with open(Ca) as csvDataFile: csvReader = csv.reader(csvDataFile) Can = list( csv.reader(csvDataFile)) total_students = len(Can)-3 Canheader = Can[0] print("for all ", total_students , " students! Hope this code works!") for i in range(0,len(Canheader)): thing = Canheader[i] thing = thing.lower() canName = thing.split() #cName = canName[0:len(h)-2] if "variables" in canName and "javascript" in canName: JScolumn = i if "variables" in canName and "python" in canName: pyColumn = i ############################################################### ### this function gets the unique TU emai and inserts in the second column of the HR list def modHR(Hr): email = [] present = datetime.datetime.now() deadline = datetime.datetime(2018,2,21) header = Hr[0] loginIDindex = header.index('Login ID') totalScoreColumn = header.index('Total score') percentColumn = header.index('Percentage score') maxColumn = header.index('Max score') for row in range(1, len(Hr)): loginID =Hr[row][loginIDindex] d = Hr[row][3].split('/') year = int(d[0]) month = int(d[1]) day = int(d[2]) subdate = datetime.datetime(year,month,day) if subdate <= deadline: # update scoring system changed on 2/21/18 grade = float(Hr[row][totalScoreColumn]) if grade == 10: Hr[row][percentColumn] = 30 #maxScore =float(Hr[row][maxColumn]) #Hr[row][percentColumn] = Hr[row][totalScoreColumn] / maxScore elif grade == 40: Hr[row][percentColumn] = 70 #maxScore =float(Hr[row][maxColumn]) #Hr[row][percentColumn] = Hr[row][totalScoreColumn]/ maxScore elif grade > 100: Hr[row][percentColumn] = 100 Hr[row].insert(17, loginID) loginID = loginID.lower() if loginID == config.loginID1: loginID = config.login1 if loginID == config.loginID2: loginID = config.login2 if loginID == config.loginID3: loginID = config.login3 if loginID == config.loginID4: loginID = config.login4 if loginID == config.loginID5: loginID = config.login5 if loginID == config.loginID6: loginID = config.login6 if "@" in loginID: a,b = loginID.split('@') email.append(a) Hr[row].insert(18, a) Hr[row][loginIDindex] = a else: email.append(loginID) Hr[row].insert(18, loginID) Hr[row][loginIDindex] =loginID return Hr ### this function creates an error log with a time stamp def writeErrorLog(nomatch): now = format(datetime.date.today()) nows = str(now) noMatchName = nows +'_unMatchedReport_' + HRtail with open(noMatchName, 'w') as f: [f.write('{0},{1}\n'.format(key, value)) for key, value in nomatch.items()] print("Error Log file created for" ,HRtail,"! Saved as ", noMatchName) def writeStats(dictio): now = format(datetime.date.today()) nows = str(now) dictName = nows+"_ProgressReport.csv" with open(dictName, "w") as output: writer = csv.writer(output, lineterminator='\n') writer.writerows(dictio) ### this function creates a new updated canvas file with a time stamp def newCanvas(nc): now = format(datetime.date.today()) nows = str(now) newCanName = nows+"_UpdatedCanvasFile.csv" with open(newCanName, "w") as output: writer = csv.writer(output, lineterminator='\n') writer.writerows(nc) print("##################################################################################################################") print("Successfully exported ",newCanName) print("and it is ready to be uploaded to canvas!") def checkpoint(Can,jscol,pycol): header = Can[0] CScol = header.index('Core Skills HackerRank (68007)') ILP1col = header.index('Individual Learning Path Assignment 1: IDE and GUI (121770)') ILP2col = header.index('Individual Learning Path Assignment 2: Core Skills (68009)') # print(CScol) # print(ILP1col) # print(ILP2col) checkList = [] #b = ['student','JS1','JS2','JS3', 'Py1', 'Py2'] b = ['student','email','JS1','JS2','JS3', 'Py1', 'Py2', 'CS','ILP1','ILP2','Eligibility'] checkList.append(b) for i in range(2,len(Can)-1): student = Can[i][0] email = Can[i][2]+ "@temple.edu" checks = 0 #print(email) for j in range(jscol,jscol+10): #loop thru JS 10 columns score = Can[i][j] if score: score1 = float(score) if score1 >=70: checks +=1 if not score: #if there is no element score = 0 Can[i][j] = score #templist = [student, '0', '0', '0', '0', '0'] # templist = [student,email,'0', '0', '0', '0', '0','0','0','0','0'] if checks >=3 and checks <6: templist[2] = '1' elif checks >=6 and checks <10: templist[2] = '1' templist[3] = '1' elif checks == 10: templist[2] = '1' templist[3] = '1' templist[4] = '1' checksp = 0 for k in range(pycol,pycol+10): #loop thru python 10 columns score = Can[i][k] if score: score1 = float(score) if score1 >=70: checksp +=1 if not score: score = 0 Can[i][k] = score if checksp >= 5 and checksp < 10: templist[5] = '1' elif checksp == 10: templist[5] = '1' templist[6] = '1' #print("CoreSkills score",Can[i][CScol]) if float(Can[i][CScol])>=70: templist[7] = '1' #print("ILP1 score",Can[i][ILP1col]) if float(Can[i][ILP1col])>=70: templist[8] = '1' #print("ILP2 score",Can[i][ILP2col]) if float(Can[i][ILP2col])>=70: templist[9] = '1' ss = templist[2:] ssSum= 0 for k in range(len(ss)): aaa = int(ss[k]) ssSum = ssSum+aaa if ssSum ==8: templist[10] = '1' #print(templist) #print(ss, "sum is",ssSum) checkList.append(templist) now = format(datetime.date.today()) nows = str(now) with open(nows+"_projectEligibility.csv", "w") as output: writer = csv.writer(output, lineterminator='\n') writer.writerows(checkList) ### this function updates a column in the canvas file def updateCanvas(ca, hr, col, scale): noMatchDict = {} # empty dict() noMatchDict['name'] = 'email' nomatches = int(0) matches = 0 gradeSum = 0 oldgradeSum = 0 hrGradeSum = 0 noMatchz = [] header = hr[0] loginIDindex = header.index('Login ID') ScoreColumn = header.index('Percentage score') print("Percentage score index", ScoreColumn) for row in range(1, len(hr)): # go thru each submission in hackerRank tuID = hr[row][loginIDindex] grade = float(hr[row][ScoreColumn]) # imported HR grade if grade == 0: continue if grade >100: grade = 100 grade = grade*scale hrName = hr[row][2] hrEmail = hr[row][17] if tuID in myTAlist: # if it is a TA submission, skip for now continue for rowz in range(2, len(ca)-1): # search canvas match with their respective canvas slot canvasID = ca[rowz][2] if canvasID == tuID: # if we match tug##### matches+=1 # increment match counter hrGradeSum += grade oldgrade = float(ca[rowz][col]) # current canvas grade if oldgrade < grade: # if oldgrade is less than grade from HR ca[rowz][col] = grade # update canvas list to higher grade oldgradeSum += grade # add new higher grade else: oldgradeSum += oldgrade # else add old original grade break if rowz == len(ca)-2: #print("we could not match canvas id with submission associated with", tuID) noMatchz.append(hr[row][16+1]) noMatchDict[hrName] = hrEmail nomatches+=1 for i in range(2,len(ca)-1): grade = float(ca[i][col]) gradeSum += grade if len(noMatchDict)>1: writeErrorLog(noMatchDict) print('---------------------------------------------------------------------------------------------------------------') tt = len(hr)-1 hrMean = hrGradeSum/matches realAvg = gradeSum/total_students subRate = (matches/total_students)*100 avgDict.append([ca[0][col],realAvg, subRate, hrMean]) return(matches,ca) def getCol(hrtail): col = 1 HRname = hrtail.lower() h = HRname.split('_') hh = h[0:len(h)-2] for i in range(0,len(Canheader)): thing = Canheader[i] thing = thing.lower() canName = thing.split() cName = canName[0:len(h)-2] # if "variables" in cName and "javascript" in cName: # print("variables in javascript in column :", i) # JScolumn = i # if "data" in cName and "python" in cName: # pyColumn = i # print("data types in python in column :", i) if cName==hh: # print("header #", i) # print(cName) # print("found it!") return i if i == len(Canheader)-1: print("no column in canvas was found associated with this assignment!") col = int(input("Enter the column to edit in CANVAS, refer to CanvasColumn.xlsx file in TA drive: ")) return col+3 root = tkinter.Tk() root.withdraw() filez = filedialog.askopenfilenames(parent=root,title='SELECT ALL HACKERANK FILES') fileList = list(filez) for i in range(0, len(fileList)): with open(fileList[i]) as csvDataFile: csvReader = csv.reader(csvDataFile) Hr = list(csv.reader(csvDataFile)) head, HRtail = os.path.split(fileList[i]) print("You have successfully imported HR file ", HRtail) numrows1 = len(Hr) numcols1 = len(Hr[0]) col = getCol(HRtail) print("this is the respective column : ", col) if col < 46: points = 100 elif col >= 46 and col < 49: points = 50 else: points = int(input("Enter how many points this assignment is worth in Canvas: ")) scaleDown = points/100 newHR = modHR(Hr) # edit the HackeRank file first ..... sb, newCa = updateCanvas(Can,newHR,col,scaleDown) #now update the canvas File! subPercent = sb/total_students newCanvas(newCa) checkpoint(newCa,JScolumn,pyColumn) writeStats(avgDict) print("You have just updated ", len(fileList),"assignments!\nThank you for using grader.py!") print("To provide feedback or report bugs, email Victor at tug86727@temple.edu")
e98e76f8a909723fe340e72dbb83d13eac50901e
JAreina/python
/4_py_libro_2_2/venv/py_2_listas/py_2_4_lists_in.py
155
3.71875
4
print(3 in [1, 3, 4, 5]) #True print(3 not in [1, 3, 4, 5]) #False print(3 in ["one", "two", "three"]) #False print(3 not in ["one", "two", "three"]) #True
fbb4cea42816b4cfbea382c7666cc1e73a652614
dtokos/FLP
/project-euler/33_Digit-cancelling-fractions.py
1,079
3.546875
4
# coding=utf-8 # Digit cancelling fractions # Problem 33 # https://projecteuler.net/problem=33 # # The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. # We shall consider fractions like, 30/50 = 3/5, to be trivial examples. # There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator. # If the product of these four fractions is given in its lowest common terms, find the value of the denominator. from importlib import import_module gcf = import_module('5_Smallest-multiple').gcf def main(): print(digitCancellingFractions()) def digitCancellingFractions(): nomiProd, denomiProd = 1, 1 for i in range(1, 10): for j in range(1, i): for k in range(1, j): if (k * 10 + i) * j == (i * 10 + j) * k: nomiProd *= k denomiProd *= j return denomiProd // gcf(nomiProd, denomiProd) if __name__ == '__main__': main()
333ee3aff66b98604610b35c98190c6a1eb2706c
wo-shi-lao-luo/Python-Practice
/LeetCode/Range Sum of BST.py
1,738
3.625
4
# Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). # # The binary search tree is guaranteed to have unique values. # # # # Example 1: # # Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 # Output: 32 # Example 2: # # Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 # Output: 23 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: self.su = 0 def s(cur): if L <= cur.val <= R: self.su += cur.val if cur.left is not None: s(cur.left) if cur.right is not None: s(cur.right) s(root) return self.su class Solution: def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: sum = 0 input = [root] while input: cur = input.pop() if L <= cur.val <= R: sum += cur.val if cur.left is not None: input.append(cur.left) if cur.right is not None: input.append(cur.right) return sum class Solution: def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: sum = 0 input = [root] while input: cur = input.pop() if cur: if L <= cur.val <= R: sum += cur.val if L < cur.val: input.append(cur.left) if R > cur.val: input.append(cur.right) return sum
55735dc84d0c8bbee42f707695c18f6dd7367b42
andytanghr/python-exercises
/turtle/shapes.py
1,942
3.671875
4
from turtle import * def drawEquilateralTriangle(size=100, fill=False, hue='black'): color(hue) if fill == True: begin_fill() for line in range(3): right(120) forward(size) end_fill() else: for line in range(3): right(120) forward(size) def drawSquare(size=100, fill=False, hue='black'): color(hue) if fill == True: begin_fill() for line in range(4): right(90) forward(size) end_fill() else: for line in range(4): right(90) forward(size) def drawPentagon(size=100, fill=False, hue='black'): color(hue) if fill == True: begin_fill() for line in range(5): right(72) forward(size) end_fill() else: for line in range(5): right(72) forward(size) def drawHexagon(size=100, fill=False, hue='black'): color(hue) if fill == True: begin_fill() for line in range(6): forward(size) right(60) end_fill() else: for line in range(6): forward(size) right(60) def drawOctagon(size=100, fill=False, hue='black'): color(hue) if fill == True: begin_fill() for line in range(8): forward(size) right(45) end_fill() else: for line in range(8): forward(size) right(45) def drawStar(size=100, fill=False, hue='black'): color(hue) #fillcolor(hue) if fill == True: begin_fill() for line in range(5): right(144) forward(100) end_fill() else: for line in range(5): right(144) forward(100) def drawCircle(size=100, fill=False, hue='black'): color(hue) # move into position up() right(90) forward(size) left(90) down() def resetPathPosition(): up() left(90) forward(size) right(90) down() if fill == True: begin_fill() circle(size) end_fill() resetPathPosition() else: circle(size) up() resetPathPosition()
07ac60877c3e49c093210c558128105a84359c2f
JackSmithThu/quant
/data_clean/power.py
1,218
3.515625
4
#!/usr/bin/env python # coding=utf-8 file = open("res.txt") div = [] # 需要除权的 list,每个元素第一列是时间,第二列是价格(string) for line in file: # print line line = line.split('\n')[0] div.append(line.split(' ')) # print div for div_node in div: price = float(div_node[1]) # print price, type(price) base_data = open("base.csv") for line in base_data: # print '================' # print 'pre:', line, line = line.split('\r\n')[0] base = line.split(',') [year, month, day] = base[0].split('/') month = '0' + month if len(month) < 2 else month day = '0' + day if len(day) < 2 else day date = year + '-' + month + '-' + day arr = [] for i in xrange(2,6): arr.append(float(base[i])) for div_item in div: if date < div_item[0]: # print 'sub:', div_item i = 0 for pri in arr: arr[i] = pri - float(div_item[1]) i = i + 1 div_pri = [] for arr_item in arr: div_pri.append("%.3f" % arr_item) converted = [date+' '+ base[1]] + div_pri + base[6:] # print 'res:', ','.join(converted) print ','.join(converted)
da9966e71749b03370b758ddeda5739530964b74
nwaiting/wolf-ai
/wolf_alg/Data_structures_and_algorithms_py/union_find_sets.py
2,630
3.578125
4
#coding=utf-8 """ 并查集: 并查集是一种树型的数据结构,用于处理一些不相交集合(Disjoint Sets)的合并及查询问题 """ class edge(object): def __init__(self, start=None, end=None): self.start = start self.end = end class GraphManager(object): def __init__(self, edge_num=3): if edge_num: self.parents = [-1 for i in xrange(edge_num)] self.edges = [] self.edges.append(edge(0,1)) self.edges.append(edge(1,2)) self.edges.append(edge(0,2)) def find(self, index): if index == self.parents[index] or -1 == self.parents[index]: return index return self.find(self.parents[index]) def check(self): for item in self.edges: i_r = self.find(item.start) j_r = self.find(item.end) if i_r == j_r: return True self.union(i_r, j_r) def union(self, i, j): i_res = self.find(i) j_res = self.find(j) if i_res != j_res: self.parents[i_res] = j_res class UnionFindSets(object): def __init__(self, arr=None): self.parents = arr def is_cycle(self): for i in xrange(len(self.parents)): res, flag = self.find(i) if i == res and flag: return True elif i > 0: self.union(i, i-1) print i, self.parents return False def find(self, index): tmp_index = index while True: tmp_value = self.parents[tmp_index] if tmp_value >= len(self.parents): return -1, False if -1 == self.parents[tmp_index]: return tmp_index, False if index == self.parents[tmp_index]: return index, True tmp_index = self.parents[tmp_index] def union(self, start=None, end=None): if start is None or end is None: return res1, flag1 = self.find(start) res2, flag2 = self.find(end) if res1 != res2: self.parents[res1] = res2 if __name__ == '__main__': run = 1 if run == 1: record_pre = [-1 for i in xrange(10)] record_pre[1] = 2 record_pre[7] = 8 record_pre[8] = 9 record_pre[9] = 7 dis_sets = UnionFindSets(arr=record_pre) if dis_sets.is_cycle(): print "have cycle" else: print "have no cycle" elif run == 2: gmanager = GraphManager() if gmanager.check(): print "check success"
cc4ba67faab9a7966555d64d39d1934655ac063a
liush79/codewars
/6kyu/string_evaluation.py
465
3.546875
4
def string_evaluation(strng, conditions): result = [] for cond in conditions: left = cond[0] if cond[0].isdigit() else str(strng.count(cond[0])) right = cond[-1] if cond[-1].isdigit() else str(strng.count(cond[-1])) result.append(eval('%s%s%s' % (left, cond[1:-1], right))) return result print string_evaluation('abb', ['a>b', 'b==a', 'b<=a', 'b>a', 'b!=b', 'a==1', 'b==1']) # [False, False, False, True, False, True, False])
66ec9272e34d5c0e053d84d4110b64a422225287
Carlos21Reyes/Mision-02
/cuenta.py
539
3.625
4
# Autor: Carlos Alberto Reyes Ortiz # Descripcion: Te ayuda a saber cuanta propina y IVA va a ser de tu comida. Dando como propina un 13% y un IVA de 15% # Escribe tu programa después de esta línea. costoComida = int(input("Costo de su comida:")) porcentajePropina = 13 porcentaheIVA = 15 propina = costoComida*porcentajePropina/100 iVA = costoComida*porcentaheIVA/100 totalPagar = costoComida + propina + iVA print("Propina:$", "{:.2f}" . format(propina)) print("IVA:$", "{:.2f}" . format(iVA)) print("Total a pagar:$", "{:.2f}" . format(totalPagar))
f34a4ef8f1604aa144e3faff2b9b1a7fe74399a2
anguszxd/leetcode2
/PalindromeNumber.py
1,120
3.9375
4
#coding:utf-8 #该方法思路:取最前一位和最末尾一位进行比较,看两者是否相同 #若相同则在原数上去除最高位和最低位,继续进行比较 #但该方法存在的问题是:去除最高位和最低位后,余下的不一定能成为数 #如:1000001,去除最高位最低位后全是0,不是一个数了 def isPalindrome(x): x1 = x digit = 0 isPalin = True while x1 > 0: x1 /= 10 digit += 1 print digit x2 = x while x2 > 10: tail = x2%10 head = x2/(pow(10,digit-1)) if tail == head: digit -= 2 x2 /= 10 x2 -= head*pow(10,digit) print x2 else: isPalin = False break return isPalin #方法2:直接使用翻转整数的方法(回文整数的特点是,翻转后与原数值相同) #将整数翻转后,与原数值进行比较,看是否相同 #这里认为负数是不能是回文整数 def isPalindrome2(x): if x < 0: return False if x == 0: return True leave = x result = 0 while 0 != leave: result = result * 10 + leave % 10 leave /= 10 print leave return x == result x = 1 print isPalindrome2(x)
854034d70081466d3808bcb843e251c737858d05
GabrielePiumatto/Scuola_2020-21
/SISTEMI-E-RETI/PYTHON/COMPITI PYTHON NATALE/ES_03.py
329
4.0625
4
def fibonacci (fib, num, a ,b): if num <= 0: return else: fib.append(fib[a] + fib[b]) a += 1 b += 1 num -= 1 fibonacci(fib, num, a, b) fib = [0, 1] a = 0 b = 1 num = int(input("Quanti numeri vuoi stampare ? ")) fibonacci(fib, num, a, b) print(fib[1:])
16bfb242e498dccd5b3203a4ce0c90340865e9b2
joycebrum/online-judge-problems
/UVA/10098-generating-fast-sorted-permutation.py
1,190
3.515625
4
def get_min_greater_than(array, letter): value = max(array) for c in array: if c > letter and c < value: value = c return value def get_next_permutation(letters): i = len(letters) - 1 removed = [] while i >= 0: if not removed: removed.append(letters.pop()) i -= 1 continue if max(removed) > letters[i]: letter = letters.pop() next_l = get_min_greater_than(removed, letter) removed.remove(next_l) letters.append(next_l) removed.append(letter) rest = sorted(removed) return letters + rest removed.append(letters.pop()) i -= 1 return None def generate_and_print_permutations(letters): print("".join(letters)) while True: letters = get_next_permutation(letters) if not letters: break print("".join(letters)) if __name__ == '__main__': n = int(input().strip()) for i in range(0, n): string = sorted(input().strip()) generate_and_print_permutations(string) print('')
878dfc95bd4069c89a95b64b6561cabfe03f6d9f
Justice0320/python_work
/ch3/self_test_cars.py
319
3.578125
4
cars = ["ford", "honda", "Lamborghini", "McLaren"] message = "My next car will be a " + cars[0] + "." print(message) message = "My next car will be a " + cars[1] + "." print(message) message = "My next car will be a " + cars[2] + "." print(message) message = "My next car will be a " + cars[3] + "." print(message)
b53f027b847f51556779b1de68e3a76bde68ef6c
Evilzlegend/Structured-Programming-Logic
/Chapter 02 - Elements of High Quality Programs/D2L Assignments/tiemens_temp.py
519
4.3125
4
# Fahrenheit to Celsius formula -32*5/9 # Entering the input for the desired temperature conversion. temperatureRequest=float(input("Please enter your degree temperature: ")) # Conversion formula for Fahrenheit to Celsius first part temperatureFirst=temperatureRequest-32 # Conversion formula for Fahrenheit to Celsius second part temperatureConversion=temperatureFirst*5/9 # Display outcome for conversion. print("Your temperature from Fahrenheit to Celsius: ",(format(temperatureConversion,',.2f')))
878132831dc91c803084bb844ae2afdb11f9c1a1
joysreb/python
/addelement_tuple.py
93
3.640625
4
tuples=(1,2,3,4,5,6) print(tuples) tuples=tuples+(7,8,9,10) listx=list(tuples) print(listx)
6c04804e7f5e7bb85360ea29d721ac77cc8fb2d5
emag-notes/automatestuff-ja
/ch05/picnic.py
705
3.671875
4
all_guests = { 'アリス': { 'リンゴ': 5, 'プレッツェル': 12 }, 'ボブ': { 'ハムサンド': 3, 'リンゴ': 2 }, 'キャロル': { 'コップ': 3, 'アップルパイ': 1 } } def total_brought(guests, item): num_brought = 0 for v in guests.values(): num_brought = num_brought + v.get(item, 0) return num_brought def print_total_brought(item): print(' - ' + item + ' ' + str(total_brought(all_guests, item))) print('持ち物の数:') print_total_brought('リンゴ') print_total_brought('コップ') print_total_brought('ケーキ') print_total_brought('ハムサンド') print_total_brought('アップルパイ')
010af8a1940ce2336935c87f5eecbb5bf2bd1e17
BrunoAfonsoHenrique/CursoEmVideoPython
/AlgoritmosPython_parte1/088.py
246
3.796875
4
num = qtd = soma = 0 while num != 999: num = int(input('Digite um numero [999 para parar]: ')) if num != 999: qtd = qtd + 1 soma = soma + num print('Você digitou {} números e a soma entre eles é {}.'.format(qtd, soma))
6efaf44fc9af001abe1e606462021979d112bcdd
saibi/python
/angela_course/section10_calculator.py
1,578
4.21875
4
# def format_name(f_name, l_name): # formated_f_name = f_name.title() # formated_l_name = l_name.title() # return formated_f_name + ' ' + formated_l_name; # print(format_name("angela", "ANGELA")) # def is_leap(year): # if year % 4 == 0: # if year % 100 == 0: # if year % 400 == 0: # print("Leap year.") # return True # else: # return False # else: # return True # else: # return False # # docstring # def days_in_month(year, month): # # """returns days of year.month""" # month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # if is_leap(year): # return month_days[month] + 1 # else: # return month_days[month] # #🚨 Do NOT change any of the code below # year = int(input("Enter a year: ")) # month = int(input("Enter a month: ")) # days = days_in_month(year, month-1) # print(days) # calculator def add(n1, n2): return n1 + n2 def sub(n1, n2): return n1 - n2 def mul(n1, n2): return n1 * n2 def div(n1, n2): return n1 / n2 operation = { "+" : add, "-" : sub, "/" : div, "*" : mul, } num1 = int(input("What's the first number?: ")) for op in operation: print(op) continue_calc = True while continue_calc: operation_symbol=input("Pick an opeation: ") num2 = int(input("What's the next number?: ")) answer = operation[operation_symbol](num1, num2) print(f"{num1} {operation_symbol} {num2} = {answer}") if input(f"Type 'y' to continue calculating with {answer}: ") == 'y': num1 = answer else: continue_calc = False
467a8fa204bf55c7126f414fcaf7b257eebcd65f
Roiw/LeetCode
/Python/131_PalindromePartitioning.py
1,377
3.921875
4
""" Backtracking - Add initial case (full word) as a base case, line 47 - Slice on every index from 1 to len-1 - If PartA and PartB are palindrome append to the list. - Continue backtracking only if PartA is palindrome. It becomes an offset now. """ class Solution: def partition(self, s: str) -> List[List[str]]: ans = [] def isPalindrome(word:str): p0, p1 = 0, len(word) - 1 while p0 < p1: if word[p0] != word[p1]: return False p0 += 1 p1 -= 1 return True def backtrack(word, index, offset): for i in range(index,len(word)): partA = word[:i] partB = word[i:] is_A_Palindrome = isPalindrome(partA) is_B_Palindrome = isPalindrome(partB) if is_A_Palindrome and is_B_Palindrome: ans.append(offset + [partA, partB]) if is_A_Palindrome: backtrack(partB, 1, offset + [partA]) if isPalindrome(s): ans.append([s]) backtrack(s, 1, []) return ans
5210887824ae21fa69dec0d45dcaa4d36a3388ea
rafael6/p3_essentials
/p3_essentials/build-in_functions/about_map.py
767
4.84375
5
# Map a function to an iterable object; run the function for each item in the iterator object print('Example 1') def fahrenheit(c): return (9.0/5)*c + 32 temps = [0, 64, 80, 93] print(list(map(fahrenheit, temps))) # With Python 3 must cast map to a list print('Same as above but using lambda expression which is more common with map.') print(list(map(lambda c: (9.0/5)*c + 32, temps))) print('Example 2, adding the elements from each list') list_1 = [1, 2, 3] list_2 = [4, 5, 6] m = map(lambda i,j: i+j, list_1, list_2) for i in m: print(i) print('Example 3, create a function which finds the lenght of each world in the phrase.') def word_lenght(p): return list(map(len, p.split())) print(word_lenght('How long are the words in this phrase'))
729704bfaf3222ac850e605af3faa3589c76742a
sprotg/2019_3d
/datastrukturer/linked_list.py
1,211
3.765625
4
class Linked_list: def __init__(self): self.head = None def list_search(self, k): x = self.head while x is not None and not (x.key == k): x = x.next #Denne metode skal returnere None # hvis k ikke findes i listen. # eller skal den returnere x return x def list_insert(self, k): k.next = self.head if not (self.head == None): self.head.prev = k self.head = k k.prev = None def list_delete(self, x): #Denne linje sammenkæder de to elementer omkring x if not (x.prev == None): x.prev.next = x.next else: #Hvis x ikke har en prev, må den være vores head. #Derfor sætter vi head til at være den x.next self.head = x.next #Hvis x har en next, skal dens prev sættes til x's gamle prev, if not (x.next == None): x.next.prev = x.prev def print_list(self): x = self.head while not (x is None): print(x.key) x = x.next class List_element: def __init__(self, k): self.next = None self.prev = None self.key = k
21579143b9c593d70bd49bc0b3bdb191c52112f9
muraleo/play_algorithm_python3
/binarySearch/binarySearch.py
757
3.796875
4
def binarySearchIter(arr, target): if not arr: return None # search in [l,r] l, r = 0, len(arr)-1 while(l <= r): mid = l + (r-l)//2 if(arr[mid] < target): l = mid + 1 elif(arr[mid] > target): r = mid - 1 else: return mid return None def __binarySearchRec(arr, l, r, target): if not arr: return None mid = l + (r - l)//2 if arr[mid] == target: return mid elif arr[mid] < target: return __binarySearchRec(arr, mid+1, r, target) else: return __binarySearchRec(arr, l, mid-1, target) def binarySearchRec(arr, target): if not arr: return None return __binarySearchRec(arr, 0, len(arr)-1, target)
75a49b14b46aee3e0554e093c459a8012b631400
jeeras/allexerciciespython3
/ex044.py
876
3.890625
4
print('-=' * 11) print('GERENCIADOR DE COMPRAS') print('-=' * 11) gastou = float(input('Quanto você gastou em compras?')) print('Você vai pagar em: ') print('[ 1 ]Dinheiro á vista') print('[ 2 ]Á vista no cartão') print('[ 3 ]2x no cartão') print('[ 4 ]3x ou mais no cartão') opcao = str(input('Sua opção: ')) if opcao == '1': print('Você ira pagar {:.2f} a vista.'.format(gastou - (gastou * 0.10))) elif opcao == '2': print('Você ira pagar {:.2f} a vista no cartão'.format(gastou - (gastou * 0.5))) elif opcao == '3': print('Você ira pagar {:.2f} 2x no cartão'.format(gastou)) elif opcao == '4': print('Quantas parcelas?') parcelas = int(input('')) print('Você comprando com {} parcelas irá pagar {:.2f}'.format(parcelas, gastou + (gastou * 0.20))) else: print('\033[32mVocê não digitou 1, 2, 3 ou 4 ')
76f579c0ef41abc77e35668d09654e9fdacaea15
yodji09/Arkademy-Test
/soal4.py
2,171
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 8 11:24:15 2020 @author: Players """ def kataganti(kataasal): kalimatbaru = [] listkata = list(kataasal) for hurufganti in listkata: if hurufganti == 'a': kalimatbaru.append('u') elif hurufganti == 'b': kalimatbaru.append('m') elif hurufganti == 'c': kalimatbaru.append('c') elif hurufganti == 'd': kalimatbaru.append('d') elif hurufganti == 'e': kalimatbaru.append('e') elif hurufganti == 'f': kalimatbaru.append('f') elif hurufganti == 'g': kalimatbaru.append('g') elif hurufganti == 'h': kalimatbaru.append('x') elif hurufganti == 'i': kalimatbaru.append('i') elif hurufganti == 'j': kalimatbaru.append('j') elif hurufganti == 'k': kalimatbaru.append('k') elif hurufganti == 'l': kalimatbaru.append('l') elif hurufganti == 'm': kalimatbaru.append('m') elif hurufganti == 'n': kalimatbaru.append('n') elif hurufganti == 'o': kalimatbaru.append('o') elif hurufganti == 'p': kalimatbaru.append('p') elif hurufganti == 'q': kalimatbaru.append('q') elif hurufganti == 'r': kalimatbaru.append('r') elif hurufganti == 's': kalimatbaru.append('s') elif hurufganti == 't': kalimatbaru.append('t') elif hurufganti == 'u': kalimatbaru.append('u') elif hurufganti == 'v': kalimatbaru.append('v') elif hurufganti == 'w': kalimatbaru.append('w') elif hurufganti == 'x': kalimatbaru.append('x') elif hurufganti == 'y': kalimatbaru.append('y') elif hurufganti == 'z': kalimatbaru.append('z') elif hurufganti == ' ': kalimatbaru.append(' ') return "".join(kalimatbaru) print (kataganti("mari belajar python"))
b9d885f03b89aaf571b0af24bc1d225718ea1074
itsrohanvj/Data-Structures-Algorithms-in-Python
/Data Structures/IMP-BST.py
3,546
3.890625
4
# Returns true if a binary tree is a binary search tree def IsBST3(root): if root == None: return 1 # false if the max of the left is > than root if (root.getLeft() != None and FindMax(root.getLeft()) > root.get_data()) return 0 # false if the min of the right is <= than root if (root.getRight() != None and FindMin(root.getRight()) < root.get_data()) return 0 # false if, recursively, the left or right is not a BST if (not IsBST3(root.getLeft()) or not IsBST3(root.getRight())) return 0 # passing all that, it's a BST return 1 #METHOD 2 def isBST4(root, previousValue=[NEG_INFINITY]): if root is None: return 1 if not isBST4(root.getLeft(), previousValue): return False if root.get_data() < lastNode[0]: return 0 previousValue = root.get_data() return isBST4(root.getRight(), previousValue) #----------------------------------------------------------------------- def DLLtoBalancedBST(head): if(not head or not head.next): return head temp = FindMiddleNode(head) # Refer Linked Lists chapter for this function. p = head #We can use two-pointer logic to find the middle node while(p.next != temp): p = p.next p.next = None q = temp.next temp.next = None temp.prev = DLLtoBalancedBST(head) temp.next = DLLtoBalancedBST(q) return temp #---------------------------------------------------------- def BuildBST(A, left, right) : if(left > right): return None newNode = Node() if(not newNode) : print("Memory Error") return if(left == right): newNode.data = A[left] newNode.left = None newNode.right = None else : mid = left + (right - left) / 2 newNode.data = A[mid] newNode.left = BuildBST(A, left, mid - 1) newNode.right = BuildBST(A, mid + 1, right) return newNode if __name__ == "__main__": # create the sample BST A = [2, 3, 4, 5, 6, 7] root = BuildBST(A, 0, len(A) - 1) print "\ncreating BST" printBST(root) #------------------------------------------------------- count = 0 def kthSmallestInBST(root, k): global count if (not root): return None left = kthSmallestInBST(root.left, k) if (left): return left count += 1 if (count == k): return root return kthSmallestInBST(root.right, k) #------------------------------------------------------- def SortedListToBST(ll, start, end): if(start > end): return None # same as (start+end)/2, avoids overflow mid = start + (end - start) // 2 left = SortedListToBST(ll, start, mid - 1) root = BSTNode(ll.head.data) ll.deleteBeg() root.left = left root.right = SortedListToBST(ll, mid + 1, end) return root def convertSortedListToBST(ll, n) : return SortedListToBST(ll, 0, n - 1) #------------------------------------------------------ #PROBLEM 96 : narasimha class Answer: def maxPathSum(self, root): self.maxValue = float("-inf") self.maxPathSumRec(root) return self.maxValue def maxPathSumRec(self, root): if root == None: return 0 leftSum = self.maxPathSumRec(root.left) rightSum = self.maxPathSumRec(root.right) if leftSum < 0 and rightSum < 0: self.maxValue = max(self.maxValue, root.val) return root.val if leftSum > 0 and rightSum > 0: self.maxValue = max(self.maxValue, root.val + leftSum + rightSum) maxValueUp = max(leftSum, rightSum) + root.val self.maxValue = max(self.maxValue, maxValueUp) return maxValueUp
7b52802663db038295473e82650035fe415f4668
Blueflybird/Python_Study
/Python_Inty/practise_2020406_args.py
248
4.125
4
'''什么是*args''' # def add(num1,num2,num3): # print(num1+num2+num3) # # add(1,1,2) # def add(*args): # print(sum(args)) # # add(1,1,2,2) def add(*args): for name in args: print('i love',name) add('我','是','天','才')
8ce9dd805f8692dd0cee869a834301a105afcc83
gabrielos307/cursoPythonIntersemestral17-2
/Intermedio/Manejo de Ficheros/modSys.py
648
3.90625
4
############ # Modulo sys ############ import sys print(sys.platform) #version instalada 32 o 64 bits print(sys.version) #version del interprete print(sys.argv) #parametros por linea de comandos """>>> import sys >>> sys.ps1 '>>> ' >>> sys.ps1="$ " $ print("Hola") Hola $ sys.ps1="-> " -> sys.getrecursionlimit() 1000 -> sys.setrecursionlimit(1002) -> sys.getrecursionlimit() 1002 -> sys.version '3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)]' """ print("Parametros de la linea de comandos ",sys.argv) i=0 for parametro in sys.argv: print("Parámetro %i : %s"%(i,parametro)) i+=1
f86364ba2cb64e69ee22736009ae72f4d8bbdfd3
newmancodes/python_exercises_for_tony
/string_sequences.py
376
3.953125
4
string_values = list(input('Enter a comma separated list of strings: ').split(',')) max_found = '' for start in range(len(string_values[0])): for end in range(len(string_values[0][start:])): look_for = string_values[0][start:start+end+1] if len(look_for) > len(max_found) and look_for in string_values[1]: max_found = look_for print(max_found)
d6b496d3bea76db1f9f008150dbba15732700722
giovannyortegon/holbertonschool-machine_learning
/supervised_learning/0x07-cnn/2-conv_backward.py
3,164
4
4
#!/usr/bin/env python3 """ Convolutional Back Prop """ import numpy as np def conv_backward(dZ, A_prev, W, b, padding="same", stride=(1, 1)): """ conv_backward - performs back propagation over a convolutional layer of a neural network. Args: dZ is a numpy.ndarray of shape (m, h_new, w_new, c_new) containing the partial derivatives with respect to the unactivated output of the convolutional layer m is the number of examples h_new is the height of the output w_new is the width of the output c_new is the number of channels in the output A_prev is a numpy.ndarray of shape (m, h_prev, w_prev, c_prev) containing the output of the previous layer. h_prev is the height of the previous layer w_prev is the width of the previous layer c_prev is the number of channels in the previous layer W is a numpy.ndarray of shape (kh, kw, c_prev, c_new) containing the kernels for the convolution. kh is the filter height kw is the filter width b is a numpy.ndarray of shape (1, 1, 1, c_new) containing the biases applied to the convolution. padding is a string that is either same or valid, indicating the type of padding used. stride is a tuple of (sh, sw) containing the strides for the convolution. sh is the stride for the height sw is the stride for the width Returns: the partial derivatives with respect to the previous layer. """ m, h_new, w_new, c_new = dZ.shape _, h_prev, w_prev, c_prev = A_prev.shape kh, kw, _, _ = W.shape ph = pw = 0 sh, sw = stride dA_prev = np.zeros(A_prev.shape) dW = np.zeros(W.shape) db = np.sum(dZ, axis=(0, 1, 2), keepdims=True) if padding == 'same': ph = int(np.ceil(((sh * h_prev) - sh + kh - h_prev) / 2)) pw = int(np.ceil(((sw * w_prev) - sw + kw - w_prev) / 2)) A_pad = np.pad( A_prev, ((0, 0), (ph, ph), (pw, pw), (0, 0)), 'constant' ) dA_pad = np.pad( dA_prev, ((0, 0), (ph, ph), (pw, pw), (0, 0)), 'constant' ) for i in range(m): a_pad = A_pad[i] da_prev = dA_pad[i] for h in range(h_new): for w in range(w_new): for c in range(c_new): v_start = h * sh v_end = h * sh + kh h_start = w * sw h_end = w * sw + kw slice_img = a_pad[v_start:v_end, h_start:h_end, :] da_prev[ v_start:v_end, h_start:h_end, : ] += W[:, :, :, c] * dZ[i, h, w, c] dW[:, :, :, c] += slice_img * dZ[i, h, w, c] if padding == 'same': dA_prev[i, :, :, :] = da_prev[ph:-ph, pw:-pw, :] else: dA_prev[i, :, :, :] = da_prev[:, :, :] return dA_prev, dW, db
ea314d6bae8572c19d84c0ce5b143594ba3a75a6
Bharath-6/Assignemnt-module5
/remove items from dict Q6.py
484
4.125
4
# Initializing dictionary test_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" : 21} # Printing dictionary before removal print ("The dictionary before performing remove is : " + str(test_dict)) # Using del to remove a dict # removes Mani del test_dict['Mani'] # Printing dictionary after removal print ("The dictionary after remove is : " + str(test_dict)) # Using del to remove a dict # raises exception del test_dict['Manjeet']
34c6793e81d6daaca7b5958586fda3bc66bcd36e
27Saidou/cours_python
/Algorithme_Permutation.py
230
3.859375
4
# a=5 a=int(input("Entrez la valeur de A!")) # b=10 b=int(input("Entrez la valeur de B!")) a=a+b #a=5+10=>a=15 b=a-b #b=15-10=>b=5 a=a-b #a=15-5=>a=10 print("La nouvelle valeur de A est:",a) print("La nouvelle valeur de B est:",b)
fb367a7622fa6bf2a1bde591a502cc024cfb888c
ChangxingJiang/LeetCode
/0001-0100/0014/0014_Python_1.py
870
3.90625
4
from typing import List class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: # 处理空列表的情况 if len(strs) == 0: return "" # 统计最长的字符串长度 min_len = min([len(s) for s in strs]) # 处理只有空字符串的情况 if min_len == 0: return "" for i in range(min_len): t = strs[0][i] for s in strs: if s[i] != t: return strs[0][0:i] return strs[0][0:min_len] if __name__ == "__main__": print(Solution().longestCommonPrefix(["flower", "flow", "flight"])) print(Solution().longestCommonPrefix(["dog", "racecar", "car"])) print(Solution().longestCommonPrefix([])) print(Solution().longestCommonPrefix([""])) print(Solution().longestCommonPrefix(["a"]))
074e36169c24ced4c1bf69f522073f560b716c01
Jcontresco/for_loop_basics1
/for_loop_basic1.py
2,449
3.734375
4
#Básico : imprime todos los enteros del 0 al 150. ''' for x in range(0, 151,): print(x) ''' #Múltiplos de cinco : imprime todos los múltiplos de 5 de 5 a 1,000 ''' for y in range(5, 1001, 5): print(y) ''' #Contar, Dojo Way - imprime enteros del 1 al 100. Si es divisible por 5, imprima "Coding" en su lugar. Si es divisible por 10, imprima "Coding Dojo". ''' for z in range(0, 101): if z % 10 == 0: print('Coding Dojo') continue elif z % 5 == 0 : print('Coding') else: print(z) ''' #¡Uf, Eso es bastante grande!: suma enteros impares de 0 a 500,000 e imprime la suma final. ''' #num = 500000 num = int(input("Please, enter a number:")) total = 0 for i in range(0, num + 1): if i % 2 != 0: total += i print("Suma de los valores impares en el rango 1 a {} is {}".format(num,total)) ''' #Cuenta regresiva por cuatro : imprime números positivos del 2018 al 0, restando 4 en cada iteración. ''' num = 2018 for i in range(0,num+1,--4): print(" ", num-i) ''' #Contador flexible : establece tres variables: lowNum, highNum, mult. Comenzando en lowNum y pasando por highNum, imprima solo los enteros que son múltiplos de mult. Por ejemplo, si lowNum = 2, highNum = 9 y mult = 3, el bucle debe imprimir 3, 6, 9 (en líneas sucesivas) ''' lowNum = 2 #int(input("Ingrese el numero menor:")) highNum = 9 #int(input("Ingrese el numero mayor:")) mult = 3 #int(input("Ingrese el multiplo que desea condicionar:")) for n in range(lowNum, highNum+1): if n % mult == 0: print(n) ''' #BONUS: ¿Cómo se puede detectar si un número es primo? ¿Cómo retornar una lista con los primos entre el 1 y el 1000? # OP 1 ''' lowNum = 1 highNum = 1000 while lowNum <=highNum: contador = 1 x = 0 while contador <= lowNum: if lowNum % contador == 0: x=x+1 contador = contador + 1 if x == 2: print(lowNum) lowNum = lowNum + 1 ''' #OP 2 ''' def numeros_primos(inicio, fin): contador = inicio numeros_primos = 0 while (contador <= fin): divisibles = 0 i = 1 while (i <= contador): if (contador % i == 0): divisibles +=1 i+=1 if divisibles == 2: numeros_primos +=1 contador +=1 print("Entre {} y {} hay {} numeros primos".format(inicio, fin, numeros_primos)) numeros_primos(1,1000) ''' #FIN
5567be33551c3b06513c35777752adcc681a53c1
anselrognlie/kanji-worksheet
/builddb/addkanken.py
3,388
3.546875
4
#!/usr/local/bin/python3 class KanjiRecord: def __init__(self, kanji, grade, english, readings): self.kanji = kanji self.grade = grade self.english = english self.readings = readings self.kanken = None class KanjiRecordKankenRater: def __init__(self, db, kk4, kk3, kk2_5): self.db = db self.kk4 = kk4 self.kk3 = kk3 self.kk2_5 = kk2_5 def applyRating(self): # simple rating for grades 1 (10) through 6 (5) kanken = 10 kyoiku = 1 for kyoiku in range(1, 7): grade = self.db.get(str(kyoiku)) for rec in grade: rec.kanken = str(kanken); kanken -= 1 # now do the more complicated S kanji # check each record against each kanken list, # if not found it must be 2 grade = self.db.get("S") for rec in grade: if rec.kanji in self.kk4: rec.kanken = "4" elif rec.kanji in self.kk3: rec.kanken = "3" elif rec.kanji in self.kk2_5: rec.kanken = "2.5" else: rec.kanken = "2" def addRecord(db, record): grade = record.grade gradeList = db.get(grade) if gradeList == None : gradeList = [] db[grade] = gradeList gradeList.append(record) def loadDbFromCsv(): import csv KANJI_FILE = "joyo-kanji.csv" db = {} with open(KANJI_FILE) as csvFile: reader = csv.reader(csvFile) for row in reader: kanji = row[1] grade = row[5] english = row[7] readings = row[8].split('\n') readings = readings[0].split('、') for i in range(len(readings)): reading = readings[i].split("[")[0] readings[i] = reading record = KanjiRecord(kanji, grade, english, readings) addRecord(db, record) return db; def loadKankenList(level): import csv KANKEN_FILE = f"kanken-{level}.csv" db = set() with open(KANKEN_FILE) as csvFile: reader = csv.reader(csvFile) for row in reader: kanji = row[0] db.add(kanji) return db; def main(): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ import sys # grades = "1" # if len(sys.argv) >= 2: # grades = sys.argv[1] db = loadDbFromCsv() kanken4 = loadKankenList("4") kanken3 = loadKankenList("3") kanken2_5 = loadKankenList("2.5") rater = KanjiRecordKankenRater(db, kanken4, kanken3, kanken2_5) rater.applyRating() # print all grade 1 kanji #gradeOne = db.get("1") #gradeSix = db.get("6") #gradeS = db.get("S") #print(gradeOne[0].kanken) #print(gradeSix[0].kanken) # for x in range(10): # rec = gradeS[x] # print(f"{rec.kanji}, {rec.kanken}") import csv writer = csv.writer(sys.stdout) for key, value in db.items(): for rec in value: # filter the kanji to remove any footnote indicator (split on space) kanji = rec.kanji.split(" ") readings = ",".join(rec.readings) writer.writerow([kanji[0], rec.grade, rec.kanken, rec.english, readings]) if __name__ == '__main__': main()
9d2b8f0302bc6dd4d7abce1f09cb66a973da5d49
iamsarin/LearnDataStructuresWithPython
/L01-BasicClass/index.py
3,750
3.78125
4
import math class Shape(object): def __init__(self, color: str = 'red', filled: bool = True): self.__color = color self.__filled = filled def get_color(self) -> str: return self.__color def set_color(self, color: str): self.__color = color def is_filled(self) -> bool: return self.__filled def get_area(self) -> float: raise NotImplementedError('subclasses must override foo()!') def get_perimeter(self) -> float: raise NotImplementedError('subclasses must override foo()!') def to_string(self) -> str: raise NotImplementedError('subclasses must override foo()!') def get_xx(self): return self.__color class Circle(Shape): def __init__(self, radius: float, color: str = None, filled: bool = None): super().__init__(color, filled) self.__radius = radius def get_radius(self) -> float: print(self.get_xx()) return self.__radius def set_radius(self, radius: float): self.__radius = radius def get_area(self) -> float: return math.pi * (self.__radius * self.__radius) def get_perimeter(self) -> float: return 2 * math.pi * self.__radius def to_string(self) -> str: return 'Circle \n\tradius: ' + str(self.__radius) class Rectangle(Shape): def __init__(self, width: float = 1.0, length: float = 1.0, color: str = None, filled: bool = None): super().__init__(color, filled) self.__width = width self.__length = length def get_width(self) -> float: return self.__width def set_width(self, width: float): self.__width = width def get_length(self) -> float: return self.__length def set_length(self, length: float): self.__length = length def get_area(self) -> float: return self.__width * self.__length def get_perimeter(self) -> float: return (self.__width + self.__length) * 2 def to_string(self) -> str: return 'Rectangle \n\twidth: ' + str(self.__width) + '\n\tlength:' + str(self.__length) def _get_x(self): return 'x' class Square(Rectangle): def __init__(self, side: float = 1.0, color: str = None, filled: bool = None): super().__init__(side, side, color, filled) print(self._get_x()) def get_side(self) -> float: return self.__width def set_side(self, side: float): self.__width = side self.__length = side def set_width(self, side: float): self.__width = side self.__length = side def set_length(self, side: float): self.__width = side self.__length = side def to_string(self) -> str: return 'Square \n\tSide: ' + str(self.__width) print('Create circle has radius 3 Unit') circle = Circle(3) print(circle.get_radius()) print('Area: ', "{0:.2f}".format(circle.get_area())) print('Perimeter: ', "{0:.2f}".format(circle.get_perimeter())) print('\n') print('Create circle has radius 5 Unit that green and filled') circle = Circle(3, 'green', True) print('Area: ', "{0:.2f}".format(circle.get_area())) print('Perimeter: ', "{0:.2f}".format(circle.get_perimeter())) print('Color: ', circle.get_color()) print('isFilled: ', 'Yes' if circle.is_filled() else 'No') print('\n') print('Create rectangle width=3 length=8') rectangle = Rectangle(3, 8) print('Area: ', "{0:.2f}".format(rectangle.get_area())) print('Perimeter: ', "{0:.2f}".format(rectangle.get_perimeter())) print('\n') print('Create square 3 Unit') square = Square(3) print('Area: ', "{0:.2f}".format(square.get_area())) print('Perimeter: ', "{0:.2f}".format(square.get_perimeter())) print('\n') print(square._get_x()) print(square._t)
9d1ab7f7b6b0b6e9b002ff262ba521c4cca9d7ee
Ramblurr/CodeGolf
/prisoner/warriors/theves.py
1,392
3.53125
4
#!/usr/bin/env python """ Honor Among Thieves, by Josh Caswell I'd never sell out a fellow thief, but I'll fleece a plump mark, and I'll cut your throat if you try to cross me. """ from __future__ import division import sys PLUMPNESS_FACTOR = .33 WARINESS = 10 THIEVES_CANT = "E" + ("K" * WARINESS) try: history = sys.argv[1] except IndexError: history = "" if history: sucker_ratio = (history.count('K') + history.count('S')) / len(history) seem_to_have_a_sucker = sucker_ratio > PLUMPNESS_FACTOR # "Hey, nice t' meetcha." if len(history) < WARINESS: #"Nice day, right?" if not set(history).intersection("RE"): print 'c' # "You sunnuvab..." else: print 't' # "Hey, lemme show ya this game. Watch the queen..." elif len(history) == WARINESS and seem_to_have_a_sucker: print 't' # "Oh, s#!t, McWongski, I swear I din't know dat were you." elif history[-len(THIEVES_CANT):] == THIEVES_CANT: # "Nobody does dat t' me!" if set(history[:-len(THIEVES_CANT)]).intersection("RE"): print 't' # "Hey, McWongski, I got dis job we could do..." else: print 'c' # "Do you know who I am?!" elif set(history).intersection("RE"): print 't' # "Ah, ya almos' had da queen dat time. One more try, free, hey? G'head!" elif seem_to_have_a_sucker: print 't' # "Boy, you don't say much, do ya?" else: print 'c'
cd91b449414cf2a28609547d1c62b9019696e6c7
hengyangKing/python-skin
/Python基础/code_day_12/装饰器/装饰器对有参数函数和无参数函数进行装饰.py
679
3.984375
4
#coding=utf-8 #无参数 def Decorator(funcName): print("Decorator----"); funcName(); def func_in(): print("func_in-----"); funcName(); print("func_in2----"); return func_in; @Decorator def test(): print("-----test-----"); test(); print("-"*100); #有参数 def Decorator2(func): print("Decorator2------") def func_in(*argc,**kargc): func(*argc,**kargc); return func_in; @Decorator2 def test2(a,b,c,d,e): print(a,b,c,d,e); test2(1,2,3,4,5); print ("*"*90) #有返回值 def Decorator3(func): def func_in(): ret = func(); return ret; return func_in; def test3(): print ("test3------"); return "hahha"; print ("test3 return value is %s"%test3());
971964384447e88f3a833ac327124dcf599041e7
Ehco1996/leetcode
/labuladong/二叉树/105.从前序与中序遍历序列构造二叉树.py
1,341
3.71875
4
# # @lc app=leetcode.cn id=105 lang=python3 # # [105] 从前序与中序遍历序列构造二叉树 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def test(self, preorder=[3, 9, 20, 15, 7], inorder=[9, 3, 15, 20, 7]): return self.buildTree(preorder, inorder) def buildTree(self, preorder, inorder): """ 先把序列拆分成root和左右两颗子树,然后反过来递归 in order +------------+------+-------------+ | left child | root | right child | +------------+------+-------------+ pre order +------------+-------------+------+ | root| left child | right child | +------------+-------------+------+ """ if len(inorder) == 0 and len(preorder) == 0: return None root_val = preorder[0] root = TreeNode(root_val) pos = inorder.index(root_val) if len(inorder) == 1 and len(preorder) == 1: return root root.left = self.buildTree(preorder[1 : pos + 1], inorder[:pos]) root.right = self.buildTree(preorder[pos + 1 :], inorder[pos + 1 :]) return root # @lc code=end
7c71e2f70997d4520662f78b8ed89edc4d0bfc42
Parth1267/PythonAssignment
/31-03-2021/factorial.py
318
4.375
4
# Python 3 program to find # factorial of given number def factorial(n): if n < 0: return 0 elif n == 0 or n == 1: return 1 else: fact = 1 while(n > 1): fact *= n n -= 1 return fact # Driver Code num = 5 print("Factorial of", num, "is", factorial(num)) # This code is contributed by Dharmik Thakkar
a2e32c804fe9b5e938b677f2d6e6c3cb687c0d60
tomaszbobrucki/coffee-machine
/Problems/Calculator/task.py
543
4.03125
4
# put your python code here first = float(input()) second = float(input()) operation = input() if operation in '/, mod, div' and second == 0: print("Division by 0!") elif operation == '+': print(first + second) elif operation == '-': print(first - second) elif operation == '*': print(first * second) elif operation == 'pow': print(first ** second) elif operation == '/': print(first / second) elif operation == 'mod': print(first % second) elif operation == 'div': print(first // second)
95d86b874511a613aedb42d3a76bf18de0854688
kartikkodes/String-Practice-Python
/str2.py
105
3.71875
4
n = input("Enter a string") if len(n) > 1: print(n[0]+n[1]+n[-1]+n[-2]) else: print("Empty")
855ead9427599664234fe1f7bcc6afec188ac5f2
xsank/cabbird
/leetcode/largest_rectangle_in_histogram.py
615
3.796875
4
def largestRectangleArea(heights): heights.append(0) stack = [0] res = 0 length = len(heights) for i in range(1, length): while stack and heights[i] < heights[stack[-1]]: h = heights[stack.pop()] w = i if not stack else i - stack[-1] - 1 res = max(res, w * h) stack.append(i) return res if __name__ == "__main__": print(largestRectangleArea([2, 1, 5, 6, 2, 3, 1, 1, 1, 1, 1])) print(largestRectangleArea([2, 1, 5, 6, 2, 3])) print(largestRectangleArea([1, 2, 3, 4, 5, 6])) print(largestRectangleArea([6, 5, 4, 3, 2, 1]))
827a1e0a61c20a92a3874af1fc421614accb160f
urduhack/urduhack
/urduhack/tests/test_stop_words.py
512
3.65625
4
# coding: utf8 """ Test cases updated""" from urduhack.normalization.character import COMBINE_URDU_CHARACTERS from ..stop_words import STOP_WORDS from ..urdu_characters import URDU_ALPHABETS def test_stop_words(): """ Test case""" for word in STOP_WORDS: for chars in COMBINE_URDU_CHARACTERS: assert len(chars) == 2 assert chars not in word for character in word: assert character in URDU_ALPHABETS, F"Incorrect word: {word} and char: {character}"
b1c671f8e181b9237d75167f26a29cc398188b8a
Galaxyknight346/Tic-Tac-Toe-AI
/functions.py
1,929
3.859375
4
import random def makeBoard(): a = " " board = [[a for i in range(3)]for j in range(3)] return board def printBoard(board): c = 0 for i in range(5): if i%2 == 0: print(" "+" | ".join(board[c])) c += 1 else: print("---+---+---") def getInput(board): userrow = int(input("Row(1-3): ")) userrow -= 1 usercol = int(input("Column(1-3): ")) usercol -= 1 board[userrow][usercol] = "X" def compInput(board): comprow = random.randint(1,3) compcol = random.randint(1,3) comprow -= 1 compcol -= 1 while board[comprow][compcol] != " ": comprow = random.randint(1,3) compcol = random.randint(1,3) comprow -= 1 compcol -= 1 board[comprow][compcol] = "X" def check(board): for i in range(len(board)): if (board[i][0] == board[i][1] == board[i][2]) and board[i][0] != " ": return board[i][0] if (board[0][i] == board[1][i] == board[2][i]) and board[0][i] != " ": return board[0][i] if (board[2][0] == board[1][1] == board[0][2]) and board[2][0] != " ": return board[2][0] if (board[0][0] == board[1][1] == board[2][2]) and board[0][0] != " ": return board[0][0] for i in range(len(board)): for j in range(len(board[i])): if board[i][j] == " ": return "in progress" return "t" def ai(board): cornerCoords = [[1,1],[0,0],[0,2],[2,2],[2,0],[0,1],[1,2],[2,1],[1,0]] for i in range(len(board)): for j in range(len(board[i])): if board[i][j] == " ": board[i][j] = "O" if check(board) == "O": return board[i][j] board[i][j] = " " for c in range(len(board)): for b in range(len(board[c])): if board[c][b] == " ": board[c][b] = "X" if check(board) == "X": board[c][b] = "O" return board[c][b] = " " for i,j in cornerCoords: if board[i][j] == " ": board[i][j] = "O" return
99dc795ac864b8d9edbab08955889af6f92437aa
MarvinBertin/NLP-Algorithms
/Levenshtein Distance/LevenshteinNumpy.py
956
3.96875
4
import numpy as np def levenshtein_numpy(s1, s2, cost_sub): """Takes 2 words and a cost of substitution, returns Levenshtein distance. >>>levenshtein('foo', 'poo', cost_sub=2) 2 >>>levenshtein('intention', 'execution', cost_sub=2) 8 """ if len(s1) < len(s2): # If one word is shorter than the other then change the order (bookkeeping to be consistent) return levenshtein(s2, s1, cost_sub) if len(s2) == 0: # Make are getting a real word, # if we are not getting a real word the cost is simply dropping all the letters in one of the words return len(s1) D = np.zeros((len(s1)+1,len(s2)+1)) D[0] = range(len(s2)+1) D[:,0] = range(len(s1)+1) for i, letter1 in enumerate(s1, start = 1): for j, letter2 in enumerate(s2, start = 1): D[i,j] = min(D[i-1][j] + 1, D[i][j-1] + 1, D[i-1,j-1] + (letter1 != letter2)*cost_sub ) return D[-1][-1]
de391043cb48a94f0c1de1445575bddd04097d99
bai345767318/python-java
/python/python/day01/demo03.py
976
3.75
4
''' 数据类型和变量 ''' '''数据类型''' # 整数 a = 100 b = -5 c = 0b01010100010101 # 二进制整数 print(c) d = 0o10 # 八进制 print(d) e = 0xab12f # 十六进制 print(e) # 浮点数 f = 123456789.0 g = 1.23456789e8 # 科学计数法 h = 123.45678926 print(g) # 字符串 i = 'abc' # 用单引号 j = "xyz" # 用双引号 k = "I'm fine" print(k) # \ : 转义字符 l = 'I\'m fine' print(l) m = 'I\'m\n fine' # \n 回车键 print(m) n = 'I\'m\t fine' # \t tab键 print(n) # 输出 \ print('\\') # 输出 \\\t\\ print(r'\\\t\\') # 布尔值 o = True p = False print(3>1) # 逻辑运算 # and or not print(True and True) print(3>5 or 6>4) print(not True) # 空值 q = None print(q) # r # 未定义 # print(r) '''变量''' # 数据有类型,变量没有类型 # python是动态语言 x = 1 y = 'abc' x = 'tom' # =是赋值符号 x = 'abc' y = x x = 'def' # y=? print('y=',y) '''常量''' # 常量的全部字母大写 PI = 3.1415926 PI = 5 print(PI)
7bdd7f3ba1fe8859c6689a348ed0fcd584d1b2fb
madhuri-kesanakurthi/madhuri-kesanakurthi
/bill1.py
566
3.96875
4
amt=int(input('enter amount')) if(amt in range(1000,2000)): print('Discount is 10%') discount=amt*10/100 bill_amt=amt-discount elif(amt in range(2000,3000)): print('Discount is 20%') discount=amt*20/100 bill_amt=amt-discount elif(amt in range(3000,5000)): print('Discount is 30%') discount=amt*30/100 bill_amt=amt-discount elif(amt>=5000): print('Discount is 40%') discount=amt*40/100 bill_amt=amt-discount else: print('Your Expenses are less than 1000 , there is no discount') bill_amt=amt print (bill_amt)
e6e43409b510e3718f0bf6dc09bcbf84f87e8a63
notruilin/LeetCode
/993. Cousins in Binary Tree/isCousins.py
647
3.625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isCousins(self, root: TreeNode, x: int, y: int) -> bool: family = {} def dfs(node, father): if not node: return if father: family[node.val] = [str(father), family[father.val][1]+1] dfs(node.left, node) dfs(node.right, node) family[root.val] = [None, 0] dfs(root, None) return family[x][1] == family[y][1] and family[x][0] != family[y][0]
172026d07d1031b5b78a9d8562d3dfd69b7466a0
Andrewpqc/python_exercises
/python_algorithom/DandC.py
589
3.890625
4
def sum_recursive(l): """ 递归计算列表的元素之和 """ if len(l)==1: return l[0] else: return l[0]+sum_recursive(l[1:]) def counter_recursive(l): """ 递归统计列表的元素个数 """ if len(l)==1: return 1 else: return 1+counter_recursive(l[1:]) def max_recursive(l): """ 递归计算列表中的最大值 """ if len(l)==1: return l[0] else: if __name__=="__main__": l=[1,2,3] print("sum:",sum_recursive(l)) print("counter:",counter_recursive(l))
69b1a4abfcc6481bc621602f0745af6d8c56b66c
gemking/COMProj1-
/venv/Scripts/parser.py
19,461
3.5625
4
import re import sys with open(sys.argv[1], "r") as file: #opens file filelines = file.read().splitlines() # reads file and splits lines file.close() #closes file insideComment = 0 keywordchecklist = ["else", "if", "int", "return", "void", "while", "float"] # list of all keywords #keywords = ["if", "else", "while", "int", "float", "void", "return"] #denotes all keywords symbols = "\/\*|\*\/|\+|-|\*|//|/|<=|<|>=|>|==|!=|=|;|,|\(|\)|\{|\}|\[|\]" #denotes symbols used comparisonSymbols = "<" or "<=" or ">" or ">=" or "==" or"!=" addSubtractSymbols = "+" or "-" multiplyDivideSymbols = "*" or "/" characters = "[a-zA-Z]+" #obtains all words for the IDs digits = "[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?" #gets all decimal values, including integer values 0-9 errors = "\S" #reports errors token = [] #creates a list that holds all of the tokens i = 0 #value that holds the token counter for the parser for importantLines in filelines: #receiving importantlines from filelines importantLine = importantLines #sets importantLine to importantLines if not importantLine: continue list = "(%s)|(%s)|(%s)|(%s)" % (characters, digits, symbols, errors) #puts entire library into a list of strings for word in re.findall(list, importantLine): #finds list if re.match(characters, word[0]) and insideComment == 0: #matches digits and makes sure insideComment is 0 if word[0] in keywordchecklist: token.append("KEYWORD: " + word[0]) #keyword is constructed out of characters a-zA-Z else: token.append("ID: " + word[0]) # appends character values that are not keywords elif re.match(digits, word[1]) and insideComment == 0: #matches characters and makes sure insideComment is 0 if "." in word[1]: token.append("FLOAT: " + word[1]) #checks if value is a decimal value and appends elif "E" in word[1]: token.append("FLOAT: " + word[1]) #checks if value is an expontential value and appends else: token.append("INTEGER: " + word[1]) #appends integer value elif re.match(symbols, word[3]): #matches symbols if "/*" in word[3]: #Checks when word approaches /* insideComment += 1 #increments insideComment if inside elif "*/" in word[3] and insideComment > 0: #Checks when word approaches */ insideComment -= 1 #decrements insideComment if outside elif "//" in word[3] and insideComment > 0: #If neither break elif insideComment == 0: #when inside counter is 0 if "*/" in word[3]: #when it reaches terminal */ if "*/*" in word: #when it's still sorting through comments token.append("*") insideComment += 1 continue #skips comments and continues through the program else: token.append("*") #appends multiplication symbol token.append("/") #appends division symbol else: token.append(word[3]) #appends rest of symbols elif word[4] and insideComment == 0: #matches errors and makes sure insideComment is 0 token.append("ERROR: " + word[4]) #appends error #end of lexical analyzer token.append("$") #end result for parsing #parser # ---------------------------------- parsing functions ----------------------------------- # def hasnum(inputstring): return any(char.isdigit() for char in inputstring) def program(): # 1 dollarOne() if "$" in token[i]: print("ACCEPT") else: print ("REJECT") def dollarOne(): # 2 declaration() dollarOnePrime() def dollarOnePrime(): # 3 if "int" in token[i] or "void" in token[i] or "float" in token[i]: declaration() dollarOnePrime() elif "$" in token[i]: return else: return def declaration(): # 4 global i types() x = token[i].isalpha() if token[i] not in keywordchecklist and x is True: i += 1 # Accept ID if ";" in token[i]: i += 1 # Accept ; elif "[" in token[i]: i += 1 # Accept [ y = hasnum(token[i]) if y is True: i += 1 # Accept NUM/FLOAT if "]" in token[i]: i += 1 # Accept ] if ";" in token[i]: i += 1 # Accept ; else: print("REJECT") sys.exit(0) else: print("REJECT") sys.exit(0) else: print("REJECT") sys.exit(0) elif "(" in token[i]: i += 1 # Accept ( parameters() if ")" in token[i]: i += 1 # Accept ) compoundStatement() else: print("REJECT") sys.exit(0) else: print("REJECT") sys.exit(0) else: print("REJECT") sys.exit(0) def variableDeclaration(): # 5 global i types() x = token[i].isalpha() if token[i] not in keywordchecklist and x is True: i += 1 # Accept ID else: print("REJECT") sys.exit(0) if ";" in token[i]: i += 1 # Accept ; elif "[" in token[i]: i += 1 # Accept [ x = hasnum(token[i]) if x is True: i += 1 # Accept NUM/FLOAT if "]" in token[i]: i += 1 # Accept ] if ";" in token[i]: i += 1 # Accept ; return else: print("REJECT") sys.exit(0) else: print("REJECT") sys.exit(0) else: print("REJECT") sys.exit(0) else: print("REJECT") sys.exit(0) # checking if in keywords messes up program process def types(): # 6 global i if "int" in token[i] or "void" in token[i] or "float" in token[i]: i += 1 # Accept int/void/float else: return def checker2(): # 7 global i types() x = token[i].isalpha() if token[i] not in keywordchecklist and x is True: i += 1 # Accept ID else: return if "(" in token[i]: i += 1 # Accept ( else: print() sys.exit(0) parameters() if ")" in token[i]: i += 1 # Accept ) else: print("REJECT") sys.exit(0) compoundStatement() def parameter(): global i types() x = token[i].isalpha() if token[i] not in keywordchecklist and x is True: i += 1 # Accept ID else: return if "[" in token[i]: i += 1 # Accept [ if "]" in token[i]: i += 1 # Accept ] return else: print("REJECT") sys.exit(0) else: return def parameters(): # 8 global i if "int" in token[i] or "float" in token[i]: parametersList() elif "void" in token[i]: i += 1 # Accept void return else: print("REJECT") sys.exit(0) def parametersList(): # 9 parameter() parametersListPrime() def parametersListPrime(): # 10 global i if "," in token[i]: i += 1 # Accept , parameter() parametersListPrime() elif ")" in token[i]: return else: return def compoundStatement(): # 12 global i if "{" in token[i]: i += 1 # Accept { else: return localDeclarations() statementList() if "}" in token[i]: i += 1 # Accept } else: print("REJECT") sys.exit(0) def localDeclarations(): # 13 localDeclarationsPrime() def localDeclarationsPrime(): # 14 if "int" in token[i] or "void" in token[i] or "float" in token[i]: checker1() localDeclarationsPrime() else: return def statementList(): # 15 statementListPrime() def statementListPrime(): # 16 x = token[i].isalpha() y = hasnum(token[i]) if token[i] not in keywordchecklist and x is True: statement() statementListPrime() elif y is True: statement() statementListPrime() elif "(" in token[i] or ";" in token[i] or "{" in token[i] or "if" in token[i] or "while" in token[i] or "return" in token[i]: statement() statementListPrime() elif "}" in token[i]: return else: return def statement(): # 17 x = token[i].isalpha() y = hasnum(token[i]) if token[i] not in keywordchecklist and x is True: expressionStatement() elif y is True: expressionStatement() elif "(" in token[i] or ";" in token[i]: expressionStatement() elif "{" in token[i]: compoundStatement() elif "if" in token[i]: selectionStatement() elif "while" in token[i]: itStatement() elif "return" in token[i]: returnStatement() else: print("REJECT") sys.exit(0) def expressionStatement(): # 18 global i x = token[i].isalpha() y = hasnum(token[i]) if token[i] not in keywordchecklist and x is True: expression() if ";" in token[i]: i += 1 # Accept ; else: print("REJECT") sys.exit(0) elif y is True: expression() if ";" in token[i]: i += 1 # Accept ; else: print("REJECT") sys.exit(0) elif "(" in token[i]: expression() if ";" in token[i]: i += 1 # Accept ; else: print("REJECT") sys.exit(0) elif ";" in token[i]: i += 1 # Accept ; else: print("REJECT") sys.exit(0) def selectionStatement(): # 19 global i if "if" in token[i]: i += 1 # Accept if else: return if "(" in token[i]: i += 1 # Accept ( else: print("REJECT") sys.exit(0) expression() if ")" in token[i]: i += 1 # Accept ) else: print("REJECT") sys.exit(0) statement() if "else" in token[i]: i += 1 # Accept else statement() else: return def itStatement(): # 20 global i if "while" in token[i]: i += 1 # Accept while else: return if "(" in token[i]: i += 1 # Accept ( else: print("REJECT") sys.exit(0) expression() if ")" in token[i]: i += 1 # Accept ) else: print("REJECT") sys.exit(0) statement() def returnStatement(): # 21 global i if "return" in token[i]: i += 1 # Accept return else: return x = token[i].isalpha() y = hasnum(token[i]) if ";" in token[i]: i += 1 # Accept ; return elif token[i] not in keywordchecklist and x is True: expression() if ";" in token[i]: i += 1 # Accept ; return else: print("REJECT") sys.exit(0) elif y is True: expression() if ";" in token[i]: i += 1 # Accept ; return else: print("REJECT") sys.exit(0) elif "(" in token[i]: expression() if ";" in token[i]: i += 1 # Accept ; return else: print("REJECT") sys.exit(0) else: print("REJECT") sys.exit(0) def expression(): # 22 global i x = token[i].isalpha() y = hasnum(token[i]) if token[i] not in keywordchecklist and x is True: i += 1 # Accept ID moreExpressions() elif "(" in token[i]: i += 1 # Accept ( expression() if ")" in token[i]: i += 1 # Accept ) termPrime() addExpressionPrime() if comparisonSymbols in token[i]: comparisonOperation() addExpression() elif addSubtractSymbols in token[i]: addExpressionPrime() if comparisonSymbols in token[i]: comparisonOperation() addExpression() elif comparisonSymbols in token[i]: comparisonOperation() addExpression() else: return else: print("REJECT") sys.exit(0) elif y is True: i += 1 # Accept NUM/FLOAT termPrime() addExpressionPrime() if comparisonSymbols in token[i]: comparisonOperation() addExpression() elif addSubtractSymbols in token[i]: addExpressionPrime() if comparisonSymbols in token[i]: comparisonOperation() addExpression() elif comparisonSymbols in token[i]: comparisonOperation() addExpression() else: return else: print("REJECT") sys.exit(0) def moreExpressions(): # 22X global i if "=" in token[i]: i += 1 # Accept = expression() elif "[" in token[i]: i += 1 # Accept [ expression() if "[" in token[i-1]: print("REJECT") sys.exit(0) if "]" in token[i]: i += 1 # Accept ] if "=" in token[i]: i += 1 # Accept = expression() elif multiplyDivideSymbols in token[i]: termPrime() addExpressionPrime() if comparisonSymbols in token[i]: comparisonOperation() addExpression() else: return elif addSubtractSymbols in token[i]: addExpressionPrime() if comparisonSymbols in token[i]: comparisonOperation() addExpression() elif comparisonSymbols in token[i]: comparisonOperation() addExpression() else: return else: print("REJECT") sys.exit(0) elif "(" in token[i]: i += 1 # Accept ( arguments() if ")" in token[i]: i += 1 # Accept ) if multiplyDivideSymbols in token[i]: termPrime() addExpressionPrime() if comparisonSymbols in token[i]: comparisonOperation() addExpression() else: return elif addSubtractSymbols in token[i]: addExpressionPrime() if comparisonSymbols in token[i]: comparisonOperation() addExpression() elif comparisonSymbols in token[i]: comparisonOperation() addExpression() else: return else: print("REJECT") sys.exit(0) elif multiplyDivideSymbols in token[i]: termPrime() addExpressionPrime() if comparisonSymbols in token[i]: comparisonOperation() addExpression() else: return # error begins elif addSubtractSymbols in token[i]: addExpressionPrime() if comparisonSymbols in token[i]: comparisonOperation() addExpression() else: return elif comparisonSymbols in token[i]: comparisonOperation() addExpression() else: return def variable(): # 23 global i x = token[i].isalpha() if token[i] not in keywordchecklist and x is True: i += 1 # Accept ID else: return if "[" in token[i]: i += 1 # Accept [ expression() if "]" in token[i]: i += 1 # Accept ] else: print("REJECT") sys.exit(0) else: return def simplifyExpression(): # 24 addExpression() if comparisonSymbols in token[i]: comparisonOperation() addExpression() else: return def comparisonOperation(): # 25 global i if comparisonSymbols in token[i]: i += 1 # Accept <=, <, >, >=, ==, or != else: return def addExpression(): # 26 term() addExpressionPrime() def addExpressionPrime(): # 27 if addSubtractSymbols in token[i]: addOperation() term() addExpressionPrime() else: return def addOperation(): # 28 global i if addSubtractSymbols in token[i]: i += 1 # Accept +, - else: return def term(): # 29 factor() termPrime() def termPrime(): # 30 if multiplyDivideSymbols in token[i]: multiplyOperation() factor() termPrime() else: return def multiplyOperation(): # 31 global i if multiplyDivideSymbols in token[i]: i += 1 # Accept *, / else: return def factor(): # 32 global i x = token[i].isalpha() y = hasnum(token[i]) if token[i] not in keywordchecklist and x is True: i += 1 # Accept ID if "[" in token[i]: i += 1 # Accept [ expression() if "]" in token[i]: i += 1 # Accept ] else: return elif "(" in token[i]: i += 1 # Accept ( arguments() if ")" in token[i]: i += 1 # Accept ) else: return else: return elif y is True: i += 1 # Accept NUM/FLOAT elif "(" in token[i]: i += 1 # Accept ( expression() if ")" in token[i]: i += 1 # Accept ) else: return else: print("REJECT") sys.exit(0) def call(): # 33 global i x = token[i].isalpha() if token[i] not in keywordchecklist and x is True: i += 1 # Accept ID if "(" in token[i]: i += 1 # Accept ( arguments() if ")" in token[i]: i += 1 # Accept ) else: print("REJECT") sys.exit(0) else: print("REJECT") sys.exit(0) else: return def arguments(): # 34 global i x = token[i].isalpha() y = hasnum(token[i]) if token[i] not in keywordchecklist and x is True: argumentsList() elif y is True: argumentsList() elif "(" in token[i]: argumentsList() elif ")" in token[i]: return else: return def argumentsList(): # 35 expression() argumentslistPrime() def argumentslistPrime(): # 36 global i if "," in token[i]: i += 1 # Accept , expression() argumentslistPrime() elif ")" in token[i]: return else: return # ----------------------------- end of parsing functions --------------------------------- # # begin parsing program()
32be2d9afd39d2d95a49e6e0ea61322a54237461
jonachung/uvaproblems
/p10050.py
635
3.515625
4
def main(): testCases = int(input()) for case in range(testCases): numDays = int(input()) calendar = [] for day in range(numDays): calendar.append(False) numParties = int(input()) for p in range(numParties): partyDay = int(input()) calendar[partyDay - 1] = True for day in range(partyDay - 1, len(calendar), partyDay): calendar[day] = True count = 0 for day in range(len(calendar)): if calendar[day] and day % 7 != 5 and day % 7 != 6: count += 1 print(count) main()
dcdce966cb6a996846de18e58c3ca9ce056e9f3f
MohamedMurad/Computer-Vision-Exercises
/Stereo Vision/dynamic_programming_disparity.py
2,782
3.734375
4
#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import cv2 from matplotlib import pyplot as plt # Stereo Matching function as per the given paper def stereoMatching(leftImg, rightImg): # image shape (rows, cols) = leftImg.shape # matrices to store disparities: left and right left_disp = np.zeros((rows, cols)) right_disp = np.zeros((rows, cols)) # some constants sig = 2 c0 = 5 # Pick a row in the image to be matched for c in range(0, rows): # Disparity path matrix disp_matrix = np.zeros((cols, cols)) # Cost matrix cost_matrix = np.zeros((cols, cols)) # Initialize the cost matrix for i in range(0, cols): cost_matrix[i][0] = i * c0 cost_matrix[0][i] = i * c0 # Iterate the row in both the images to find the path using dynamic programming for k in range(0, cols): for j in range(0, cols): # calculate matcing cost match_cost = ((leftImg[c][k] - rightImg[c][j]) ** 2 )/ (sig ** 2) # Finding minimum cost min1 = cost_matrix[k - 1][j - 1] + match_cost min2 = cost_matrix[k - 1][j] + c0 min3 = cost_matrix[k][j - 1] + c0 cost_matrix[k][j] = min(min1, min2, min3) # marking the path if cost_matrix[k][j] == min1: disp_matrix[k][j] = 1 if cost_matrix[k][j] == min2: disp_matrix[k][j] = 2 if cost_matrix[k][j] == min3: disp_matrix[k][j] = 3 # backtracking and update the disparity value i = cols - 1 j = cols - 1 while i != 0 and j != 0: if disp_matrix[i][j] == 1: left_disp[c][i] = np.absolute(i - j) right_disp[c][j] = np.absolute(j - i) i = i - 1 j = j - 1 elif disp_matrix[i][j] == 2: left_disp[c][i] = 0 i = i - 1 elif disp_matrix[i][j] == 3: right_disp[c][j] = 0 j = j - 1 return left_disp, right_disp def main(): # determine path to read images path = 'samples/sample2/' # Read images. leftImg = cv2.imread(path + 'img1.png', 0) leftImg = np.asarray(leftImg, dtype=np.float) rightImg = cv2.imread(path + 'img2.png', 0) rightImg = np.asarray(rightImg, dtype=np.float) # Call disparity matching algorithm left_disp, right_disp = stereoMatching(leftImg, rightImg) # save images cv2.imwrite(path + 'left_disparity' + '.png', left_disp) cv2.imwrite(path + 'right_disparity' + '.png', right_disp) main()
9b508908eddd78c221b376455eced77f41a29b98
BoyYongXin/algorithm
/Problemset/reorder-list/reorder-list.py
1,293
3.75
4
# @Title: 重排链表 (Reorder List) # @Author: 18015528893 # @Date: 2021-02-04 15:38:09 # @Runtime: 104 ms # @Memory: 23.7 MB # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ if head is None: return if head.next is None: return slow = head fast = head.next # 如果是fast=head,那么对于长度为偶数的链表是落在后中点,如果是fast=head.next则落在前中点 while fast and fast.next: slow = slow.next fast = fast.next.next q = self.reverse(slow.next) slow.next = None p = head while p.next: tmp = p.next p.next = q q = q.next p.next.next = tmp p = p.next.next if q: p.next = q return def reverse(self, head): pre = None cur = head while cur: next_tmp = cur.next cur.next = pre pre = cur cur = next_tmp return pre
a853f2fb5f6f55804b0c6e8f6025cde2a7962f65
gistable/gistable
/all-gists/3754590/snippet.py
456
3.78125
4
#!/usr/bin/python def f(x): return x*x def fastmodexp(x, y, mod): p = 1 aux = x while y > 0: if y % 2 == 1: p = (p * aux) % mod aux = (aux * aux) % mod y = y >> 1 return p def main(): x = int(raw_input("Escribe tu x -> ")) d = int(raw_input("Escribe tu d -> ")) n = int(raw_input("Escribe tu n -> ")) y = f(x) r = fastmodexp(y, d, n) print "Esta es tu r = " + str(r) main()
171599f0f7b2f3127a8a99aa507bfd5b7e548c37
MasterAlexM/SnakePyGame
/Main.py
4,589
3.609375
4
#Importation import pygame import Difficulties #Initialisaiton des couleurs WHITE = pygame.Color(255, 255, 255) GREY = pygame.Color(160,160,160) GREYY = pygame.Color(100,100,100) BLUE = pygame.Color(0,0,255) #Initialisation de l'écran de jeu pygame.init() screenSize = 800 screen = pygame.display.set_mode((screenSize,screenSize))#init display a 800x800 pygame.display.set_caption('Snake') screen.fill(WHITE) border = 50 mazeSize = screenSize-border*2 pygame.draw.rect(screen,GREY,(border,border,mazeSize,mazeSize)) #Initialisation des principales variables du Snake up = 0 right = 1 dn = 2 left = 3 Snake = [[1,0]] direction = right running = True waze = Difficulties.difficulties("easy") #Création de la grille de jeu for i in range(20): for y in range(20): pygame.draw.rect(screen,GREY,(border,border,mazeSize,mazeSize)) for i in range(21): pygame.draw.lines(screen,GREYY,False,[(border + (35*i), border),(border + (35*i), border + mazeSize)], 3) pygame.draw.lines(screen,GREYY,False,[(border , border+ (35*i)),(border+ mazeSize, border + (35*i))], 3) pygame.display.update() keys = [] while running: #Délai du jeu pour l'affichage pygame.time.delay(300) #Lecture des évènements for event in pygame.event.get(): #Exit if event.type == pygame.QUIT:#Exit running = False #Si une touche est appuyé if event.type == pygame.KEYDOWN: keys = pygame.key.get_pressed() #Flèche de gauche if keys[pygame.K_LEFT]: direction = left #Flèche de droite elif keys[pygame.K_RIGHT]: direction = right #Flèche du haut elif keys[pygame.K_UP]: direction = up #Flèche du bas elif keys[pygame.K_DOWN]: direction = dn #On tourne a droite if(direction == right): for i in range(len(Snake)): if(i==0): DrawSnake.drawErase(screen,border + 5 + 35 * Snake[i][0], border + 5 + 35 * Snake[i][1]) Snake[i][0]+= 1 DrawSnake.drawSnakeHead(screen,border + 5 + 35 * Snake[i][0],border + 5 + 35 * Snake[i][1],right) if(i>0): DrawSnake.drawErase(screen,border+5 + 35*Snake[i][0],border+5 + 35*Snake[i][1]) Snake[i] = Snake[0] Snake[i][0] -= 1 DrawSnake.drawSnakeCorpse(screen,border+5 + 35 * Snake[i][0],border + 5 + 35 * Snake[i][1]) #On tourne a gauche elif(direction == left): for i in range(len(Snake)): if(i==0): DrawSnake.drawErase(screen,border + 5 + 35 * Snake[i][0], border + 5 + 35 * Snake[i][1]) Snake[i][0]-= 1 DrawSnake.drawSnakeHead(screen,border + 5 + 35 * Snake[i][0],border + 5 + 35 * Snake[i][1],left) if(i>0): DrawSnake.drawErase(screen,border+5 + 35*Snake[i][0],border+5 + 35*Snake[i][1]) Snake[i] = Snake[0] Snake[i][0] += 1 DrawSnake.drawSnakeCorpse(screen,border+5 + 35 * Snake[i][0],border + 5 + 35 * Snake[i][1]) #On tourne en haut elif(direction == up): for i in range(len(Snake)): if(i==0): DrawSnake.drawErase(screen,border + 5 + 35 * Snake[i][0], border + 5 + 35 * Snake[i][1]) Snake[i][1]-= 1 DrawSnake.drawSnakeHead(screen,border + 5 + 35 * Snake[i][0],border + 5 + 35 * Snake[i][1],up) if(i>0): DrawSnake.drawErase(screen,border+5 + 35*Snake[i][0],border+5 + 35*Snake[i][1]) Snake[i] = Snake[0] Snake[i][1] += 1 DrawSnake.drawSnakeCorpse(screen,border+5 + 35 * Snake[i][0],border + 5 + 35 * Snake[i][1]) #On tourne en bas elif(direction == dn): for i in range(len(Snake)): if(i==0): DrawSnake.drawErase(screen,border + 5 + 35 * Snake[i][0], border + 5 + 35 * Snake[i][1]) Snake[i][1] += 1 DrawSnake.drawSnakeHead(screen,border + 5 + 35 * Snake[i][0],border + 5 + 35 * Snake[i][1],dn) if(i>0): DrawSnake.drawErase(screen,border+5 + 35*Snake[i][0],border+5 + 35*Snake[i][1]) Snake[i] = Snake[0] Snake[i][1] -= 1 DrawSnake.drawSnakeCorpse(screen,border+5 + 35 * Snake[i][0],border + 5 + 35 * Snake[i][1]) #if evenement.type == pygame.KEYDOWN: pygame.quit()#on quitte le programme
6ebc9777085327e460c1dce3ec45a50607b50bd9
amensh07/start_python-
/hw - 6.2.py
383
3.578125
4
class Road: def first(self, _length, _width): self._length = _length self._width = _width def _area(self): result = self._length * self._width * 25 * 5 print(f'Масса асфальта,необходимая для покрытия всего дорожного полотна = {result}') road = Road() road.first(10, 15) road._area()
1251fb6e265138164951077854cbb4de9c8869ac
jonam-code/Machine-Learning-Laboratory
/2/Machine-Learning-Algorithms-from-Scratch-master/Linear Regression.py
3,966
3.578125
4
#================================================================================================================ #---------------------------------------------------------------------------------------------------------------- # SIMPLE LINEAR REGRESSION #---------------------------------------------------------------------------------------------------------------- #================================================================================================================ #Simple linear regression is applied to stock data, where the x values are time and y values are the stock closing price. #This is not an ideal application of simple linear regression, but it suffices to be a good experiment. import math import numpy as np import matplotlib.pyplot as plt from matplotlib import style import pandas import datetime #Quandl for getting stock data import quandl #for plotting plt.style.use('ggplot') class CustomLinearRegression: def __init__(self): self.intercept = 0 self.slope = 0 #arithmetic mean def am(self, arr): tot = 0.0 for i in arr: tot+= i return tot/len(arr) #finding the slope in best fit line def best_fit(self, dimOne, dimTwo): self.slope = ( (self.am(dimOne) * self.am(dimTwo) ) - self.am(dimOne*dimTwo) ) / ( self.am(dimOne)**2 - self.am(dimOne**2) ) #formula for finding slope return self.slope #finding the best fit intercept def y_intercept(self, dimOne ,dimTwo): self.intercept = self.am( dimTwo ) - ( self.slope * self.am(dimOne) ) return self.intercept #predict for future values based on model def predict(self, ip): ip = np.array(ip) predicted = [(self.slope*param) + self.intercept for param in ip] #create a "predicted" array where the index corresponds to the index of the input return predicted #find the squared error def squared_error(self, original, model): return sum((model - original) **2) #find co-efficient of determination for R^2 def cod(self, original, model): am_line = [self.am(original) for y in original] sq_error = self.squared_error(original, model) sq_error_am = self.squared_error(original, am_line) return 1 - (sq_error/sq_error_am) #R^2 is nothing but 1 - of squared error for our model / squared error if the model only consisted of the mean def main(): stk = quandl.get("WIKI/TSLA") simpl_linear_regression = CustomLinearRegression() #reset index to procure date - date was the initial default index stk = stk.reset_index() #Add them headers stk = stk[['Date','Adj. Open','Adj. High','Adj. Low','Adj. Close', 'Volume']] stk['Date'] = pandas.to_datetime(stk['Date']) stk['Date'] = (stk['Date'] - stk['Date'].min()) / np.timedelta64(1,'D') #The column that needs to be forcasted using linear regression forecast_col = 'Adj. Close' #take care of NA's stk.fillna(-999999, inplace = True) stk['label'] = stk[forecast_col] #IN CASE THE INPUT IS TO BE TAKEN IN FROM THE COMMAND PROMPT UNCOMMENT THE LINES BELOW #takes in input from the user #x = list(map(int, input("Enter x: \n").split())) #y = list(map(int, input("Enter y: \n").split())) #convert to an numpy array with datatype as 64 bit float. #x = np.array(x, dtype = np.float64) #y = np.array(y, dtype = np.float64) stk.dropna(inplace = True) x = np.array(stk['Date']) y = np.array(stk['label']) #Always in the order: first slope, then intercept slope = simpl_linear_regression.best_fit(x, y) #find slope intercept = simpl_linear_regression.y_intercept(x, y) #find the intercept ip = list(map(int, input("Enter x to predict y: \n").split())) line = simpl_linear_regression.predict(ip) #predict based on model reg = [(slope*param) + intercept for param in x] print("Predicted value(s) after linear regression :", line) r_sqrd = simpl_linear_regression.cod(y, reg) print("R^2 Value: " ,r_sqrd) plt.scatter(x, y) plt.scatter(ip, line, color = "red") plt.plot(x, reg) plt.show() if __name__ == "__main__": main()
9e5724977363a1881194b9852e83833e5528b623
DanielFHermanadez/Readme
/Trabajo#2/Python/Trabajo#9.py
128
3.875
4
n1 = int(input("Digite el numero: ")) if n1%2==0: print("el numero es par") else: print ("el numero es impar")
cbd2ec5da690aadfe2cf1a88adebec5bc83205b4
rajitbanerjee/kattis
/Datum/datum.py
364
3.515625
4
"""https://open.kattis.com/problems/datum""" D, M = map(int, input().split()) months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 01/01/2009 was a Thursday day = ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"] total_days = 0 for i in range(M): total_days += months[i] total_days += D print(day[total_days % 7 - 1])
010f96de082eb5d4b463858c8655947a34ba4f16
Jflinchum/asl-recognition
/util.py
864
3.859375
4
def getCoord(percentX, percentY, image_size): """ Returns the width and height coordinates given the percentage of the image size you want percentX - percentage along x axis percentY - percentage along y axis image_size - tuple (width, height) of the total size of the image @return - tuple formatted as (x, y) coordinates """ width, height = image_size # Unpack tuple size = (int(width*(percentX/100.0)), int(height*(percentY/100.0))) return size def getFontSize(scale, image_size): """ Returns the font size depending on the size of the image scale - How large the font should be image_size - tuple of width and height of image @return - floating point value of font size """ imageScale = 2000. totalSize = image_size[0] + image_size[1] return scale * (totalSize / imageScale)
dd5df38a9abfba10698099e7879146f7f1c1616f
isobelfc/eng84_python_tdd_exercises
/bread_factory.py
573
3.859375
4
# Bread factory exercise class Bread(): def make_dough(self, ingredient1, ingredient2): if ingredient1 == "water" and ingredient2 == "flour": return "dough" else: return "recipe unknown" def bake_dough(self, ingredient): if ingredient == "dough": return "naan" else: return "recipe unknown" def run_factory(self, ingredient1, ingredient2): if ingredient1 == "water" and ingredient2 == "flour": return "naan" else: return "recipe unknown"
e1ab2774e310898d36e9e335363d5499d6f60132
sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions
/ex9_3_4.py
1,211
4.3125
4
# Chapter 9 # Exercise 3: Write a program to read through a mail log, build a histogram using # a dictionary to count how many messages have come from each email address, and # print the dictionary. # Exercise 4: Add code to the above program to figure out who has the most # messages in the file. # After all the data has been read and the dictionary has been created, look through # the dictionary using a maximum loop (see Section [maximumloop]) to find who # has the most messages and print how many messages the person has. email_dict =dict() fname = input('Enter a file name:') fopen = open(fname) for line in fopen: line = line.strip() if line.startswith('From '): s = line.split() email = s[1] if email not in email_dict: email_dict[email] = 1 else: email_dict[email] = email_dict[email] + 1 print(email_dict) flag =0 for key in email_dict: if flag==0: maximum = email_dict[key] max_key = key flag = 1 else: if maximum < email_dict[key]: maximum = email_dict[key] max_key = key else: continue print(max_key, maximum)
dd415d28ad24b63ec47f41c5dc0227a9b8e4d3b1
iasminqmoura/algoritmos
/Lista 1/Exercicio03.py
417
4.0625
4
print("Insira a idade no formato de Anos/Meses/Dias. Ex: 20 anos, 2 meses e 7 dias") ano = int(input("Anos: ")) mes = int(input("Meses: ")) dia = int(input("Dias: ")) if(mes < 0 or mes > 12): print("Um ano possui 12 meses, insira um valor entre 0 e 12") else: mesDia = mes * 30 anoDia = ano * 365 totalDias = anoDia + mesDia + dia print("A idade inserida expressa em dias é: ", totalDias)
e755ba689fd28230f6bdf13b7dd74d7c59d72908
TCLloyd/pwp-capstones
/TomeRater/TomeRater.py
5,750
3.828125
4
class User(object): def __init__(self, name, email): self.name = name self.email = email self.books = {} def get_email(self): return self.email def change_email(self, address): self.email = address print("Email has been changed to {}".format(address)) def __repr__(self): return "User: {name}, Email:{email}, Books read: {b}".format(name = self.name, email = self.email, b = len(self.books.keys())) def __eq__(self, other_user): if self.name == other_user.name and self.email == other_user.email: return True else: return False def read_book(self, book, rating = None): self.books[book] = rating def get_average_rating(self): total = 0 for value in self.books.values(): if value != None: total += value return (total / len(self.books.values())) class Book: def __init__(self, title, isbn): self.title = title self.isbn = isbn self.ratings = [] def get_title(self): return self.title def get_isbn(self): return self.isbn def set_isbn(self, new_isbn): self.isbn = new_isbn def add_rating(self, rating): if rating != None: if rating < 0 or rating > 4: print("Invalid Rating") else: self.ratings.append(rating) def __eq__(self, other_book): if self.title == other_book.title and self.isbn == other_book.isbn: return True else: return False def get_average_rating(self): total = 0 for rating in self.ratings: total += rating return (total / len(self.ratings)) def __hash__(self): return hash((self.title, self.isbn)) def __repr__(self): return "{title}".format(title = self.title) class Fiction(Book): def __init__(self, title, author, isbn): super().__init__(title, isbn) self.author = author def get_author(self): return self.author def __repr__(self): return "{title} by {author}".format(title = self.title, author = self.author) class Non_Fiction(Book): def __init__(self, title, subject, level, isbn): super().__init__(title, isbn) self.subject = subject self.level = level def get_subject(self): return self.subject def get_level(self): return self.level def __repr__(self): return "{title}, a {level} manual on {subject}".format(title=self.title, level=self.level, subject=self.subject) class TomeRater: def __init__(self): self.users = {} self.books = {} self.isbns = [] def __repr__(self): return "TomeRater has {users} users rating {books} books and counting!".format(users = len(self.users.keys()), books = len(self.books.keys())) def __eq__(self, other_tr): if self.users == other_tr.users and self.books == other_tr.books: return True else: return False def create_book(self, title, isbn): if isbn in self.isbns: print("A book with that ISBN already exists!") else: self.isbns.append(isbn) return Book(title, isbn) def create_novel(self, title, author, isbn): if isbn in self.isbns: print("A book with that ISBN already exists!") else: self.isbns.append(isbn) return Fiction(title, author, isbn) def create_non_fiction(self, title, subject, level, isbn): if isbn in self.isbns: print("A book with that ISBN already exists!") else: self.isbns.append(isbn) return Non_Fiction(title, subject, level, isbn) def add_book_to_user(self, book, email, rating = None): if email in self.users.keys(): self.users[email].read_book(book, rating) book.add_rating(rating) if book in self.books.keys(): self.books[book] += 1 else: self.books[book] = 1 else: print("No user with email {email}".format(email = self.email)) def add_user(self, name, email, user_books = None): if "@" in email and (".com" or ".edu" or ".org" in email): if email in self.users.keys(): print("A user with that email already exists!") else: self.users[email] = User(name, email) if user_books != None: for book in user_books: self.add_book_to_user(book, email) else: print("Not a valid email address!") def print_catalog(self): for key in self.books.keys(): print(key) def print_users(self): for value in self.users.values(): print(value) def get_most_read_book(self): highest = -1 highest_book = None for key, value in self.books.items(): if value > highest: highest = value highest_book = key return highest_book def highest_rated_book(self): highest = -1 highest_book = None for book in self.books.keys(): if book.get_average_rating() > highest: highest = book.get_average_rating() highest_book = book return highest_book def most_positive_user(self): highest = -1 highest_user = None for user in self.users.values(): if user.get_average_rating() > highest: highest = user.get_average_rating() highest_user = user return highest_user
02b50ab3efd5c50ceeab8c1263f53ec86d130b13
RishabhKatiyar/CorePython
/LeetCode/Problem34.py
1,355
3.609375
4
from typing import List class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: index = self.binarySearch(nums, target, 0, len(nums) - 1) #print(f'Index = {index}') if index == -1: return [-1, -1] right_index = index left_index = index result = index while result != -1: result = self.binarySearch(nums, target, right_index + 1, len(nums) - 1) if result != -1: right_index = result #print(result) #print(right_index) result = index while result != -1: result = self.binarySearch(nums, target, 0, left_index - 1) if result != -1: left_index = result #print(result) #print(left_index) return [left_index, right_index] def binarySearch(self, nums: List[int], target: int, low, high) -> int: index = -1 while low <= high: mid = int((low + high)/2) if nums[mid] == target: index = mid break elif nums[mid] < target: low = mid + 1 else: high = mid - 1 return index ob = Solution() nums = [5,7,7,8,10] target = 8 print(ob.searchRange(nums, target))
84f34f672867723f46d7230483b5e0826741c8a6
DukhDmytro/py_levenstein
/levenstein.py
672
3.71875
4
"""module for creating matrix""" import numpy def dist(strf: str, strs: str) -> int: """calculate Levenstein distance""" rows = len(strf) + 1 cols = len(strs) + 1 matrix = numpy.zeros((cols, rows)) matrix[0, :] = numpy.arange(rows) matrix[:, 0] = numpy.arange(cols) for i in range(1, cols): for j in range(1, rows): if strs[i-1] == strf[j-1]: matrix[i][j] = min(matrix[i-1][j] + 1, matrix[i][j-1] + 1, matrix[i-1][j-1]) else: matrix[i][j] = min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + 1) return matrix[-1][-1]
36affac2c3a215808c46d0e99c6da5188f4d0dc9
Journey99/boj-studyfolio
/class1/1157.py
478
3.84375
4
word = input() word = word.upper() # 문자열을 대문자로 변경 # 알파벳 개수 세기 dic = {} for i in word: if i in dic: dic[i] += 1 else: dic[i] = 1 # 가장 많이 사용된 알파벳 찾기 max_key = max(dic, key=dic.get) # key를 기준으로 최대값을 찾는다. max_value = dic[max_key] dic.pop(max_key) # max_key위치에 있는 요소를 pop if max_value in dic.values(): print("?") else: print(max_key)
3ee8b10f97971de017fcadafaa67d4f0a91225a6
mengyangbai/leetcode
/practise/replacewords.py
1,432
3.9375
4
class Node(object): def __init__(self): self.children = dict() self.isWord = False class Trie(object): def __init__(self): """ Initialize your data structure here. """ self.root = Node() def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ node = self.root for letter in word: child = node.children.get(letter) if child is None: child = Node() node.children[letter] = child node = child node.isWord = True def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ res = '' node = self.root for letter in word: node = node.children.get(letter) if node is None: break res += letter if node.isWord: return res return word class Solution(object): def replaceWords(self, dict, sentence): """ :type dict: List[str] :type sentence: str :rtype: str """ trie = Trie() for prefix in dict: trie.insert(prefix) res = [] for word in sentence.split(): res.append(trie.search(word)) return ' '.join(res)
b49f3cf68908bf5aeb60aab7f3f0e2c44bbdb10d
simrangrover5/Advance_Pythonbatch
/dbms/sqlite1.py
528
3.953125
4
import sqlite3 as sql db = sql.connect("bank.db") c = db.cursor() #cmd = "create table customer(id integer,name varchar(50),address varchar(100))" #c.execute(cmd) while True: id1 = int(input("Enter your id : ")) name = input("Enter your name : ") address = input("Enter address : ") cmd = "insert into customer values({},'{}','{}')".format(id1,name,address) c.execute(cmd) db.commit() ch = input("Do you want to continue(y/n): ") if ch == "n": print("Thanks for coming") break
9670c74f92863aa5a7e9c5474d9c8a8cb6b8a404
adelaideramey/Formation-Data-Science
/Exo 2 - Formation Datascience.py
4,170
4.15625
4
# coding: utf-8 # In[7]: # A. donuts # Given an int count of a number of donuts, # return a string of the form 'Number of donuts: ', # where is the number passed in. However, if the count is 10 or more, then use the word 'many' instead of the actual count. # So donuts(5) returns 'Number of donuts: 5' and donuts(23) returns 'Number of donuts: many' count = input("Saisissez un nombre de donuts : ") count = int(count) def donuts(): if count<10: return 'Number of donuts: ' +str(count) else: return 'Number of donuts: many' donuts() # In[8]: # B. both_ends # Given a string s, # return a string made of the first 2 and the last 2 chars of the original string, # so 'spring' yields 'spng'. However, if the string length is less than 2, return instead the empty string. def both_ends(words): if len(words)>2: return words[:2]+words[-2:] else: return '' test=('spring') both_ends(test) # In[10]: # C. fix_start # Given a string s, # return a string where all occurences of its first char have been changed to '*', # except do not change the first char itself. # e.g. 'babble' yields 'ba**le' # Assume that the string is length 1 or more. # Hint: s.replace(stra, strb) returns a version of string s where all instances of stra have been replaced by strb. def fix_start(s): return s[0] + s[1:].replace(s[0],'*') test=fix_start('springs') print test # In[11]: # D. MixUp # Given strings a and b, # return a single string with a and b separated by a space '<a> <b>', # except swap the first 2 chars of each string. # e.g.'mix', pod' -> 'pox mid' 'dog', 'dinner' -> 'dig donner' # Assume a and b are length 2 or more. def mix_up(a, b): return b[:2]+a[2:]+' '+a[:2]+b[2:] test=mix_up('mix','pod') print test # In[13]: def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected)) #Provided main() calls the above functions with interesting inputs, using test() to check if each result is correct or not. def main(): print 'donuts' # Each line calls donuts, compares its result to the expected for that call. test(donuts(4), 'Number of donuts: 4') test(donuts(9), 'Number of donuts: 9') test(donuts(10), 'Number of donuts: many') test(donuts(99), 'Number of donuts: many') print print 'both_ends' test(both_ends('spring'), 'spng') test(both_ends('Hello'), 'Helo') test(both_ends('a'), '') test(both_ends('xyz'), 'xyyz') print print 'fix_start' test(fix_start('babble'), 'ba**le') test(fix_start('aardvark'), 'a*rdv*rk') test(fix_start('google'), 'goo*le') test(fix_start('donut'), 'donut') print print 'mix_up' test(mix_up('mix', 'pod'), 'pox mid') test(mix_up('dog', 'dinner'), 'dig donner') test(mix_up('gnash', 'sport'), 'spash gnort') test(mix_up('pezzy', 'firm'), 'fizzy perm') #We call the main function. main() #Donuts paramétrés en dynamique # In[18]: # E. not_bad # Given a string, find the first appearance of the substring 'not' and 'bad'. # If the 'bad' follows the 'not', replace the whole 'not'...'bad' substring with 'good'. # Return the resulting string. # So 'This dinner is not that bad!' yields: This dinner is good! def not_bad(s): i = s.find('not') j = s.find('bad') if (j > i): return s[:i] + 'good' + s[(j+3):] return s s=('This dinner is not that bad!') not_bad(s) # In[20]: # F. front_back # Consider dividing a string into two halves. # If the length is even, the front and back halves are the same length. # If the length is odd, we'll say that the extra char goes in the front half. # e.g. 'abcde', the front half is 'abc', the back half 'de'. # Given 2 strings, a and b, return a string of the form a-front + b-front + a-back + b-back def front_back(a, b): i = int(len(a)/2+(len(a)%2)) j = int(len(b)/2+(len(b)%2)) return a[:i]+b[:j]+a[i:]+b[j:] a=('mix') b=('pod') front_back(a,b) # In[25]:
cdf5093e8b9cc5047cbe4aa0576baff3d7e9f0d6
narenchandra859/DAALab
/Final Python Solutions/3a.py
208
3.53125
4
g = { 0: [1,2,3], 1: [0,2,4], 2: [0,1,4], 3: [0,4], 4: [1,2,3] } visited = [0 for i in range(5)] def dfs(s): visited[s]=1 print(s," --->") for i in g[s]: if visited[i]==0: dfs(i) print(dfs(0))
8c9c3fa4d04635480dc8c3653403f448eea4b7aa
amanjn38/pythondemo
/Practice Problems/pp.py
656
4.1875
4
print("Enter the numbers of the list one by onw\n") size = int(input("Enter size of list\n")) mylist = [] for i in range(size): mylist.append(int(input("Enter list Element"))) print(f"Your list is {mylist}") reverse1 = mylist[:] reverse1.reverse() print(f"My first reversed list is {reverse1}") reverse2 = mylist[:] print(f"My second reversed list is {reverse2[::-1]}") reverse3 = mylist[:] for i in range(len(mylist)//2): reverse3[i],reverse3[len(mylist)-i-1] = reverse3[len(mylist)-i-1],reverse3[i] print(f"My third reverse list is {reverse3} ") if reverse3 == reverse1 == reverse2: print("All the three methods return the same result")
b3d95c3e64c2015c027eca5e91153c283ebc9d13
hsrwrobotics/Robotics_club_lectures
/Week 2/Functions/simple_echo.py
681
4.21875
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 21 16:15:36 2019 HSRW Robotics @author: mtc-20 """ # Use a variable to store the input string string = input("Shout out something: ") # This is like a confirmation check stating what is going to be # echoed to cross check th input print("Echoing ", string) # Use .upper() to print the input in all uppercase. print (string.upper()) print(string) print(string.lower()) # Expicitly specify how much of the input to be printed. print(string[:-1]) print(string[0:-2]) # Now if we want this to be repeated again, we would have to type/copy # the same 7 lines again and again, which is just redundant and tiring
8a7672fe3736e23df9646f92e6f3f5afbbdae370
ParisRohan/Python_Projects
/MultipleInputs.py
225
3.828125
4
#Given 3 integers A, B, C. Do the following steps- #Swap A and B. #Multiply A by C. #Add C to B. #Output new values of A and B. a,b,c=map(int,input().split()) #code to take multiple inputs a,b=b,a a=a*c b=b+c print(a,b)
971a45935891dfdc1d2f5ef3cf233e2ff201abec
takayuu1999/Pythin-study
/11ユーザ定義クラス/11_11.py
6,511
3.765625
4
import math import copy # テスト結果の順位の順番に並べて表示する class School: """ 国語の点数リスト """ __jap_score_list = [] """ 数学の点数リスト """ __math_score_list = [] """ 英語の点数リスト """ __eng_score_list = [] """ 学生リスト """ student_list = [] def get_student_list(self): return self.student_list """ 学生情報の追加 """ def add_student(self, student) -> None: """ 常に平均点が高い順にソートして格納 """ temp_list = [] rank = 1 is_add = False for stu in self.student_list: if is_add == False: if stu.get_score_average() < student.get_score_average(): # 追加 student.set_rank(rank) rank += 1 temp_list.append(student) self.add_score(student) is_add = True stu.set_rank(rank) rank += 1 temp_list.append(stu) self.add_score(stu) if is_add == False: student.set_rank(rank) temp_list.append(student) self.add_score(student) self.student_list = copy.deepcopy(temp_list) def add_score(self, student) -> None: """ 指定された学生の点数を追加する """ self.__jap_score_list.append(student.get_jap_score()) self.__math_score_list.append(student.get_math_score()) self.__eng_score_list.append(student.get_eng_score()) def get_jap_score_max(self) -> int: """ 国語の最高得点を取得 """ return max(self.__jap_score_list) def get_math_score_max(self) -> int: """ 数学の最高得点を取得 """ return max(self.__math_score_list) def get_eng_score_max(self) -> int: """ 英語の最高得点を取得 """ return max(self.__eng_score_list) def get_jap_score_min(self) -> int: """ 国語の最低点を取得 """ return min(self.__jap_score_list) def get_math_score_min(self) -> int: """ 数学の最低点を取得 """ return min(self.__math_score_list) def get_eng_score_min(self) -> int: """ 英語の最低点を取得 """ return min(self.__eng_score_list) def get_jap_score_ave(self) -> int: """ 国語の平均点を取得 """ ave = sum(self.__jap_score_list) / len(self.__jap_score_list) return math.floor(ave * 10 ** 2) / (10 ** 2) def get_math_score_ave(self) -> int: """ 数学の平均点を取得 """ ave = sum(self.__math_score_list) / len(self.__math_score_list) return math.floor(ave * 10 ** 2) / (10 ** 2) def get_eng_score_ave(self) -> int: """ 英語の平均点を取得 """ ave = sum(self.__eng_score_list) / len(self.__eng_score_list) return math.floor(ave * 10 ** 2) / (10 ** 2) class Student: """ クラス内順位 """ __rank = 0 def __init__(self, name: str, no: str) -> None: """ コンストラクタ """ self.name = name self.no = no self.ave_score = 0 self.rank = 0 self.test_result = TestResult("", 0, 0, 0) def set_test_result(self, result) -> None: self.test_result = result self.ave_score = self.test_result.get_score_average() def get_score_average(self) -> float: return self.ave_score def set_rank(self, rank) -> None: self.rank = rank def get_rank(self) -> int: return self.rank def get_jap_score(self) -> int: return self.test_result.jap_score def get_math_score(self) -> int: return self.test_result.math_score def get_eng_score(self) -> int: return self.test_result.eng_score def get_display_str(self): return "{} {: <6}{:>4} {:>4} {:>4} {:<6}".format(self.no, self.name, self.get_jap_score(), self.get_math_score(), self.get_eng_score(), self.ave_score) class TestResult: """ テスト結果 """ def __init__(self, no: str, jap_score: int, math_score: int, eng_score: int) -> None: """ コンストラクタ """ self.no = no self.jap_score = jap_score self.math_score = math_score self.eng_score = eng_score """ 平均点取得 """ def get_score_average(self) -> float: # 平均点を算出 ave = (self.jap_score + self.math_score + self.eng_score) / 3 # 小数点第3位を四捨五入して返却 return round(ave, 2) # 学校クラス作成 school = School() # 学生オブジェクトの作成 sakuragi = Student("桜木花道", "001") rukawa = Student("流川楓", "002") mitsui = Student("三井寿", "003") akagi = Student("赤木剛憲", "004") miyagi = Student("宮城リョータ", "005") # テスト結果オブジェクト作成 sakuragi_score = TestResult("001", 65, 45, 55) rukawa_score = TestResult("002", 80, 88, 78) mitsui_score = TestResult("003", 76, 73, 87) akagi_score = TestResult("004", 96, 88, 99) miyagi_score = TestResult("005", 70, 56, 75) # 学生オブジェクトにテスト結果オブジェクトを設定して学校オブジェクトに追加 sakuragi.set_test_result(sakuragi_score) school.add_student(sakuragi) rukawa.set_test_result(rukawa_score) school.add_student(rukawa) mitsui.set_test_result(mitsui_score) school.add_student(mitsui) akagi.set_test_result(akagi_score) school.add_student(akagi) miyagi.set_test_result(miyagi_score) school.add_student(miyagi) # 学生毎のテスト結果の表示 print("No 名前     国語 数学 英語 平均点") for student in school.get_student_list(): print(student.get_display_str()) print() # 科目毎の結果表示 print("国語の最高点:{}".format(school.get_jap_score_max())) print("国語の最低点:{}".format(school.get_jap_score_min())) print("国語の平均点:{}".format(school.get_jap_score_ave())) print("数学の最高点:{}".format(school.get_math_score_max())) print("数学の最低点:{}".format(school.get_math_score_min())) print("数学の平均点:{}".format(school.get_math_score_ave())) print("英語の最高点:{}".format(school.get_eng_score_max())) print("英語の最低点:{}".format(school.get_eng_score_min())) print("英語の平均点:{}".format(school.get_eng_score_ave()))
cbec1051e0bc11ec33814afb151868f7ba2bb340
nikhilsharan/python-learning
/day4-ex-abc.py
156
3.75
4
def abc(a,b,c): if a+b == c: return True else: return False a = int(input()) b = int(input()) c = int(input()) print(abc(a,b,c))
86c13ed87e38dae4b5eee5a6f08ea3a0fc2a2747
Neil-C1119/Practicepython.org-exercises
/practicePython5.py
953
4.125
4
# I'm going to make this more complicated than the exercise calls for # Import the random module import random # Create two empty lists to compare list1 = [] list2 = [] # Create an empty list to push any similar numbers into listSame = [] # For loops to fill the two lists with random numbers to compare for x in range(1, 9): list1.append(random.randrange(100)) for x in range(1, 13): list2.append(random.randrange(100)) # For loop to check through every number in list1 for x in list1: # If the number in list1 is also in list2 if x in list2: # Push that number into the list that holds similar numbers listSame.append(x) # If the same number list has at least one element if len(listSame) > 0: # Print the list print(listSame) # If the list doesn't have at least one element else: # Print this message print("There are no similar numbers in either of the lists.")
563c087a7a8cf2472812b00a9025872cb2836040
boisdecerf/jeudupendu
/jeudupendu.py
2,526
3.84375
4
import random title = "Jeu du pendu" print("---{:^14}---".format(title)) playing = True while playing : # Counting the numbers of lines in the file def len_file(file) : with open(file) as f : for index, line in enumerate(f) : pass return index + 1 lenFile= len_file("./listedemots") # Searching for a random word in the file randomNumber = random.randint(1, lenFile) with open("./listedemots", "r") as file : for i in range(randomNumber) : wordToGuess = file.readline() # Preparing the game wordToGuess = wordToGuess.rstrip().upper() copyWordToGuess = wordToGuess wordInConstruction = "#" * len(wordToGuess) lettersList = [] for i in range(1,6+1) : # Word guessing print("\nMot à deviner : ", wordInConstruction) print("Il reste", 6+1-i, "tour(s)") letter = input("Entrez une lettre : ") letter= letter.upper() while not letter.isalpha() or letter in lettersList or len(letter) > 1 : # Check only one character has been choosen if len(letter) > 1 : letter = input("Entrez une seule lettre : ") # Check if the input is not in alphabet if not letter.isalpha() : letter = input("Ceci n'est pas une lettre.\nEntrez une lettre : ") # Check if the letter has already been proposed if letter in lettersList : letter = input("Letter déjà proposée.\nEntrez une lettre : ") letter = letter.upper() lettersList.append(letter) # Word construction while letter in copyWordToGuess : indexLetter = copyWordToGuess.index(letter) wordInConstruction= wordInConstruction[:indexLetter] + letter + wordInConstruction [indexLetter+1:] copyWordToGuess = copyWordToGuess[:indexLetter] + "#" + copyWordToGuess[indexLetter+1:] # Propose a word print("\nMot à deviner : ", wordInConstruction) guessedWord = input("Devinez le mot : ") if guessedWord.upper() == wordToGuess : print("\n\tGagné !") else : print("\n\tPerdu...") # Ask to keep playing or not answerPlaying = input("\nSouhaitez-vous rejouer ? (oui/non) : ") while answerPlaying != "oui" and answerPlaying != "non" : answerPlaying = input("\nRépondez par \"oui\" ou par \"non\". Souhaitez-vous rejouer ? (oui/non) : ") if answerPlaying == "non" : playing = False
81a509d34b1289560e111cfaf2103fe29f327009
AlymbaevaBegimai/TEST
/2.py
401
4
4
class Phone: username = "Kate" __how_many_times_turned_on = 0 def call(self): print( "Ring-ring!" ) def __turn_on(self): self.__how_many_times_turned_on += 1 print( "Times was turned on: ", self.__how_many_times_turned_on ) my_phone = Phone() my_phone.call() print( "The username is ", my_phone.username )
92d154c9f27fd1b215694f960353d856d08ac952
kmenon89/python-practice
/cond_challenge_ip_ad.py
990
4.21875
4
#program to get ip address as input , count number of segments in it and length of each segments #get ip adress from user ip_address=input("please enter the ip address:") len_ip=len(ip_address) segment=0 segment_length="" #count the number of segments if ip_address: for i in range(0,len_ip): if (ip_address[i] == ".") : segment +=1 segment_length=len(segment_length) print("segment {0} length is {1}".format(segment,segment_length)) segment_length="" else : segment_length =segment_length+ip_address[i] #print(ip_address[i],i,len_ip-1,segment_length) if (i==(len_ip-1)): segment +=1 segment_length=len(segment_length) print("segment {0} length is {1}".format(segment,segment_length)) #print(segment_length) else: print("please enter an ip address!")
696342915b27268c8f5669456659cf6cdebd489d
Dheeraj-1999/interview-questions-competitve-programming
/Comp pro qus and sol/gfg/general/prime/1 prime bruteForce.py
297
3.828125
4
import math def prime(n): for i in range(2, int(math.sqrt(n))+1): if(n%i == 0): return False return True def nPrimes(n): primes = [] for i in range(n+1): if(prime(i)): primes.append(i) return(primes) n = int(input()) print(nPrimes(n))
8184f753c482209b51abd0b1e909cdd4a974587c
vidojeg/python
/cube.py
277
3.796875
4
from random import * mini = 1 maxi = 6 def randomly(): x = randint(mini, maxi) print x while (1): print ("Would you like run again:") text = raw_input("") if text == "": randomly() elif text == "no": print "Good bye" break
225bae46a8892d2b3c434a27d85dc23efb2c0fac
otisscott/1114-Stuff
/Lab 5/romanbullshit.py
576
3.640625
4
# Otis Scott # CS - UY 1114 # 4 Oct 2018 # Homework 4 num = int(input("Enter a decimal number: ")) orig = num roman = "" while num > 0: if num > 1000: roman += "M" num -= 1000 elif num > 500: roman += "D" num -= 500 elif num > 100: roman += "C" num -= 100 elif num > 50: roman += "L" num -= 50 elif num > 10: roman += "X" num -= 10 elif num > 5: roman += "V" num -= 5 elif num > 0: roman += "I" num -= 1 print(str(orig) + " is " + roman)
84233c76b2937cf7f7ec0b7c1315c5be14702670
fuzhanrahmanian/python_euler
/fibonacci.py
233
3.875
4
def fibonacci(x, y, n): even_num = list() while n < 4000000: if n % 2 == 0: even_num.append(n) y = x x = n n = x + y return sum(even_num) fibonacci(1, 0, 1) print("Hello")
3db4cebeecf7adb1e2b531f8a867c86ed293a93f
hsmith851/Python-Projects
/Adding Numbers Input:Output.py
315
4.0625
4
from numpy import double #program to add two numbers #Store input numbers from numpy import double num1 = input('Enter the first number: ') num2 = input('Enter the second number: ') # Adding two nos sum = double(num1) + double(num2) # printing values print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))