text
stringlengths
37
1.41M
import asyncio import time import threading # @asyncio.coroutine # 会把一个生成器标记为coroutine类型 # def hello(): # print("Hello world! (%s)" % threading.currentThread()) # # 异步调用asyncio.sleep(2): # yield from asyncio.sleep(2) # print("Hello again! (%s)" % threading.currentThread()) # 请注意,async和await是针对coroutine的新语法,要使用新的语法,只需要做两步简单的替换: # 1.把@asyncio.coroutine替换为async; # 2.把yield from替换为await。 async def hello(): print("Hello world!") r = await asyncio.sleep(2) print("Hello again!") if __name__ == '__main__': start = time.time() # 获取EventLoop: loop = asyncio.get_event_loop() # 执行coroutine loop.run_until_complete(hello()) loop.close() print('times: %0.4f seconds' % (time.time() - start))
from tkinter import * import sys root = Tk() label_1 = Label(root, text="Values:") input = Entry(root) addition = Button(root, text=" Add ") subtract = Button(root, text="Subtract") multiply = Button(root, text="Multiply") division = Button(root, text="Divide") equal = Button(root, text=" = ") output = Label(root, text="") label_1.grid(row=0, column=0,sticky=W) input.grid(row=0, column=1, columnspan=4,sticky=W+E+N+S) addition.grid(row=1, column=0) subtract.grid(row=1, column=1) multiply.grid(row=1, column=2) division.grid(row=1, column=3) equal.grid(row=1, column=4) output.grid(row=2) input_str = '' def add(event): global input_str global input input_str += input.get() + '+' output.config(text=input_str) input = Entry(root, text="") input.grid(row=0, column=1, columnspan=3, sticky=W + E + N + S) def sub(event): global input_str global input input_str += input.get() + '-' output.config(text=input_str) input = Entry(root, text="") input.grid(row=0, column=1, columnspan=3, sticky=W + E + N + S) def mul(event): global input_str global input input_str += input.get() + 'x' output.config(text=input_str) input = Entry(root, text="") input.grid(row=0, column=1, columnspan=3, sticky=W + E + N + S) def div(event): global input_str global input input_str += input.get() + '÷' output.config(text=input_str) input = Entry(root, text="") input.grid(row=0, column=1, columnspan=3, sticky=W + E + N + S) def eq(event): global input_str input_str = input_str.replace('x', '*') input_str = input_str.replace('÷', '/') string = input_str[0:len(input_str)-1] calculation = str(eval(string)) calc = calculation input_str = '' output.config(text=calc) addition.bind("<Button-1>", add) subtract.bind("<Button-1>", sub) multiply.bind("<Button-1>", mul) division.bind("<Button-1>", div) equal.bind("<Button-1>", eq) root.mainloop()
#!python def linear_search(array, item): """return the first index of item in array or None if item is not found""" # implement linear_search_iterative and linear_search_recursive below, then # change this to call your implementation to verify it passes all tests # return linear_search_iterative(array, item) return linear_search_recursive(array, item) def linear_search_iterative(array, item): # loop over all array values until item is found for index, value in enumerate(array): if item == value: return index # found return None # not found def linear_search_recursive(array, item, index=0): # once implemented, change linear_search to call linear_search_recursive # to verify that your recursive implementation passes all tests if index > len(array) -1: return None # not found # base case - when we have found item if array[index] == item: return index else: # recurse to the next index return linear_search_recursive(array, item, index+1) def binary_search(array, item): """return the index of item in sorted array or None if item is not found""" # implement binary_search_iterative and binary_search_recursive below, then # change this to call your implementation to verify it passes all tests # return binary_search_iterative(array, item) return binary_search_recursive(array, item) def binary_search_iterative(array, item): ''' O(log n) time - because we're cutting half at every iteration O(1) space - we're not making any memory ''' left = 0 right = len(array)-1 while left <= right: middle = (left + right) // 2 if array[middle] == item: return middle elif array[middle] < item: left = middle + 1 else: right = middle - 1 return None # not found # edge case is a tricky input def binary_search_recursive(array, item, left=None, right=None): # O(log n) space + time - because we're using the stack as space and cutting half at every iteration if item in array: # set left and right starter values if left == None and right == None: return binary_search_recursive(array, item, left=0, right=((len(array) -1) // 2)) # base case if (array[right] == item): return right # => found # recursive cases if left <= right: if (array[right] < item): return binary_search_recursive(array, item, left = (left + right) // 2, right= right + 1) elif (array[right] > item): return binary_search_recursive(array, item, left = (left + right) // 2, right= right -1) return None # not found
from Tkinter import * window = Tk() ps2_canvas = Canvas(window, width=500, height=500) ps2_canvas.grid(row=0, column=0) # These next four statements are the ones you should play with for your # program. LEAVE EVERYTHING ELSE (apart from the comments) ALONE # draw the face ps2_canvas.create_oval(100, 100, 400, 400, fill='yellow') # Draw the mouth ps2_canvas.create_arc(175, 175, 325, 325, start=225, extent=90, style=ARC) # Draw the left eye ps2_canvas.create_oval(200, 205, 202, 207, fill='black') # Draw the right eye ps2_canvas.create_oval(298, 205, 300, 207, fill='black') # Keep this line at the end of your program window.mainloop()
#Problem Set 5, Part II #Kim, Matthew # you might want to use one of the functions you defined in the previous part # of this pset. This is why we're importing that file here. If you want to use # the list_sort function in the other file, you should use the dot notation, # i.e., listops.list_sort(....) Make sure this file, the listops file, and the # part2helper.py are all in the same folder. import listops import part2helper # importing this file to get the nested list defined there. def list_min(a): temp = a[0] for i in a: if i < temp: temp = i return temp def list_sort(b): x = [] y = [] z = list(b) q = [] for i in range(0,len(b)): num = list_min(z) y.append(b.index(num)) x.append(num) z.remove(num) q.append(x) q.append(y) return q # All your function definitions should be before this line and after the # import lines. # __main__ # Please do **not** remove the following line. The variable tasks is the # nested list storing the tasks. tasks = part2helper.tasks # Have the rest of your main program here. def print_task(tasks,b): months = ['','Jan', 'Feb','Mar','Apr','May','June','Jul','Aug','Sept','Oct','Nov','Dec'] q = [] lastlist = [] for n in range(0,len(tasks)): if b[0] == tasks[n][1] and b[1] == tasks[n][2]: q.append(tasks[n]) result_printtask = q return result_printtask def order(a): x = [] a = print_task(tasks,a) for i in a: x.append(i[3]) result_order = list_sort(x) return result_order def starttime(a): x = [] b = order(a) result_printtask = print_task(tasks,a) for i in b[1]: x.append(result_printtask[i][3]) return x def minutes(a): x = [] b = order(a) result_printtask = print_task(tasks,a) for i in b[1]: x.append(result_printtask[i][4]) return x def task(a): x = [] b = order(a) result_printtask = print_task(tasks,a) for i in b[1]: x.append(result_printtask[i][0]) return x def description(a): x = [] b = order(a) result_printtask = print_task(tasks,a) for i in b[1]: x.append(result_printtask[i][6]) return x def duration(a): x = [] b = order(a) result_printtask = print_task(tasks,a) for i in b[1]: x.append(result_printtask[i][5]) return x def convert_to_minutes(a): hour = starttime(a) minute = minutes(a) x = [hour, minute] time = [] for i in range(0,len(x[1])): time.append(x[0][i]*60 + x[1][i]) return time def newtime(a): start_time = convert_to_minutes(a) newtime = [] for i in range(0,len(start_time)): newtime.append(start_time[i] + duration(a)[i]) return newtime def newtime2(a): newtime2 = [] newtimet = newtime(a) for n in range(0,len(newtimet)): newtime2.append(int(newtimet[n]/60)) return newtime2 def newminutes(a): newminutes = [] newtimed = newtime(a) newtimeo = newtime2(a) for j in range(0,len(newtimed)): newminutes.append((newtimed[j]/60.0 - newtimeo[j])*60) return newminutes def print_tasks(tasks,a): months = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov','Dec'] b = newtime(a) for i in range(0, len(b)): print 'These are your tasks for ' + str(months[a[0]]) + str(a[1]) print '' print 'Task Name: ' + task(a)[i] print '' print ' Start time: ', starttime(a)[i], ':', int(minutes(a)[i]) print ' End time: ', newtime2(a)[i], ':', int(newminutes(a)[i]) print ' Description: ' + description(a)[i] print '' print print_tasks(tasks, [10,1])
#Problem Set 1 #Kim, Matthew #Collaborators:Jeremy Lim #Part I import math def golden_ratio(): g_ratio = (1 + math.sqrt(5))/2 return g_ratio print golden_ratio () #Part II def is_even (input_int): lol = int(input_int) % 2 return lol == 0 print is_even(20) print is_even(3) #Part III import math def quad_form(a,b,c): disc = float(b**2 - (4*a*c)) sdisc = math.sqrt((disc)) denominator = float(2*a) numerator1 = float((-b + sdisc)) numerator2 = float((-b - sdisc)) return numerator1/denominator, numerator2/denominator def explanation(): print 'Quadratic Equation values' a = float(raw_input('Value of a: ')) b = float(raw_input('Value of b: ')) c = float(raw_input('Vale of c: ')) return quad_form(a,b,c) print explanation() #Hello Professor, I really didn't understand how specific you wanted us to be #when you said "You should always have a prompt for input, explaining what is #desired". My friend Jeremy interpreted it as putting the Value of the variables #rather than simply "a=" or "b=" but I thought you meant more explanation. #I did what I did also because I wanted to try calling a function within a function #FYI, I originally had the raw inputs not in a function and printed quad_form(a,b,c) #Have a great weekend!
class Line(object): def __init__(self,p1, p2): p1 = Point(p1) p2 = Point(p2) def getp1(self): return self.p1 def getp2(self): return self.p2 def setp1(self,p1): self.p1 = p1 def setp2(self,p2): self.p2 = p2 def __str__(self): return length(p1,p2) #2 class Song(object): def __init__(self): if isinstance(self.lyric, list): self.lyric = list1 else: happybdaylist = list1 def __str__(self): for lyric in list1: print lyric
meal_cost = float(input()) tip_percent = int(input()) tax_percent = int(input()) tip = meal_cost * (tip_percent / 100) tax = meal_cost * (tax_percent / 100) total_cost = int(round(meal_cost + tip + tax)) print(total_cost)
import onetimepad from tkinter import * root = Tk() root.title("Chryptography App") def encryptMessage(): a = var.get() ct = onetimepad.encrypt(a,"saikumar") print("Working",ct) e2.delete(0,END) e2.insert(END,ct) def dycrptMessage(): a = var2.get() ct = onetimepad.decrypt(a,"saikumar") print("Working",ct) e4.delete(0,END) e4.insert(END,ct) l1 = Label(root,text="Plain Text") l1.grid(row=0,column=0) l3 = Label(root,text="Encypted Text") l3.grid(row=0,column=2) var= StringVar() e1 = Entry(root,textvariable=var) e1.grid(row=0,column=1) var2= StringVar() e3 = Entry(root,textvariable=var2) e3.grid(row=0,column=3) l2 = Label(root,text="Encypted Text") l2.grid(row=1,column=0) l4 = Label(root,text="Plain Text") l4.grid(row=1,column=2) e2 = Entry(root) e2.grid(row=1,column=1) e4 = Entry(root) e4.grid(row=1,column=3) b1 = Button(root,text="Encyption",bg="blue",fg="Red",command=encryptMessage) b1.grid(row=2,column=1) b2 = Button(root,text="Dycrption",bg="blue",fg="Red",command=dycrptMessage) b2.grid(row=2,column=3) root.mainloop()
# Contains basic utility functions. class Utility: def __init__(self): pass @staticmethod def str_to_list_converter(str_val=''): # Converting string to list # Input : 'a,b,c' or '[a,b,c]' or '1,2,3' or '[1,2,3]' # Output : ['a','b','c'] or [1,2,3] if str_val[0] is '[' and str_val[-1] is ']': edited_list = str_val[1:-1].split(',') else: edited_list = str_val.split(',') try: final_list = map(int, edited_list) return final_list except ValueError: final_list = edited_list return final_list
from arrays import * arr1 = array("i",[1,2,5,4,3]) def searchelement(array,value): for i in array: if i == value: return array.index(value) return "The element does not exist" searchelement(arr1,5)
from arrays import * arr1 = array("i",[1,2,3,4,5,6,7,8]) print(arr1) def tranversearray(array): for i in array: print(i) traversearray(arr1) def accessElement(array,index): if index >= len(array): print("There is not any element in this index") else: print(array[index]) accessElement(arr1,4) def searchelement(array,value): for i in array: if i == value: return array.index(value) return "The element does not exist in this array" print(searchelement(arr1,5)) arr1.remove(2) print(arr1)
# student1 = "Tarkek" # student2 = "Chris" # student3 = "Michael" # def Students(): # print(f"{student1} {student2} {student3}") # Students() # student1 = "Glen" # Students() # class Students: # def PrintStudents(): # print("Tarek Chris Michael") #Students.PrintStudents() # class Students: # def students(self): # print("Tarek Chris Michael") # Michael = Students() # Michael.students() # Chris = Students() # Chris.students() # class MyClass(object): # def __init__(self, first_name, last_name): # print("hello world") # self.first_name = first_name # self.last_name = last_name # def printName(self): # # name = "Celeste" # print(f"{self.first_name} {self.last_name} ") # dc = MyClass("Chris", "Humphrey") # dc.printName() # dc_houston = MyClass("Mohammad", "Azam") # dc_houston.printName() # def Person(name, count): # print(f"my name is {name} {count}") # count = count + 1 # return count # count = Person("Lisa", 0) # print(count) # count = 67 # count = Person("Veronica", count) # print(count) # countPeter = Person("Peter", 5) # print(countPeter) # countPeter = Person("Bob", countPeter) # print(countPeter) # Cindy = Person("Cindy") # class Person(object): # def __init__(self, name): # self.name = name # self.count = 0 # print(f"my name is {self.name}") # def change_name(new_name): # self.count = self.count + 1 # self.name = new_name # print(f"name is {self.name} I've changed my name {self.count} times") # class Person(object): # def __init__(self, name, whoAmI): # self.name = name # self.count = 0 # self.whoAmI = whoAmI # # print(f"hello {self.name}") # def change_name(self, new_name): # self.name = new_name # self.count = self.count + 1 # print(f"who: {self.whoAmI} name:{self.name} count: {self.count}") # student = Person("veronica", "student") # atlanta_student = Person("Michael", "atlanta_student") # student.change_name("Matt") # student.change_name("Katy") # student.change_name("Chris") # atlanta_student.change_name("Jake") # student.change_name("Andrew") # student.change_name("Sabrina") # student.change_name("Garrett") # atlanta_student.change_name("Jason") # class Phone(object): # def __init__(self, phone_type): # self.phone_type = phone_type # self.status = "off" # print(f"my phone is a {self.phone_type}") # def print_phone(self): # print(self.phone_type) # def on(self): # print('on') # self.status = "on" # def off(self): # print('off') # self.status = "off" # def get_status(self): # print(f'your {self.phone_type} phone is currently: {self.status}') # android = Phone("android") # iPhone = Phone("iPhone") # blackberry = Phone("blackberry") # android.get_status() # android.on() # android.get_status() # iPhone.get_status() # blackberry.get_status() # import datetime # we will use this for date objects # class Person: # def __init__(self, name, surname, birthdate, address, telephone, email): # self.name = name # self.surname = surname # self.birthdate = birthdate # self.address = address # self.telephone = telephone # self.email = email # def age(self): # today = datetime.date.today() # age = today.year - self.birthdate.year # if today < datetime.date(today.year, self.birthdate.month, # self.birthdate.day): # age -= 1 # return age # person = Person( # "Jane", # "Doe", # datetime.date(1992, 3, 12), # year, month, day # "No. 12 Short Street, Greenville", # "555 456 0987", # "[email protected]" # ) # print(person.name) # print(person.email) # print(person.age()) class Car: pi = 0 def __init__(self, make, model, color): self.make = make self.model = model self.color = color self.doorStatus = "closed" print(f"make: {self.make} model:{self.model} color:{self.color}") self.myList = [] Car.pi = 5 def ChangeColor(self, newColor): self.color = newColor return (self.color) def openDoor(self): self.doorStatus = "open" def displayColor(self): print(f"The color of your {self.make} is {self.color}") def displayInfo(self): print(f"make: {self.make} model:{self.model} color:{self.color}") def cir(self, length): return 2 * Car.pi * length def override(self): print("override of car class") def altered(self): print("altered of car class") class ElectricCar(Car): def __init__(self, electricMotor, make, model, color): self.electricMotor = electricMotor super(ElectricCar, self).__init__(make, model, color) def printCarType(self): print("I'm an electric car") def override(self): print("override of electric car class") def altered(self): print("BEFPRE altered of electric car class") super(ElectricCar, self).altered() print("After altered of electric car class") def motorType(self): print(self.electricMotor) ec = ElectricCar("ac motor", "tesla", "s", "red") ec.printCarType() ec.ChangeColor("green") ec.displayInfo() ec.override() ec.altered() ec.motorType() ec2 = ElectricCar("dc motor", "nissan", "leaf", "yellow") ec2.printCarType() ec2.ChangeColor("blue") ec2.displayInfo() ec2.override() ec2.altered() ec2.motorType() # class HybridCar(Car): # def printCarType(self): # print("I'm a hybrid car") # print(Car.pi) # Car.greeting # toyota = Car("toyota", "prius", "green") # toyota.greeting # honda = Car("honda", "civic", "purple") # Car.pi =4 # print(honda.cir(2)) # print(toyota.pi) # print(honda.pi) # jeep = Car("jeep", "wrangler", "white") # print(jeep.pi) # f150 = Car("Ford", "f150", "marble") # print(f150.cir(3)) # f150.ChangeColor("Midnight Red") # f150.displayColor() # toyota.displayInfo() # honda.displayInfo() # jeep.displayInfo() # f150.displayInfo() # fleet = [toyota, honda, jeep, f150] # for carObject in fleet: # # print(carObject.displayInfo()) # class Person: # def __init__ (self, name): # self.name = name # self.count = 0 # self._a = 1 # self.__b = 5 # def greet (self): # self._greet() # def _greet (self): # self.count += 1 # if self.count > 1: # print("Stop being so nice") # self.__reset_count() # else: # print("Hello", self.name) # def __reset_count(self): # self.count = 0 # person = Person("Sabrina") # person.greet() # person.greet() # person.greet() # print(person._a) # print(person._Person__b) # class Animal: # def __init__ (self, name): # self.name = name # def fourleggs(self): # print("i have 4 legs") # class Dog(Animal): # def woof(self): # print("Woof") # puppy = Dog("pickle") # print(puppy.name) # puppy.woof() # puppy.fourleggs() # puppy2 = Dog("john luke") # print(puppy2.name) # puppy2.woof() # puppy2.fourleggs() # class Cat (Animal): # def meow (self): # print("Meow") # cat1 = Cat("misty") # cat2 = Cat("bubbles") # print(cat1.name) # cat1.meow() # cat1.fourleggs() # print(cat2.name) # cat2.meow() # cat2.fourleggs()
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys if len(sys.argv) < 1: exit() #def line_split_by_label_vecgtor(line): def line_split(line): sents_split = line.strip().split(" ") #['ラベル', 'a:x', 'b:y', ...] label = sents_split[0] #ラベル #print(label) sentence = sents_split[1:] #ラベル以外の部分 return(label, sentence) def sentence_to_idx_freq(sentence): dic = [] for idx_and_freq in sentence: #x:y split_idx_freq = idx_and_freq.split(":") #['x', 'y'] idx = split_idx_freq[0] freq = split_idx_freq[1] for i in range(int(freq)):#idxの繰り返し数分だけリストにidxを追加 #print(idx) dic.append(idx) return dic #dic.appeend(split_idx_freq[0]) #split_idx_freq[1]) #return split_idx_freq #print(split_idx_time) #return split_idx_time #def read_instance(label, sentence): #def lab_sents_to_read_instance(lab_sents): # for sents in lab_sents: #sents:文のラベル+素性ベクトル1つ分(x:y) # dic = [] # sents_split = sents.strip().split(" ") # label = sents_split[0] #ラベル # #print(label) # sents_delete_label = sents_split[1:] #ラベル削除 # for idx_and_time in sents_delete_label: #x:yを一つずつ取り出し # #print(idx_and_time) # split_idx_time = idx_and_time.split(":") #:で区切ってリスト表示 # #print(split_idx_time) # # idx = split_idx_time[0] # time = split_idx_time[1] #頻度回数の取り出し # #print(idx) # # for i in range(int(time)):#idxの繰り返し数分だけリストにidxを追加 # #print(idx) # dic.append(idx) # tuple = (label,dic) # # return tuple txt = sys.argv[1] f = open(txt, "r") lab_sents = f.read().strip().split("\n") label_list=[] idx_freq_list=[] for line in lab_sents: #1行分のラベルと素性 label, sentence = line_split(line) #ラベルと文に分ける #print(label,sentence) label_list.append(label) idx_freq_list.append(sentence_to_idx_freq(sentence)) """ for idx_freq in sentence_to_idx_freq(sentence): #print(idx_freq) idx_freq_list.append(idx_freq) #print(label_list,idx_freq_list) """ x = [label_list,idx_freq_list] #print(x) #idx_list = sentence_to_idx_times(sentence) #print(lab_sents) #a = lab_sents_to_read_instance(lab_sents) #print(a)
# to check if the selected path valid path (not 0 (wall), and the path hasn't been travelled yet) def isValidPath(maze, row, col, solutions): if (maze[row][col] != 0) and \ ((row >= 0 and row < len(maze)) and (col >= 0 and col < len(maze[0])) ) and \ solutions[row][col] == 0: return True else: return False # move the row and column given the direction def move(row, col, dir): newrow = row newcol = col if dir == "up": newrow -= 1 elif dir == "down": newrow += 1 elif dir == "left": newcol -= 1 elif dir == "right": newcol += 1 return newrow, newcol # solve the maze def solveMaze(maze, row, col, solutions): # directions arah = ["up","down","left","right"] # check if our position is at the goal if maze[row][col] == 2: solutions[row][col] = 2 return True # if we havent reached the goal yet else: # if we havent reached the goal yet solutions[row][col] = 1 for dir in arah: # we move to another cell newrow, newcol = move(row, col, dir) # check if path taken is valid if isValidPath(maze, newrow, newcol, solutions): oldrow, oldcol = row, col row, col = newrow, newcol if solveMaze(maze, row, col, solutions): return True else: solutions[row][col] = 0 row, col = oldrow, oldcol return False def print_maze(maze): for i in range(len(maze)): for j in maze[i]: print(j, end=" ") print() # main function to test the maze solver if __name__ == '__main__': maze = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,1,1,1,1,1,0,1,1,1,1,1,1,1,2], [0,1,0,0,0,1,0,1,0,0,0,0,0,0,0], [0,1,0,1,0,1,0,1,1,1,1,1,1,1,0], [0,1,0,1,0,1,0,0,0,1,0,1,0,0,0], [0,1,0,1,1,1,1,1,0,1,0,1,0,1,0], [0,1,0,1,0,0,0,1,0,0,0,1,0,1,0], [0,1,0,1,0,1,1,1,0,1,1,1,0,1,0], [0,1,0,1,0,1,0,0,0,1,0,0,0,1,0], [0,1,0,1,0,1,0,1,1,1,0,1,1,1,0], [0,1,0,1,0,1,0,1,0,0,0,1,0,1,0], [0,1,0,1,0,1,1,1,1,1,1,1,0,1,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]] start_row = 1 start_col = 0 solutions = [[0 for a in range(len(maze[0]))] for b in range(len(maze))] print("\nis this maze solvable? = ", solveMaze(maze, start_row, start_col, solutions)) print_maze(solutions)
''' Created on Oct 2, 2017 @author: [email protected] Pledge: I pledge my honor that I have abided by the Stevens Honor System ''' def helper(l): if l == [] or l[1:] == []: return [] return [l[0]+l[1]] + helper(l[1:]) def pascal_row(n): '''The pascal row function takes a single integer, which represents a row number and it returns that row. ''' if n == 0: return [1] return [1] + helper(pascal_row(n-1)) + [1] def pascal_triangle(n): '''The pascal triangle function takes in a single integer and returns a list containing the values of all the rows up to and including row n''' if n == 0: return [[1]] return pascal_triangle(n-1) + [pascal_row(n)]
# Two Sum from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: sort_nums = sorted(nums) l = 0 r = len(sort_nums)-1 while r > l: summ = sort_nums[l] + sort_nums[r] if summ > target: r -= 1 elif summ < target: l += 1 else: break # sort_nums[l],sort_nums[r] res = [] for i in range(len(nums)): if nums[i] == sort_nums[l] or nums[i] == sort_nums[r]: res.append(i) if len(res) == 2: break else: continue return(res) number = [2,7,11,5] target = 9 a = Solution() print(a.twoSum(number,target)) #=========================================================================================================== # 15. 3Sum def threeSum(self, nums): nums.sort() ans = [] if len(nums) < 3: return ans for i in range(len(nums)): if i >= 1 and nums[i-1] == nums[i]: continue left = i + 1 right = len(nums) -1 while left < right: sum3 = nums[i] + nums[left] + nums[right] if sum3 < 0: left += 1 elif sum3 > 0: right -= 1 else: ans.append([nums[i], nums[left], nums[right]]) left += 1 while nums[left] == nums[left - 1] and left < right: left += 1 return ans # 18. 4Sum
from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: sort_nums = sorted(nums) l = 0 r = len(sort_nums)-1 while r > l: summ = sort_nums[l] + sort_nums[r] if summ > target: r -= 1 elif summ < target: l += 1 else: break # sort_nums[l],sort_nums[r] res = [] for i in range(len(nums)): if nums[i] == sort_nums[l] or nums[i] == sort_nums[r]: res.append(i) if len(res) == 2: break else: continue return(res) number = [2,7,11,5] target = 9 a = Solution() print(a.twoSum(number,target))
''' REINFORCE Monte Carlo Policy Gradient AI Player Author: Lei Mao Date: 5/2/2017 Introduction: The REINFORCE_AI used REINFORCE, one of the Monte Carlo Policy Gradient methods, to optimize the AI actions in certain environment. It is extremely complicated to implement the loss function of REINFORCE in Keras. Tensorflow, though it takes time to construct the neural network, makes it easier to customize different loss functions. ''' import os import numpy as np import tensorflow as tf GAMMA = .99# decay rate of past observations LEARNING_RATE = 0.00005 # learning rate in deep learning RAND_SEED = 0 # random seed SAVE_PERIOD = 100 # period of time steps to save the model LOG_PERIOD = 100 # period of time steps to save the log of training MODEL_DIR = 'model/' # path for saving the model LOG_DIR = 'log/' # path for saving the training log np.random.seed(RAND_SEED) tf.set_random_seed(RAND_SEED) class REINFORCE(): def __init__(self, num_actions, num_features): # Initialize the number of player actions available in the game self.num_actions = num_actions # Initialize the number of features in the observation self.num_features = num_features # Initialize the model self.model = self.REINFORCE_FC_Setup() # Initialize tensorflow session self.saver = tf.train.Saver() self.sess = tf.Session() self.sess.run(tf.global_variables_initializer()) # Initialize the episode number self.episode = 0 # Initialize episode replays used for caching game transitions in one single episode self.episode_observations = list() # observation feature list self.episode_actions = list() # one-hot encoded action self.episode_rewards = list() # immediate reward def Softmax_Cross_Entropy(softmax_label, softmax_pred): # Calculate cross entropy for softmaxed label and prediction matrices # This function is not used in Tensorflow version of the code return (-1.) * np.dot(softmax_label, np.log(softmax_pred.T)) def One_Hot_Encoding(labels, num_class): # Transform labels to one-hot encoded array # This function is not used in Tensorflow version of the code matrix_encoded = np.zeros(len(labels), num_class, dtype = np.bool) matrix_encoded[np.arrange(len(labels)), labels] = 1 return matrix_encoded def REINFORCE_FC_Setup(self): # Set up REINFORCE Tensorflow environment with tf.name_scope('inputs'): self.tf_observations = tf.placeholder(tf.float32, [None, self.num_features], name = 'observations') self.tf_actions = tf.placeholder(tf.int32, [None,], name = 'num_actions') self.tf_values = tf.placeholder(tf.float32, [None,], name = 'state_values') # FC1 fc1 = tf.layers.dense( inputs = self.tf_observations, units = 16, activation = tf.nn.tanh, # tanh activation kernel_initializer = tf.random_normal_initializer(mean=0, stddev=0.5), bias_initializer = tf.constant_initializer(0.1), name='FC1' ) # FC2 fc2 = tf.layers.dense( inputs = fc1, units = 32, activation = tf.nn.tanh, # tanh activation kernel_initializer = tf.random_normal_initializer(mean=0, stddev=0.4), bias_initializer = tf.constant_initializer(0.1), name='FC2' ) # FC3 # fc3 = tf.layers.dense( # inputs = fc2, # units = 8, # activation = tf.nn.sigmoid, # tanh activation # kernel_initializer = tf.random_normal_initializer(mean=0, stddev=0.3), # bias_initializer = tf.constant_initializer(0.1), # name='FC3' # ) # fc4 = tf.layers.dense( # inputs = fc3, # units = 8, # activation = tf.nn.leaky_relu, # tanh activation # kernel_initializer = tf.random_normal_initializer(mean=0, stddev=0.3), # bias_initializer = tf.constant_initializer(0.1), # name='FC4' # ) # FC3 logits = tf.layers.dense( inputs = fc2, units = self.num_actions, activation = None, kernel_initializer = tf.random_normal_initializer(mean=0, stddev=0.3), bias_initializer = tf.constant_initializer(0.1), name='FC5' ) # Softmax self.action_probs = tf.nn.softmax(logits, name='action_probs') with tf.name_scope('loss'): # To maximize (log_p * V) is equal to minimize -(log_p * V) # Construct loss function mean(-(log_p * V)) to be minimized by tensorflow neg_log_prob = tf.nn.sparse_softmax_cross_entropy_with_logits(logits = logits, labels = self.tf_actions) # this equals to -log_p self.loss = tf.reduce_mean(neg_log_prob * self.tf_values) with tf.name_scope('train'): self.optimizer = tf.train.AdamOptimizer(LEARNING_RATE).minimize(self.loss) def REINFORCE_FC_Restore(self): # Restore the trained model self.saver.restore(self.sess, MODEL_DIR + 'AI_model') def Store_Transition(self, observation, action, reward): # Store game transitions used for updating the weights in the Policy Neural Network self.episode_observations.append(observation) self.episode_actions.append(action) self.episode_rewards.append(reward) def Clear_Episode_Replays(self): # Clear game transitions self.episode_observations = list() self.episode_actions = list() self.episode_rewards = list() def Calculate_Value(self): # The estimate of v(St) is updated in the direction of the complete return: # Gt = Rt+1 + gamma * Rt+2 + gamma^2 * Rt+3 + ... + gamma^(T-t+1)RT; # where T is the last time step of the episode. state_values = np.zeros_like(self.episode_rewards, dtype=np.float64) state_values[-1] = self.episode_rewards[-1] for t in reversed(range(0, len(self.episode_rewards)-1)): state_values[t] = GAMMA * state_values[t+1] + self.episode_rewards[t] # Normalization to help the control of the gradient estimator variance state_values -= np.mean(state_values) state_values /= np.std(state_values) return state_values def REINFORCE_FC_Train(self): # Train model using data from one episode inputs = np.array(self.episode_observations) state_values = self.Calculate_Value() # Start gradient descent _, train_loss = self.sess.run([self.optimizer, self.loss], feed_dict = { self.tf_observations: np.vstack(self.episode_observations), self.tf_actions: np.array(self.episode_actions), self.tf_values: state_values}) # Print train_loss print('Episode train loss: %f' %train_loss) # Clear episode replays after training for one episode self.Clear_Episode_Replays() return train_loss def AI_Action(self, observation): # Calculate action probabilities when given observation prob_weights = self.sess.run(self.action_probs, feed_dict = {self.tf_observations: observation[np.newaxis, :]}) # Randomly choose action according to the probabilities action = np.random.choice(range(prob_weights.shape[1]), p=prob_weights.ravel()) return action
def is_triangle(func): """Tests, if given 3 sides, they make up a triangle. For a shape to be a triangle at all, all sides have to be of length > 0, and the sum of the lengths of any two sides must be greater than or equal to the length of the third side. Input: list with 3 integers Returns: True or False """ def wrapper(arg): if all(v == 0 for v in arg) or sorted(arg)[0] + sorted(arg)[1] < sorted(arg)[2]: return False else: return func(arg) return wrapper @is_triangle def is_equilateral(sides): """Tests if all three sides of a triangle have the same length. Input: list with 3 integers Returns: True or False """ return sides[0] == sides[1] == sides[2] @is_triangle def is_isosceles(sides): """Tests if at least two sides of a triangle have the same length. Input: list with 3 integers Returns: True or False """ return sides[0] == sides[1] or sides[0] == sides[2] or sides[1] == sides[2] @is_triangle def is_scalene(sides): """Tests if all sides of a triangle have different lengths. Input: list with 3 integers Returns: True or False """ return sides[0] != sides[1] and sides[0] != sides[2] and sides[1] != sides[2]
def prime_factors(natural_number): """Prime factorisation of an integer """ prime_factors = [] i = 2 while natural_number > 1: if natural_number % i == 0: # check if i is a factor if is_prime_number(i): # if i is a factor, check if i is a prime prime_factors.append(i) natural_number = natural_number / i else: i += 1 return prime_factors def is_prime_number(x): if x >= 2: for y in range(2,x): if not ( x % y ): return False else: return False return True
#!/usr/bin/env python """ Ask for a string and print the lenght of that string. """ #import __author__ = "Stijn Janssen" __email__ = "[email protected]" __status__ = "Development" def main(): #Ask for a word word = input("Give me a word.\n") #Give the lenght of the word print(len(word)) if __name__ == '__main__': # code to execute if called from command-line main()
#!/usr/bin/env python3 """ each layer should be given the name layer """ import tensorflow as tf def create_layer(prev, n, activation): """ prev: is the tensor output of the previous layer n: is the number of nodes in the layer to create activation: is the activation function that the layer should use tf.contrib.layers.variance_scaling_initializer(mode="FAN_AVG") to implement He et. al initialization for the layer weights each layer have the name 'layer' Returns: the tensor output of the layer """ i = tf.contrib.layers.variance_scaling_initializer(mode="FAN_AVG") la = tf.layers.Dense( units=n, activation=activation, kernel_initializer=i, name='layer' ) return la(prev)
def cal_room(people): room6=0 room4=0 room2=0 total_price=10000 for room6_num in range(0,6): for room4_num in range(0,8): for room2_num in range(0,14): if((room6_num*6+room4_num*4+room2_num*2)>=people): num=room6_num*120+room4_num*100+room2_num*80 if num <= total_price: total_price=num room6=room6_num room4=room4_num room2=room2_num print (room6, room4, room2, total_price) print (room6, room4, room2) cal_room(16) cal_room(26)
class Student(object): def __init__(self, name, age): self.name = name self.age = age def introduce(self): print("I am", self.name, " And"," I am", self.age ) class Student_Sport(Student): def sport(self): print(self.name," likes Swimming !!!") maidou = Student("Maidou", 11) Luke = Student("Luke", 9) maidou.introduce() Luke.introduce() Luke1 = Student_Sport("Luke", 9) Luke1.introduce() Luke1.sport() maidou.sport()
def isprime(y): isprime=True #print(y) if y == 0: return False if y == 1: return True for a in range(2,y): if y%a==0: isprime=False break return isprime #x=int(input("input a number")) y=int(input("input a number")) for a in range(y): if(isprime(a)): print (a,end=" ")
#!/usr/bin/env python # -*- coding: UTF-8 -*- def remainder() : evenList = [x for x in range(1, 21) if x % 2 == 0 ] return evenList def oddNumber() : oddList = [ x for x in range(1, 21) if x % 2 != 0] return oddList def divisible(num1 , num2) : if isNumber(num1) and isNumber(num2): return num1 % num2 == 0 def isNumber(obj) : return isinstance(obj, (int, long)) if __name__ == '__main__': print remainder() print oddNumber() num1 = int(raw_input("Enter num1 > ")) num2 = int(raw_input("Enter num2 > ")) print divisible(num1, num2)
# Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. # Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. # Требуется определить номер дня, на который результат спортсмена составит не менее b километров. # Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня. # Например: a = 2, b = 3. # Результат: # 1-й день: 2 # 2-й день: 2,2 # 3-й день: 2,42 # 4-й день: 2,66 # 5-й день: 2,93 # 6-й день: 3,22 # Ответ: на 6-й день спортсмен достиг результата — не менее 3 км. point_a = int(input('Введите начальное значение дистанции: ')) point_b = int(input('Введите конечное значение дистанции: ')) day = 1 while point_a < point_b: point_a = point_a + point_a * 0.1 day += 1 print(f'Ответ: на {day}-й день спортсмен достиг результата - не менее {point_b} км')
# Реализовать программу работы с органическими клетками, состоящими из ячеек. # Необходимо создать класс Клетка. В его конструкторе инициализировать параметр, # соответствующий количеству ячеек клетки (целое число). В классе должны быть реализованы методы перегрузки арифметических операторов: # сложение (__add__()), вычитание (__sub__()), умножение (__mul__()), деление (__truediv__()). # Данные методы должны применяться только к клеткам и выполнять увеличение, уменьшение, умножение и целочисленное (с округлением до целого) деление клеток, соответственно. # Сложение. Объединение двух клеток. При этом число ячеек общей клетки должно равняться сумме ячеек исходных двух клеток. # Вычитание. Участвуют две клетки. Операцию необходимо выполнять только если разность количества ячеек двух клеток больше нуля, иначе выводить соответствующее сообщение. # Умножение. Создается общая клетка из двух. Число ячеек общей клетки определяется как произведение количества ячеек этих двух клеток. # Деление. Создается общая клетка из двух. Число ячеек общей клетки определяется как целочисленное деление количества ячеек этих двух клеток. # В классе необходимо реализовать метод make_order(), принимающий экземпляр класса и количество ячеек в ряду. Данный метод позволяет организовать ячейки по рядам. # Метод должен возвращать строку вида *****\n*****\n*****..., где количество ячеек между \n равно переданному аргументу. Если ячеек на формирование ряда не хватает, то в последний ряд записываются все оставшиеся. # Например, количество ячеек клетки равняется 12, количество ячеек в ряду — 5. Тогда метод make_order() вернет строку: *****\n*****\n**. # Или, количество ячеек клетки равняется 15, количество ячеек в ряду — 5. Тогда метод make_order() вернет строку: *****\n*****\n*****. class Cell: def __init__(self, amount_cell): self.amount_cell = amount_cell @staticmethod def make_order(count_row, cell): while True: print('*' * count_row) cell -= count_row if cell < count_row: print('*' * cell) break def __add__(self, other): return self.amount_cell + other.amount_cell def __sub__(self, other): if self.amount_cell - other.amount_cell > 0: return self.amount_cell - other.amount_cell else: print('Результат вычетания мееньше 0') def __mul__(self, other): return self.amount_cell * other.amount_cell def __truediv__(self, other): return self.amount_cell // other.amount_cell c1 = Cell(17) c2 = Cell(3) print(c1 + c2) print(c1 - c2) print(c1 * c2) print(c1 / c2) Cell.make_order(5, c1.amount_cell)
# 2. Пользователь вводит время в секундах. # Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. # Используйте форматирование строк. person_time = int(input('Введите время в секундах: ')) hours = person_time // 3600 minutes = person_time // 60 - hours * 60 seconds = person_time - 3600 * hours - 60 * minutes if hours > 9: zero_hours = '' else: zero_hours = 0 if minutes > 9: zero_minutes = '' else: zero_minutes = 0 if seconds > 9: zero_seconds = '' else: zero_seconds = 0 print(f'{zero_hours}{hours}:{zero_minutes}{minutes}:{zero_seconds}{seconds}')
# Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение. # При вызове функции должен создаваться объект-генератор. # Функция должна вызываться следующим образом: for el in fact(n). # Функция отвечает за получение факториала числа, а в цикле необходимо выводить только первые n чисел, начиная с 1! и до n!. # Подсказка: факториал числа n — произведение чисел от 1 до n. Например, факториал четырёх 4! = 1 * 2 * 3 * 4 = 24. def fact(num1): i = 0 result = [] fac = 1 while i < num1: i += 1 fac = fac * i result.append(fac) for el in result: yield el g = fact(5) print(g) for el in fact(5): print(el)
def isBalanced(mystring): result = mystring.count("(") == mystring.count(")") print(result) return(result) isBalanced("a(bcd)d") isBalanced("(kjds(hfkj)sdhf") isBalanced("(sfdsf)(fsfsf") isBalanced("{[]}()") isBalanced("{[}]") with open("input.txt", 'r') as f: inputArray = [] for line in f: print(line) inputArray.append(line.split(",")) inputArray = sorted(inputArray, key=lambda x: x[1]) print(inputArray) def fib(n): a, b = 0, 1 for i in range(n-1): a, b = b, a+b print(a) return a print(fib(5)) def int2str(numb): return str(numb) print(int2str(1234))
import unittest from .game import Game class TestGameResults(unittest.TestCase): def testResults(self): data = [[2, 13, 8, '​RYGPBRYGBRPOP', 'R,B,GG,Y,P,B,P,RR', 'Player 1 won after 7 cards.'], [2, 6, 5, 'RYGRYB', 'R,YY,G,G,B', 'Player 2 won after 4 cards.'], [3, 9, 6, 'QQQQQQQQQ', 'Q,QQ,Q,Q,QQ,Q', 'No player won after 6 cards.']] for case in data: game = Game(case[0], case[1], case[2], case[3], case[4]) result = game.run_game() self.assertEquals(result, case[5])
class Language: en="english" ua="українська" ru="русский" de="deutsche" class Human: def __init__(self, name, age, language): self.name = name self.age = age self.language = language def __str__(self): return "Name: {:>10}, age:{:3}, language:{}".format(self.name, self.age, self.language) def speak(self): if self.language == Language.en: print("Hello, {}!".format(self.name)) elif self.language == Language.ua: print("Привіт, {}!".format(self.name)) elif self.language == Language.ru: print("Привет, {}!".format(self.name)) elif self.language == Language.de: print("Guten Tag, {}!".format(self.name)) if __name__=="__main__": humans=[] humans.append(Human("Broderick", 45, Language.en)) humans.append(Human("Кирил", 15, Language.ru)) humans.append(Human("Софія", 18, Language.ua)) humans.append(Human("Otto", 32, Language.de)) for thishuman in humans: print(thishuman) thishuman.speak() print()
def text_year(old): # для чисел, которые заканчиваются на 11,12,13,14 - пишется "лет" year = old%10 dyear = old%100//10 if year in [2,3,4] and dyear != 1: return "года" elif year == 1 and dyear !=1: return "год" else: return "лет" def human(name, sex): def how_old(): old = int(input("\n{}, cколько Вам полных лет: ".format(name.title()))) print("Добрый день, {0} {1}. Вам {2} {3}.".format(_sexWrite[sex], name.title(), old, text_year(old))) return how_old def input_sex(): man = ["m","м","man"] sex = input("Ваш пол ({}/{}): ".format(*_sex)) if sex.lower() in man: return _sex[0] else: return _sex[1] def main(): fhello = [] for num in range(1,4): name = input("Как зовут {}-го пользователя: ".format(num)) sex = input_sex() fhello.append(human(name, sex)) for fn in fhello: fn() _sex = ("м","ж") _sexWrite = {"м":"г-н","ж":"г-жа"} main()
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print list(l) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print max(l) # 9 print min(l) # 0 # index(l) # NameError: name 'index' is not defined # count(l) # NameError: name 'count' is not defined print len(l) # 10 print sorted(l) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # remove(l) # NameError: name 'remove' is not defined # append(l) # NameError: name 'append' is not defined print l.index(5) # 5 print l.count(6) # 1 print l.remove(5) # None print l.append(5) # None
#https://leetcode.com/problems/find-numbers-with-even-number-of-digits/ class Solution(object): def findNumbers(self, nums): even = 0 for i, num in enumerate(nums): if len(str(nums[i]))%2 == 0: even += 1 else: even += 0 return even
'efficiently compute median of a set of numbers given one by one' from __future__ import division from heapq import heappush, heappop import unittest class RunningMedian: def __init__(self): self.left_max_heap = [] self.right_min_heap = [] def insert(self, item): left_len = len(self.left_max_heap) right_len = len(self.right_min_heap) if left_len == right_len == 0: heappush(self.left_max_heap, -item) return if item < -self.left_max_heap[0]: heappush(self.left_max_heap, -item) else: heappush(self.right_min_heap, item) left_len = len(self.left_max_heap) right_len = len(self.right_min_heap) if right_len < left_len: l_pop = -heappop(self.left_max_heap) heappush(self.right_min_heap, l_pop) elif right_len > left_len: r_pop = heappop(self.right_min_heap) heappush(self.left_max_heap, -r_pop) def getMedian(self): left_len = len(self.left_max_heap) right_len = len(self.right_min_heap) if left_len > right_len: return -self.left_max_heap[0] elif left_len < right_len: return self.right_min_heap[0] else: return (-self.left_max_heap[0] + self.right_min_heap[0]) / 2 class Test_RunningMedian(unittest.TestCase): def setUp(self): self.rm = RunningMedian() def test_insert1(self): elems_to_inset = [ (4, 4), (0, 2), (3, 3), (5, 3.5), (1, 3), (2, 2.5), (6, 3)] for elem, exp_median in elems_to_inset: self.rm.insert(elem) self.assertEquals(exp_median, self.rm.getMedian(), "expected median = {exp_median}; got = {calc_median} " "after inserting element = {elem}".format( exp_median = exp_median, calc_median= self.rm.getMedian(), elem = elem)) def test_insert2(self): elems_to_inset = [ (1, 1), (3, 2), (8, 3), (9, 5.5), (6, 6), (4, 5), (5, 5), (7, 5.5), (2, 5), (0, 4.5)] for elem, exp_median in elems_to_inset: self.rm.insert(elem) self.assertEquals(exp_median, self.rm.getMedian(), "expected median = {exp_median}; got = {calc_median} " "after inserting element = {elem}".format( exp_median = exp_median, calc_median= self.rm.getMedian(), elem = elem)) if __name__ == '__main__': unittest.main()
'write a program to print pre-order binary tree traversal non-recursively' from binary_tree import BinaryTree, get_toy_binary_tree2 import unittest def pre_order_non_recur(n): if n == None: return [] result = [] util_stack = [n] while len(util_stack) != 0: top = util_stack.pop() result.append(top['data']) if top['right']: util_stack.append(top['right']) if top['left']: util_stack.append(top['left']) return result class Test_pre_order_non_recur(unittest.TestCase): def test_basic_functionality(self): in_ordr = [1, 3, 16, 29, 14, 86, 4, 18, 69, 63, 141] pre_ordr = [4, 3, 1, 29, 16, 86, 14, 69, 18, 141, 63] post_order = [1, 16, 14, 86, 29, 3, 18, 63, 141, 69, 4] tr = BinaryTree.from_in_and_pre_order_traversal(in_ordr, pre_ordr) curr_pre_order = pre_order_non_recur(tr.root) self.assertEqual(curr_pre_order, pre_ordr) def test_basic_functionality1(self): tr = get_toy_binary_tree2() expecte_pre_order = [5, 3, 9, 6, 8, 8, 42, 7, 98, 23, 28, 0, 86] self.assertEqual(expecte_pre_order, pre_order_non_recur(tr.root)) if __name__ == '__main__': unittest.main()
'compute the k closest stars to earth. Assume earth is a (0, 0, 0)' import unittest from heapq import heappush, heappushpop, heappop def get_k_closest(lst, k = 3): h = [] for p in lst: dist = p[0] ** 2 + p[1] ** 2 + p[2] ** 2 if len(h) < k: heappush(h, (-dist, p)) else: heappushpop(h, (-dist, p)) result = [] while len(h) != 0: result.append(heappop(h)[1]) return result class TestKClosest(unittest.TestCase): def test_basic_functionality(self): stars = [ (1, 0, 9), (-1, 1, 3), (3, 4, 0), (3, 1, 2), (3, 1, 1)] k = 3 expected_out = [(3, 1, 2), (-1, 1, 3), (3, 1, 1)] self.assertEqual(expected_out, get_k_closest(stars, k)) def test_test_all_dist_equal(self): stars = [(3, 4, 0), (4, 3, 0), (4, 0, 3), (0, 3, 4), (3, 0, 4)] expected_out = [(3, 4, 0), (4, 0, 3), (4, 3, 0)] k = 3 self.assertEqual(expected_out, get_k_closest(stars, k)) def test_k_greater_than_len(self): stars = [(3, 4, 0), (4, 3, 0)] expected_out = [(3, 4, 0), (4, 3, 0)] k = 3 self.assertEqual(expected_out, get_k_closest(stars, k)) if __name__ == '__main__': unittest.main()
'''Write a program which takes as input an integer and a binary tree with integer weights, and checks if there exists a leaf whose path weight equals the given integer. path-weight: pw of a node is the sum of the integers on the unique path from the root to that node '''
"find the i'th order statistic in an array A" from random import randint def randomized_partition(A, start_ind, end_ind): 'partition array A randomly by choosing a random pivot' piv_ind = randint(start_ind, end_ind) A[start_ind], A[piv_ind] = A[piv_ind], A[start_ind] i = start_ind + 1 pivot = A[start_ind] for j in range(start_ind + 1, end_ind + 1): if A[j] < pivot: A[i], A[j] = A[j], A[i] i += 1 A[start_ind], A[i - 1] = A[i - 1], A[start_ind] return i - 1 def random_select(A, start_ind, end_ind, i_order_to_find): 'find the ith order statistic from array A' if start_ind == end_ind: return A[start_ind] j = randomized_partition(A, start_ind, end_ind) k = j - start_ind if k + 1 == i_order_to_find: return A[j] elif k + 1 > i_order_to_find: return random_select(A, start_ind, j - 1, i_order_to_find) else: return random_select(A, j + 1, end_ind, i_order_to_find -k -1)
'''We are given items 1, 2, 3, 4, 5... with integral weights w1, w2, w3, w4, w5... and values of items v1, v2, v3, v4, v5... W -> maximum weight the knapsack can carry We would like to find what is the maximum value and what items to pack if Case 1) There is only 1 count of each item (art gallery) Case 2) There is unlimited numbers of each item (supermarket) ''' import unittest def get_max_val(d, W): ''' given data d of form d = { 1 : {'weight':4, 'value':5}, . . } and W (maximum knapsack capacity) find the maximum value of goods that can be packed ''' item_weight_value_table = [ [None] * (W + 1) for i in range((len(d) + 1))] for item in range(len(d) + 1): item_weight_value_table[item][0] = 0 for weight in range(W + 1): item_weight_value_table[0][weight] = 0 for item in range(1, len(d) + 1): for wt in range(1, W + 1): if d[item]['weight'] > wt: item_weight_value_table[item][wt] = item_weight_value_table[item - 1][wt] else: item_weight_value_table[item][wt] = max( item_weight_value_table[item - 1][wt], d[item]['value'] + item_weight_value_table[item - 1][wt - d[item]['weight']]) return item_weight_value_table[-1][-1] class Test_knapsack_case1(unittest.TestCase): def setUp(self): self.data1 = { 1 : {'weight': 3, 'value': 5}, 2 : {'weight': 2, 'value': 6}, 3 : {'weight': 5, 'value': 7}, 4 : {'weight': 10, 'value': 15}, 5 : {'weight': 8, 'value': 12}, } def test_1(self): W = 1 self.assertEqual(get_max_val(self.data1, W), 0) W = 2 self.assertEqual(get_max_val(self.data1, W), 6) W = 3 self.assertEqual(get_max_val(self.data1, W), 6) W = 5 self.assertEqual(get_max_val(self.data1, W), 11) W = 8 self.assertEqual(get_max_val(self.data1, W), 13) W = 10 self.assertEqual(get_max_val(self.data1, W), 18) W = 11 self.assertEqual(get_max_val(self.data1, W), 18) W = 12 self.assertEqual(get_max_val(self.data1, W), 21) # items 10 + 2 -> 15 + 6 W = 13 self.assertEqual(get_max_val(self.data1, W), 23) # items 8 + 2 + 3 -> 12 + 6 + 5 if __name__ == '__main__': unittest.main()
#!/usr/bin/env python3 'tests for binary_tree.py' from binary_tree import BinaryTree, BinarySearchTree,\ get_toy_binary_tree, get_empty_tree, get_toy_binary_search_tree, \ BinaryTreeWithPrarent import unittest class TestBinaryTree(unittest.TestCase): def setUp(self): self.tr = get_toy_binary_tree() self.empty_tr = get_empty_tree() self.bst = get_toy_binary_search_tree() def test_basic_functionality(self): self.assertTrue(self.tr) self.assertTrue(self.bst) def test_size(self): self.assertEqual(0, self.empty_tr.size()) self.assertEqual(9, self.tr.size()) self.assertEqual(12, self.bst.size()) def test_maxDepth(self): self.assertEqual(0, self.empty_tr.maxDepth()) self.assertEqual(4, self.tr.maxDepth()) self.assertEqual(5, self.bst.maxDepth()) def test_printInOrder(self): print("printing bst -->") self.bst.printInOrder() print("printing normal tree -->") self.tr.printInOrder() print("printing empty tree") self.empty_tr.printInOrder() def test_build_binary_tree(self): in_ordr = [1, 3, 16, 29, 14, 86, 4, 18, 69, 63, 141] pre_ordr = [4, 3, 1, 29, 16, 86, 14, 69, 18, 141, 63] post_order = [1, 16, 14, 86, 29, 3, 18, 63, 141, 69, 4] tr = BinaryTree.from_in_and_pre_order_traversal(in_ordr, pre_ordr) print("printing post order -->") tr.printPostOrder() print("expected order -->") print("(" + " ".join(map(str, post_order)) + " )") self.assertEqual(5, tr.maxDepth()) def test_binary_tree_in_order_path(self): in_ordr = [1, 3, 16, 29, 14, 86, 4, 18, 69, 63, 141] pre_ordr = [4, 3, 1, 29, 16, 86, 14, 69, 18, 141, 63] tr = BinaryTree.from_in_and_pre_order_traversal(in_ordr, pre_ordr) self.assertEqual(tr.getInOrderPath(), in_ordr) class TestBinarySearchTree(unittest.TestCase): def setUp(self): self.empty_bst = BinarySearchTree() self.single_node_bst = BinarySearchTree() self.single_node_bst.insert(-1) self.small_bst = BinarySearchTree() self.small_bst.insert(43) self.small_bst.insert(43) self.small_bst.insert(-2) self.small_bst.insert(102) self.toy_bst = get_toy_binary_search_tree() def test_maxValue(self): self.assertRaises(TypeError, self.empty_bst.maxValue) self.assertEqual(-1, self.single_node_bst.maxValue()) self.assertEqual(102, self.small_bst.maxValue()) self.assertEqual(102, self.toy_bst.maxValue()) def test_minValue(self): self.assertRaises(TypeError, self.empty_bst.minValue) self.assertEqual(-1, self.single_node_bst.minValue()) self.assertEqual(-2, self.small_bst.minValue()) self.assertEqual(-1, self.toy_bst.minValue()) def test_delete_node(self): values = [7, 3, 23, 1, 5, 9, 52, 2, 4, 36] tr = BinarySearchTree() for v in values: tr.insert(v) tr.populate_parent() expected_in_order_tree_after_7_delete = \ [1, 2, 3, 4, 5, 9, 23, 36, 52] tr.delete_data(7) self.assertEquals(tr.getInOrderPath(), expected_in_order_tree_after_7_delete) self.assertRaises(Exception, tr.delete_data, 6) expected_in_order = \ [1, 3, 4, 5, 9, 23, 36, 52] tr.delete_data(2) self.assertEquals(tr.getInOrderPath(), expected_in_order) expected_in_order = \ [1, 4, 5, 9, 23, 36, 52] tr.delete_data(3) self.assertEquals(tr.getInOrderPath(), expected_in_order) expected_in_order = \ [1, 4, 5, 9, 23, 36] tr.delete_data(52) self.assertEquals(tr.getInOrderPath(), expected_in_order) expected_in_order = \ [1, 5, 9, 23, 36] tr.delete_data(4) self.assertEquals(tr.getInOrderPath(), expected_in_order) class TestBinaryTreeWithParent(unittest.TestCase): def test_populate_parent(self): in_ordr = [1, 3, 16, 29, 14, 86, 4, 18, 69, 63, 141] pre_ordr = [4, 3, 1, 29, 16, 86, 14, 69, 18, 141, 63] tr = BinaryTreeWithPrarent.from_in_and_pre_order_traversal(in_ordr, pre_ordr) tr.populate_parent() self.assertEqual(None, tr.root['parent']) self.assertEqual(tr.root['left'], tr.root['left']['right']['parent']) self.assertEqual(tr.root['left'], tr.root['left']['left']['parent']) self.assertEqual(141, tr.root['right']['right']['left']['parent']['data']) self.assertEqual(tr.root['right'], tr.root['right']['left']['parent']) self.assertEqual(tr.getInOrderPath(), in_ordr) if __name__ == '__main__': unittest.main()
'tests for quicksort implementation' from quicksort_impl import quicksort, partition from random import randint import unittest class Test_Quicksort_impl(unittest.TestCase): def test_partition(self): lst1 = [2, 5, 4, 7, 3, 1, 6] self.assertEqual(5, partition(lst1, 0, len(lst1) - 1)) expected_lst = [2, 5, 4, 3, 1, 6, 7] self.assertEqual(expected_lst, lst1) self.assertEqual(6, partition(lst1, 0, len(lst1) - 1)) self.assertEqual(expected_lst, lst1) self.assertEqual(0, partition(lst1, 0, len(lst1) - 3)) expected_lst = [1, 5, 4, 3, 2, 6, 7] self.assertEqual(expected_lst, lst1) lst2 = [5] * 5 self.assertEqual(4, partition(lst2, 0, len(lst2) - 1)) def test_quicksort(self): lst1 = [2, 5, 4, 7, 3, 1, 6] sorted_list = sorted(lst1) quicksort(lst1, 0, len(lst1) - 1) self.assertEqual(sorted_list, lst1) lst2 = [5] * 10 quicksort(lst2, 0, len(lst2) - 1) self.assertEqual(lst2, [5] * 10) lst3 = [] quicksort(lst3, 0, len(lst3) - 1) self.assertEqual(lst3, []) size = 100000 rand_arr = [randint(0, 200) for i in range(size)] sorted_rand_arr = sorted(rand_arr) quicksort(rand_arr, 0, size - 1) self.assertEqual(sorted_rand_arr, rand_arr) if __name__ == '__main__': unittest.main()
'search a sorted array for the first occurence of k' import unittest def get_first_occur(lst, k): l = 0 u = len(lst) - 1 while l <= u: m = l + (u - l) // 2 if lst[m] == k: if m == 0: return 0 if lst[m - 1] == k: u = m - 1 else: return m elif lst[m] < k: l = m + 1 else: u = m - 1 return -1 class Test_GetFirstOccurence(unittest.TestCase): def test_basic_functionality(self): lst = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] self.assertEqual(3, get_first_occur(lst, 108)) self.assertEqual(6, get_first_occur(lst, 285)) self.assertEqual(0, get_first_occur(lst, -14)) self.assertEqual(9, get_first_occur(lst, 401)) self.assertEqual(-1, get_first_occur(lst, -21)) self.assertEqual(-1, get_first_occur(lst, -11)) self.assertEqual(-1, get_first_occur(lst, 284)) self.assertEqual(-1, get_first_occur(lst, 402)) def test_all_inp_list_same(self): lst = [255] * 10 tgt = 255 self.assertEqual(0, get_first_occur(lst, tgt)) if __name__ == '__main__': unittest.main()
n = int(input()) for i in range(n): A, B = map(int, input().split()) if B == 0: print("divisao impossivel") else: print("{:.1f}".format(A/B))
entradas = input() A, B, C = entradas.split(" ") A = float(A) B = float(B) C = float(C) print("TRIANGULO: {:.3f}".format((A*C)/2)) print("CIRCULO: {:.3f}".format(3.14159*C**2)) print("TRAPEZIO: {:.3f}".format((A+B)*(C/2))) print("QUADRADO: {:.3f}".format(B*B)) print("RETANGULO: {:.3f}".format(A*B))
n = int(input()) for num in range(1, n + 1): print(num, num ** 2, num ** 3) print(num, num ** 2 + 1, num ** 3 + 1)
import random number=random.randint(1,100) guess=0 count=0 while guess!=number and guess!="exit": guess=int(input("whts your guess man?\n")) if guess=="exit": break guess=int(guess) count+=1 if guess<number: print("too low!") elif guess>number: print("too high!") else: print("you got it!") print("and it only took you",count,"tries!")
# The in and not in operators a = "Welcome" if 'come' in a: print('Inside') if 'busy' not in a: print('not in')
class Rectangle: def __init__(self, height = 1, width = 2): self.height = height self.width = width def getArea(self): return self.height* self.width def getPerimeter(self): return self.height * self.width*2 a = Rectangle(int(input('enter the height here: ')), int(input('enter the width here: '))) print("The Area of the rectangle is", a.getArea()) print("The Perimeter of the rectangle is", a.getPerimeter())
#Creating a prime number my_list= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] for num in (my_list): if num>1: for i in range (2, num): if num%i== 0: print(num, ' not a prime') break else: print(num, 'is a prime number')
''' This script allows you to INPUT countries of interest, data of interest, starting date and an integer smoothing parameter in order to plot the time series for the given type of data and country set using matplotlib module and parsing the information provided in the dataset collected by "Our World in Data" organization. Credits for the dataset goes to: Hasell, J., Mathieu, E., Beltekian, D. et al. A cross-country database of COVID-19 testing. Sci Data 7, 345 (2020). https://doi.org/10.1038/s41597-020-00688-8 ''' import csv import requests import datetime import os import pandas as pd import warnings warnings.filterwarnings("ignore", "(?s).*MATPLOTLIBDATA.*", category=UserWarning) import matplotlib.pyplot as plt import PIL.Image as pili import data as dt ################################################## ##### GENERIC FUNCTION rolling: dataset -> dataset ################################################## def rolling_n_deep_avg(alist,n_deep): ''' INPUT: a list, integer n_deep OUTPUT: rolling "n_deep" data average list ("n_deep"-1 elements shorter). Integer rounded result ''' new_list = [] for elem in range(len(alist)-n_deep+1): subsidiary_list = [alist[elem+num] for num in range(n_deep)] new_list.append( sum(subsidiary_list)/n_deep) return new_list ######################### #### PARSE DATA FUNCTIONS ######################### def transdate(string): """ INPUT: string of the form "YYYY-MM-DD" OUTPUT: datetime.date object with the corresponding date """ day = int(string[8:]) month = int(string[5:7]) year = int(string[:4]) #print(day, month, year) return datetime.date(year, month, day) def parse_title(a_string): ''' Take a string such as 'new_deaths_per_million' and return 'New deaths per million' ''' a_list = a_string.split('_') b_string = (' '.join(a_list)).capitalize() return b_string ##################################################### ##################################################### def parser_local(countries): """ INPUT: List of Country Names in English OUTPUT: A dictionary of dictionaries. The key value of the outer dictionary is a tuple (date, 'country'). The inner dictionary has keys from dt.COLUMNS and their respective values. """ num_of_countries = len(countries) tot_entries = ((datetime.date.today()-datetime.date(2019, 12, 31)).days+1)*num_of_countries print('') print('At most a total of',tot_entries,'entries expected.') with open(dt.FILE, 'rt', newline = "", encoding='utf-8-sig') as myfile: csvreader = csv.reader(myfile,skipinitialspace = True, delimiter = ',', quoting = csv.QUOTE_MINIMAL) ntable = [] num = 0 print('') for line in csvreader: if line[2] in countries: ntable.append(line) num += 1 #print(num,'\b', sep=' ', end='', flush=True) #print('') print(num,'entries found for selected countries ... OK') print('') ncolumn = dt.COLUMNS mydic = {} for element in ntable: mydic[(element[2],element[3])] = {ncolumn[index]: element[index] for index in range(len(ncolumn))} return mydic def order_for_plot(mydic, country, init_date, type_graph, deep): ''' INPUT: - Parsed dictionary with all the data corresponding to selected countries. Assumed the form returned by parser_local function - a single country (string) - initial date to consider in format 'YYYY-MM-DD' - type_graph data we are interested in - integer deep level or rolling average RETURNS: List of [date, data] elements with the moving average applied on data for single country ''' data_table = [] date_table = [] for key, val in mydic.items(): if len(val[type_graph]) > 0 and key[0] == country and transdate(val['date']) >= transdate(init_date): data_table.append(float(val[type_graph])) date_table.append(transdate(val['date'])) elif len(val[type_graph]) == 0 and key[0] == country and transdate(val['date']) >= transdate(init_date): data_table.append(0) date_table.append(transdate(val['date'])) if len(data_table) == 0: return [] else: new_data = rolling_n_deep_avg(data_table,deep) new_date = list(date_table) for iter in range(deep-1): new_date.pop(0) return pd.Series(data=new_data, index=new_date) ##################################################### ##################################################### def draw_many_lines(countries, data_type, deep=7, init_date='2019-12-31', outputfile=0): """ INPUT: - List of countries written as strings in English - String with the data type - depth of the moving average. Default being 7 - Initial date to consider in format 'YYYY-MM-DD'. Default being the whole COVID series. - name of output file. If parameter omitted plot is rendered in the browser OUTPUT: Produces a png plot rendered in a temporary file (unless outputfile chosen) for the specified countries and data type with a deep-day rolling mean. RETURN: None """ plt.style.use('seaborn-notebook') if os.path.exists(dt.FILE): statbuf = datetime.datetime.fromtimestamp((os.stat(dt.FILE)).st_mtime) print('') print('=====================================================================') print('') print("LAST DOWNLOAD OF DATA: {}".format(statbuf)) print('') fresh_or_not = input("Want to download fresh data? Press y/n (default is 'n'): ") if fresh_or_not == 'y': print('') print('Downloading fresh data from "Our World in Data" ...', end='') my_web = requests.get(dt.WEB, allow_redirects=True) with open('owid-covid-data.csv', 'wb') as newdatafile: newdatafile.write(my_web.content) elif not os.path.exists(dt.FILE): print('') print('Downloading fresh data from "Our World in Data" ...', end='') my_web = requests.get(dt.WEB, allow_redirects=True) with open('owid-covid-data.csv', 'wb') as newdatafile: newdatafile.write(my_web.content) print('OK') mydic = parser_local(countries) for pais in countries: print('Processing data for',pais,'... ', end='') if data_type in dt.COLUMNS: mytable = order_for_plot(mydic, pais, init_date, data_type, deep) else: print('') print('') print('WARNING!!!!') print('No such data type as '+data_type+'. Please check your spelling and run again.') print('') return if len(mytable) > 0: print('OK') if deep == 1: plot_title = parse_title(data_type)+". dataset OWID" elif deep > 1: plot_title = parse_title(data_type)+". "+str(deep)+" days moving average. dataset OWID" mytable.plot(legend=True, label=pais, grid=True, logy=False, figsize=(12,6), title=plot_title, xlabel='date') else: print('') print('') print('WARNING!!!!') print('No such country as '+pais+'. Please check your spelling and run again.') print('') return if outputfile == 0: print('Preparing plot... ', end='') plt.savefig('temporalMLO2511.png') fooooo = pili.open('temporalMLO2511.png').show() os.remove('temporalMLO2511.png') print('OK') else: print('Saving plot... ', end='') plt.savefig(outputfile) print('OK') print('File saved to',outputfile) def input_output_execution(): ''' INPUT: - RETURN: - OUTPUT: after executing input questions to the user ir executes draw_many_lines function with the proper arguments ''' ### GENERAL INFORMATION os.system('cls') print('======================================================================================================') print('') print(' PLOT COVID-19 DATA ') print('This program is designed to plot time series lines for different COVID-19 data of different countries.') print('Author: Matias Leoni') print('') print('Credit for the dataset:') print('Hasell, J., Mathieu, E., Beltekian, D. et al. A cross-country database of COVID-19 testing.') print('Sci Data 7, 345 (2020). https://doi.org/10.1038/s41597-020-00688-8') print('======================================================================================================') ### INPUT Country names in English country_list = [] while True: print() print('Input country name in english (e.g. Argentina).') print("If you would like to see a country list to check your spelling press '?'") country = input('If no more countries are needed just press ENTER: ') if country == '' and len(country_list) > 0: break elif country == '' and len(country_list) == 0: os.system('cls') print() print('At least one country name is needed') elif country == '?': os.system('cls') print() if len(country_list) > 0: print('Your set of country choices is: ',end='') print(*country_list, sep=', ') print('') print(*sorted(list(dt.COUNTRIES)), sep=', ') elif country.title() not in dt.COUNTRIES: os.system('cls') print() if len(country_list) > 0: print('Your set of country choices is: ',end='') print(*country_list, sep=', ') print('') print(country, 'is non-existent. Check your spelling') elif country.title() in dt.COUNTRIES: country_list.append(country.title()) country_list = list(set(country_list)) os.system('cls') print('') print('Your set of country choices is: ',end='') print(*country_list, sep=', ') os.system('cls') print('') print('Your set of country choices is: ',end='') print(*country_list, sep=', ') ### Present data types print() print('=====================================================================') print() print() data_type_list = dt.data_list data_type_obj = dt.numbered_dic(data_type_list) data_type_dic = data_type_obj.alist print('LIST OF DATA TYPES') print('----------------------------------------------------------------------') data_type_obj.printdic() print() print('----------------------------------------------------------------------') print() ### INPUT Data types more = True while more: print('Please choose a data type from the previous list.') try: data_type = data_type_dic[int(input('For example, press 2 for new_cases: '))] more = False except ValueError: print('') print('Not an integer number. Try again') print('') except KeyError: print('') print('Your number is out of range. Try again') print('') print() print() os.system('cls') print('') print('Your set of country choices is: ',end='') print(*country_list, sep=', ') print('') print('Your choice of data type to plot: ', parse_title(data_type)) print('=====================================================================') print('') ### INPUT integer number corresponding to the number of days for the moving average while True: try: print('Input an integer number (days) for smoothing data with moving average.') deep_avg = input('1 is the default. 7 is the recommended for daily data: ') if deep_avg == '': deep_avg = 1 else: deep_avg = int(deep_avg) break except ValueError: print('') print('That was not an integer number. Please try again') print('') print() print() os.system('cls') print('') print('Your set of country choices is: ',end='') print(*country_list, sep=', ') print('') print('Your choice of data type to plot: ', parse_title(data_type)) print('') if deep_avg > 1: print('You decided to plot using a', deep_avg,'days moving average ') print('=====================================================================') print('') ### INPUT the desired starting date while True: try: print('Input starting date in format YYYY-MM-DD.') init_date = input('For example 2020-06-30. Press ENTER for default (beginning of the pandemic):') if init_date == '': init_date = '2019-12-31' else: transdate(init_date) break except ValueError: print('') print('Non-existent date or incorrect format. Please try again') print('') print() print() os.system('cls') print('') print('Your set of country choices is: ',end='') print(*country_list, sep=', ') print('') print('Your choice of data type to plot: ', parse_title(data_type)) print('') if deep_avg > 1: print('You decided to plot using a', deep_avg,'days moving average ') print('') print('You will plot data starting on', init_date) print('=====================================================================') print('') ### INPUT the name of the file to render the plot print('Input the file name for the output (e.g: grafico.png).') outputfile = input('Press ENTER to show the plot without saving it: ') if outputfile == '': outputfile = 0 os.system('cls') print('') print('Your set of country choices is: ',end='') print(*country_list, sep=', ') print('') print('Your choice of data type to plot: ', parse_title(data_type)) print('') if deep_avg > 1: print('You decided to plot using a', deep_avg,'days moving average ') print('') print('You will plot data starting on', init_date) print('') if outputfile == 0: print('The plot will be shown in a new window and will not be saved') else: print('The plot will be saved to the file: ', outputfile) ### EXECUTE draw_many_lines(country_list, data_type, deep_avg, init_date, outputfile) # while True: # execute = input('Do you want to execute the program interactively? (y/n): ') # if execute == 'y': # input_output_execution() # del(execute) # break # elif execute == 'n': # del(execute) # break input_output_execution()
# Ask the user to enter their name x = raw_input("What's your name? \n") # Print hello + their name print("Hello, " + x)
# Uses python3 # Given two integers a and b, find their greatest common divisor. # Input.The two integers a,b are given in the same line separated by space. # Constraints. 1 ≤ a,b ≤ 2·109. # Output Format. Output GCD(a,b). import sys def gcd(a, b): if a % b == 0: return b else: return gcd(b, a % b) #for automatic tests if __name__ == "__main__": input = sys.stdin.read() a, b = map(int, input.split()) print(gcd(a, b))
#comment one def do_nothing(c): if c > 0: do_nothing(c - 1) def main(): # comment two frmt = """#comment one def do_nothing(c): if c > 0: do_nothing(c - 1) def main(): # comment two frmt = %c%c%c%s%c%c%c print frmt %% (34,34,34,frmt,34,34,34,34,34) if __name__ == %c__main__%c: main()""" print frmt % (34,34,34,frmt,34,34,34,34,34) if __name__ == "__main__": main()
file = open('text.txt', 'r') read = file.read() # – прочитать входной файл, считать все символы; print('все символы: ' + read) list1 = list() for i in read: if i.isdigit(): list1 += i print('цифры в файле, с сохранением порядка: ' + str(list1)) # – вывести те символы из файла, которые обозначают цифры от 0 до 9, в том порядке, как они встречаются в файле; print('цифры по убыванию: ' + str(sorted(list1, reverse=True))) # – вывести эти символы, упорядочив их по убыванию кода символа; list2 = list() for i in read: if i.isdigit(): if i not in list2 and i !=' ': list2 += i print(list2) # – вывести каждый символ не более одного раза;
""" Do not change the input and output format. If our script cannot run your code or the format is improper, your code will not be graded. The only functions you need to implement in this template is linear_regression_noreg, linear_regression_invertible,regularized_linear_regression, tune_lambda, test_error and mapping_data. """ import numpy as np import pandas as pd def _error(y, w): """ Simple error """ return np.subtract(y, w) ###### Q1.1 ###### def mean_absolute_error(w, X, y): """ Compute the mean absolute error on test set given X, y, and model parameter w. Inputs: - X: A numpy array of shape (num_samples, D) containing test feature. - y: A numpy array of shape (num_samples, ) containing test label - w: a numpy array of shape (D, ) Returns: - err: the mean absolute error """ ##################################################### # TODO 1: Fill in your code here # ##################################################### err = None temp = np.dot(X, w) err = np.mean(np.abs(_error(y, temp))) return err ###### Q1.2 ###### def linear_regression_noreg(X, y): """ Compute the weight parameter given X and y. Inputs: - X: A numpy array of shape (num_samples, D) containing feature. - y: A numpy array of shape (num_samples, ) containing label Returns: - w: a numpy array of shape (D, ) """ ##################################################### # TODO 2: Fill in your code here # ##################################################### temp = X.T result = np.dot(temp, X) result = np.linalg.inv(result) result = np.dot(result, temp) w = np.dot(result, y) return w ###### Q1.3 ###### def linear_regression_invertible(X, y): """ Compute the weight parameter given X and y. Inputs: - X: A numpy array of shape (num_samples, D) containing feature. - y: A numpy array of shape (num_samples, ) containing label Returns: - w: a numpy array of shape (D, ) """ ##################################################### # TODO 3: Fill in your code here # ##################################################### w = None X_X_T = np.dot(X.T, X) ev = 0 while ev < (10**-5): ev = np.min((np.linalg.eig(X_X_T)[0])) if ev < (10**-5): X_X_T = X_X_T + (10**-1) * np.identity(X_X_T.shape[0]) w = np.dot(np.dot(np.linalg.inv(X_X_T), X.T), y) return w ###### Q1.4 ###### def regularized_linear_regression(X, y, lambd): """ Compute the weight parameter given X, y and lambda. Inputs: - X: A numpy array of shape (num_samples, D) containing feature. - y: A numpy array of shape (num_samples, ) containing label - lambd: a float number containing regularization strength Returns: - w: a numpy array of shape (D, ) """ ##################################################### # TODO 4: Fill in your code here # ##################################################### w = None X_X_T = np.dot(X.T, X) X_X_T += lambd * np.identity(X_X_T.shape[0]) w = np.dot(np.dot(np.linalg.inv(X_X_T), X.T), y) return w ###### Q1.5 ###### def tune_lambda(Xtrain, ytrain, Xval, yval): """ Find the best lambda value. Inputs: - Xtrain: A numpy array of shape (num_training_samples, D) containing training feature. - ytrain: A numpy array of shape (num_training_samples, ) containing training label - Xval: A numpy array of shape (num_val_samples, D) containing validation feature. - yval: A numpy array of shape (num_val_samples, ) containing validation label Returns: - bestlambda: the best lambda you find in lambds """ ##################################################### # TODO 5: Fill in your code here # ##################################################### bestlambda = None err = 1 for v in range(-19,20): if v>=0: val = float("1e+"+str(v)) else: val = float("1e"+str(v)) w = regularized_linear_regression(Xtrain,ytrain, val) error = mean_absolute_error(w, Xval,yval) if err > error: err = error bestlambda = val return bestlambda ###### Q1.6 ###### def mapping_data(X, power): """ Mapping the data. Inputs: - X: A numpy array of shape (num_training_samples, D) containing training feature. - power: A integer that indicate the power in polynomial regression Returns: - X: mapped_X, You can manully calculate the size of X based on the power and original size of X """ ##################################################### # TODO 6: Fill in your code here # ##################################################### X_temp = X[:] for i in range(2, power + 1): x = np.power(X, i) for col in range(0, x.shape[1]): X_temp = np.insert(X_temp, X_temp.shape[1], x[:, col], axis=1) return X_temp
# -*- coding=utf-8 -*- import urlparse def reverseUrl(url): """ examples: http://bar.foo.com:8983/to/index.html?a=b com.foo.bar:http:8983/to/index.html?a=b https://www.google.com.hk:8080/home/search;12432?newwi.1.9.serpuc#1234 hk.com.google.www:https:8080/home/search;12432?newwi.1.9.serpuc#1234 """ reverse_url = '' url = urlparse.urlsplit(url) reverse_host = '.'.join(url.hostname.split('.')[::-1]) reverse_url += reverse_host reverse_url += ':' reverse_url += url.scheme if url.port: reverse_url += ':' reverse_url += str(url.port) if url.path: reverse_url += url.path if url.query: reverse_url += '?' reverse_url += url.query if url.fragment: reverse_url += '#' reverse_url += url.fragment return reverse_url if __name__ == '__main__': url = 'http://www.tianyancha.com/company/2313776032' url = 'http://www.11467.com/foshan/co/444200.htm' print reverseUrl(url)
""" - 9/28/2016 """ from random import randrange from typing import List def bsort(array: List[int]): modified = False size = len(array) - 1 for i in range(size): if array[i] > array[i+1]: array[i], array[i+1] = array[i+1], array[i] modified = True i += 1 if modified: bsort(array) def main(): to_sort = [randrange(0, 50) for _ in range(50, 0, -1)] print(to_sort) bsort(to_sort) print(to_sort) return 0 if __name__ == "__main__": main()
""" Mike McMahon """ from typing import List class LinkedList(object): class Node(object): def __init__(self, data: any = None, next_node=None): self._data = data self._next = next_node def get_next(self): return self._next def set_next(self, next_node): self._next = next_node def set_data(self, data): self._data = data def get_data(self): return self._data def __str__(self): return str(self._data) def __init__(self, initial: List=None): self._size = len(initial) if initial else 0 self._root = None self._tail = None if initial: for i in range(len(initial)): if i == 0: self._root = LinkedList.Node(initial[i]) self._tail = self._root else: self._tail.set_next(LinkedList.Node(initial[i])) self._tail = self._tail.get_next() def add(self, value): if self._root is None: self._root = LinkedList.Node(value) else: node = self.get(self._size) node.set_next(LinkedList.Node(value)) self._tail = node.get_next() self._size += 1 def __len__(self): return self._size def remove(self, i=None): """ Removes the element at a given position, if no position :param i: :return: """ if i: if i > self._size or self._size == 0: raise IndexError if i == 0: self._root = self._root.get_next() prev = None to_remove = self._root for _ in range(0, i): prev = to_remove to_remove = to_remove.get_next() prev.set_next(prev.get_next().get_next()) self._size -= 1 else: self.remove(self._size) def get(self, i) -> Node: """ O(N) :param i: :return: """ if i > self._size or self._size == 0: raise IndexError if i == 0: return self._root node = self._root for _ in range(0, i): node = node.get_next() return node def search(self, value): """ Given the nature of linked list we're working with O(N) time here... :param value: :return: """ node = self._root for _ in range(0, self._size): if node.get_data() == value: return node node = node.get_next() raise ValueError("Value not found in linked list") def __str__(self): node = self._root str_rpr = "[" for _ in range(0, self._size): str_rpr += str(node.get_data()) + "," node = node.get_next() return str_rpr[:-1] + "]" def main(): arr = [1, 2, 3, 4, 5, 6, 7] llist = LinkedList(arr) print(len(llist)) print(llist) llist.remove(3) print(len(llist)) print(llist) if __name__ == "__main__": main()
#!/usr/bin/env python import sys # input comes from STDIN (standard input) for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() # Calculate the length of the line vlen = len(line) # TODO: Students to output <lineLength, 1> print('%s\t%s' % (vlen, 1))
# import os, csv, datetime and openpyxl libraries import os import csv from datetime import datetime from openpyxl import Workbook folder = './data' # function to scan folder for xlsx and csv files def scan_folder(folder): print(os.getcwd()) files = os.listdir(folder) xlsx_files = [] csv_files = [] # categorize file types for f in files: fcomp = f.split('.') if fcomp[-1] == 'xlsx': xlsx_files.append(f) if fcomp[-1] == 'csv': csv_files.append(f) return {'XLSX': xlsx_files, 'CSV':csv_files} # function to extract CSV contents def extract_csv(files): records = [] for f in files: print(f + ' is CSV file') return records def gen_sumfile(records): print(records) # main program if __name__=='__main__': files = scan_folder(folder) if len(files['CSV']) > 0: records = extract_csv(files['CSV']) gen_sumfile(records)
''' Ask the user what their Favorite ganmeis and say that you also like to play that game''' game = input('what is your Favourite game?\n') print("i like to paly",game,"too")
class Parser: def __init__(self, grammar, word): self.grammar = grammar self.alpha = word + '$' self.pif = self.readPIF("PIF.txt") self.st = self.readFile("ST.txt") self.codificationTable = self.readCodificationTable() def parseSequence(self): beta = self.grammar.S + '$' pi = '' accepted = True ok = True while ok: if beta[0] == 'e': value = self.grammar.TABLE[('$', self.alpha[0])] else: value = self.grammar.TABLE[(beta[0], self.alpha[0])] if len(value) == 2: value[0] = value[0].replace(' ', '') beta = beta[1:] if value[0] != 'e': beta = str(value[0]) + beta pi += str(value[1]) print(self.grammar.P[value[1]]) else: if len(value) == 1: if value[0] == "POP": beta = beta[1:] self.alpha = self.alpha[1:] elif value[0] == "ACC": ok = False accepted = True else: ok = False accepted = False return accepted def readCodificationTable(self): filepath = 'codificationTable.txt' codificationTable = {} with open(filepath) as file: line = file.readline() while line: line = line.strip().split(' ') codificationTable[line[1]] = line[0] line = file.readline() return codificationTable def readFile(self, filename): st = {} with open(filename) as file: line = file.readline() while line: line = line.strip().replace(' ', '').split("|") st[line[0]] = line[1] file.readline() line = file.readline() return st def readPIF(self, filename): pif = [] with open(filename) as file: line = file.readline() while line: line = line.strip().replace(' ', '').split("|") pif.append(line) file.readline() line = file.readline() return pif def parseByPIF(self): word = [] for code, posST in self.pif: if posST == "-1": word.append(self.codificationTable[code]) else: word.append(self.st[posST]) word.append('$') print(word) beta = [] beta.append(self.grammar.S) beta.append('$') pi = '' accepted = True ok = True while ok: if beta[0] == 'e': value = self.grammar.TABLE[('$', word[0])] else: value = self.grammar.TABLE[(beta[0], word[0])] if len(value) == 2: value[0] = value[0].split(' ') beta = beta[1:] if value[0] != 'e': beta[0:0] = value[0] pi += str(value[1]) print(self.grammar.P[value[1]]) else: if len(value) == 1: if value[0] == "POP": beta = beta[1:] word = word[1:] elif value[0] == "ACC": ok = False accepted = True else: ok = False accepted = False return accepted
#Description: Build a movie recommendation engine (more specifically a content based recommendation engine) #Import Libraries import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics.pairwise import cosine_similarity #Load the data from google.colab import files # Use to load data on Google Colab uploaded = files.upload() # Use to load data on Google Colab df = pd.read_csv("movie_dataset.csv") #Print the first 3 rows of the data set df.head(3) #Get a count of the number of rows/movies in the data set and the number of columns df.shape #Create a list of important columns to keep a.k.a. the main content of the movie features = ['keywords','cast','genres','director'] df[features].head(3) #Clean and preprocess the data for feature in features: df[feature] = df[feature].fillna('') #Fill any missing values with the empty string # print(df[feature]) #A function to combine the values of the important columns into a single string def combine_features(row): return row['keywords'] +" "+row['cast']+" "+row["genres"]+" "+row["director"] #Apply the function to each row in the dataset to store the combined strings into a new column called combined_features df["combined_features"] = df.apply(combine_features,axis=1) #df["combined_features"] #Print the data frame to show the new column 'combined_features' df.head(3) #Convert a collection of text to a matrix/vector of token counts count_matrix = CountVectorizer().fit_transform(df["combined_features"]) #Print the count matrix #print(count_matrix.toarray()) #Get the cosine similarity matrix from the count matrix (cos(theta)) cosine_sim = cosine_similarity(count_matrix) #Print the cosine similarity matrix print(cosine_sim) #Get the number of rows and columns in the data set cosine_sim.shape #Helper function to get the title from the index def get_title_from_index(index): return df[df.index == index]["title"].values[0] #Helper function to get the index from the title def get_index_from_title(title): return df[df.title == title]["index"].values[0] #Get the title of the movie that the user likes movie_user_likes = "The Amazing Spider-Man" #Find that movies index movie_index = get_index_from_title(movie_user_likes) #Access the row, through the movies index, corresponding to this movie (the liked movie) in the similarity matrix, # by doing this we will get the similarity scores of all other movies from the current movie #Enumerate through all the similarity scores of that movie to make a tuple of movie index and similarity scores. # This will convert a row of similarity scores like this- [5 0.6 0.3 0.9] to this- [(0, 5) (1, 0.6) (2, 0.3) (3, 0.9)] . # Note this puts each item in the list in this form (movie index, similarity score) similar_movies = list(enumerate(cosine_sim[movie_index])) #Sort the list of similar movies according to the similarity scores in descending order #Since the most similar movie is itself, we will discard the first element after sorting. sorted_similar_movies = sorted(similar_movies,key=lambda x:x[1],reverse=True)[1:] #Print the sorted similar movies to the movie the user like # The tuples are in the form (movie_index, similarity value) print(sorted_similar_movies) #Create a loop to print the first 5 entries from the sorted similar movies list i=0 print("Top 5 similar movies to "+movie_user_likes+" are:") for element in sorted_similar_movies: print(get_title_from_index(element[0]) ) i=i+1 if i>=5: break #Create a loop to print the first 5 entries from the sorted similar movies list # and similarity scores i=0 print("Top 5 similar movies to "+movie_user_likes+" are:") for i in range( len(sorted_similar_movies)): print('Movie title:',get_title_from_index(sorted_similar_movies[i][0]), ', Similarity Score: ', sorted_similar_movies[i][1] ) i=i+1 if i>=5: break
#Created by: Justin Bronson #Created on: Sept, 2017. #Created for: ICS3U #This program calculates the height of an # object in mid air using the gravity formula import ui def calculate_button_touch_up_inside(sender): #calculate circumference #constant GRAVITY = 9.8 #input seconds = int(view['seconds_textbox'].text) #process height = 100 - (0.5 * GRAVITY * seconds ** 2) #output view['answer_label'].text = 'The height is: ' + str(height) + ' cm' view = ui.load_view() view.present('full_screen')
#!/usr/bin/env python3 import os, glob def main(): rootDir = input('Enter parent directory to run script: ') + '/' keywords = input('Enter words in filename to be replaced (multiple words separated by space): ').split(" ") replaceInFileName = input('Enter string to take its place (Enter to remove keywords): ') print('replacing with ', replaceInFileName) for keyword in keywords: print('changing for keyword ', keyword) for filename in os.listdir(rootDir): print('scanning ' + filename) if "." and keyword in filename: newFileName = filename.replace(keyword, replaceInFileName) print('new file name: ', newFileName) src = rootDir + filename dst = rootDir + newFileName print("src: " + src) print("dst: " + dst) os.rename(src, dst) print(filename + " changed to " + newFileName) print(' ') if __name__ == '__main__': main()
from tkinter import * from functools import partial from NewWordPage import NewWordPage class Startpage: #-------------------------------# #----------CONSTRUCTOR----------# #-------------------------------# def __init__(self, window): Button(window, text="Add a new word", command=lambda: self.show_new_word_page(window)).grid(row=1) #--------------------------------------# #----------SHOW NEW WORD PAGE----------# #--------------------------------------# def show_new_word_page(self, window): for element in window.grid_slaves(): # Removing all the window's content. element.grid_forget() newWordPage = NewWordPage(window) # Showing the NewWordPage.
# We maintain a stack of active rectangles. # One could store them as pairs (start, height) # Here an optimization is to store rightmost locations of bottleneck heights. # Then both start and height are encoded in same queue: # the height is just heights[bottleneck location], # and the start of the rectangle is just after # the location of the rightmost bottleneck # for the next shorter rectangle in the queue! class Solution: def largestRectangleArea(self, heights: list[int]) -> int: heights.append(0) rightmost_locations_of_bottleneck = [-1] max_area = 0 for end, next_height in enumerate(heights): # Close off non-extendable rectangles. while next_height < heights[rightmost_locations_of_bottleneck[-1]]: # Remove and compute height. height = heights[rightmost_locations_of_bottleneck.pop()] area = (end-(rightmost_locations_of_bottleneck[-1]+1))*height if area > max_area: max_area = area # If needed, move the bottleneck. if next_height == heights[rightmost_locations_of_bottleneck[-1]]: rightmost_locations_of_bottleneck[-1] = end # If needed, add a new rectangle. else: rightmost_locations_of_bottleneck.append(end) return max_area if __name__ == "__main__": solution = Solution() heights = [2] found = solution.largestRectangleArea(heights) print(found)
# Reading an excel file using Python import xlrd import pandas as pd import sys class ExcelFileParser: def parseFile(self, inputFilePath, outPutFilePath): csv = pd.read_csv(inputFilePath, error_bad_lines=False) csv = csv.rename(columns={'Team 1': 'home_team'}) csv = csv.rename(columns={'Team 2': 'away_team'}) csv = csv.drop(columns='HT') home_score = csv['FT'] new_home_scores = [] new_away_scores = [] for str in home_score: ind = str.index('-') new_home_scores.append(str[:ind]) new_away_scores.append(str[ind+1:]) csv['home_score'] = new_home_scores csv['away_score'] = new_away_scores csv.to_csv(outPutFilePath, index=None, header=True) if __name__ == "__main__": excelParser = ExcelFileParser() excelParser.parseFile("./season/%s" % sys.argv[1], "./season/%s" % sys.argv[2])
entrada = input ("Entre com um valor: ") print "Voce entrou com o valor: " + str (entrada)
def prime(n): prime = True for el in range(2, n//2): if n % el == 0: prime = False break return prime number = int(input()) for i in range(2, number//2+1): if prime(i) and prime(number - i): print(i, number-i) break
from typing import Sequence import warnings import matplotlib.pyplot as plt import numpy as np __all__ = [ 'calculate_enrichment_factor', 'convert_label_to_zero_or_one', 'plot_predictiveness_curve', ] def _normalize(arr): return (arr - arr.min()) / (arr.max() - arr.min()) def _set_axes(ax, lim, fontsize: int): ax.set_xlim(left=lim[0], right=lim[1]) ax.grid(True) ax.xaxis.label.set_fontsize(fontsize) ax.yaxis.label.set_fontsize(fontsize) def plot_predictiveness_curve(risks, labels, classes: Sequence = [0, 1], normalize: bool = False, points: int = 100, figsize: Sequence = (4.5, 10), fontsize: int = 14, kind: str = 'TPR', xlabel: str = None, top_ylabel: str = None, bottom_ylabel: str = None, **kwargs): """ Plot predictiveness curve. Predictiveness curve is a method to display two graphs simultaneously. In both figures, the x-axis is risk percentile, the y-axis of one figure is the value of risk, and the y-axis of the other figure is true positive fractions. See Am. J. Epidemiol. 2008; 167:362–368 for details. The plot of EF at the threshold value where the product with the sample data is less than 1 are not displayed. Parameters ---------- risks : array_like, shape = [n_samples] Risks or probabilities for something happens labels : array_like, shape = [n_samples] Labels for sample data. The argument classes can set negative and postive values respectively. In default, 0 means negative and 1 means positive. classes : array_like, default [0, 1] Represents the names of the negative class and the positive class. Give in the order of [negative, positive]. In default, 0 means negative and 1 means positive. normalize : boolean, default False If the risk data is not normalized to the 0-1 range, normalize it. points : int, default 100 Determine the fineness of the plotted points. The larger the number, the finer the detail. figsize : tuple, default (4.5, 10) Width, height in inches. If not provided, defaults to = (4.5, 10). fontsize : int, default 14 Font size for labels in plots. kind : str, default TPR * TPR : plot risk percentile vs TPR at bottom. * EF : plot risk percentile vs EF at bottom. The risk percentile of the upper plot is also in descending order. xlabel : str, default Risk percentiles Set the label for the x-axis. top_ylabel : str, default Risk Set the label for the y-axis in the top plot. bottom_ylabel : str, default value of kind. Set the label for the y-axis in the bottom plot. **kwargs : matplotlib.pyplot.Line2D properties, optional This function internally calls matplotlib.pyplot.plot. The argument kwargs is passed to this function. See https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot for details. Returns ------- figure : matplotlib.figure.Figure A figure instance is returned. You can also assign this figure instant attribute and customize it yourself. """ risks = np.array(risks) labels = np.array(labels) thresholds = np.linspace(0, 1, points + 1)[1:] points = np.linspace(0, 1, points + 1) if not np.all(np.unique(labels) == np.unique(classes)): raise ValueError('The values of labels and classes do not match') default_classes = [0, 1] # Sequence if not np.array_equal(classes, default_classes): labels = convert_label_to_zero_or_one(labels, classes) if normalize: risks = _normalize(risks) if xlabel is None: xlabel = 'Risk percentiles' if top_ylabel is None: top_ylabel = 'Risk' if bottom_ylabel is None: bottom_ylabel = kind labels = labels[np.argsort(risks)] risks = np.sort(risks) num_positive: int = labels.sum() if kind.upper() == 'TPR': def f(point): count: int = np.count_nonzero(risks <= point) return count / len(risks) if count > 0 else 0 calculate_risk_percentiles = np.frompyfunc(f, 1, 1) risk_percentiles = calculate_risk_percentiles(points) risk_percentiles = np.append(0, risk_percentiles) points = np.append(0, points) elif kind.upper() == 'EF': def f(point): count: int = np.count_nonzero(risks >= point) return count / len(risks) if count > 0 else 0 labels = labels[::-1] risks = risks[::-1] calculate_risk_percentiles = np.frompyfunc(f, 1, 1) risk_percentiles = calculate_risk_percentiles(points) risk_percentiles = np.append(risk_percentiles, 0) points = np.append(points, 1) else: raise ValueError(f'kind must be either TPR or EF, not {kind}') margin: float = 0.03 lim: Sequence = (0 - margin, 1 + margin) fig = plt.figure(figsize=figsize) ax = fig.add_subplot(2, 1, 1) _set_axes(ax, lim, fontsize) ax.set_ylim(bottom=lim[0], top=lim[1]) ax.plot(risk_percentiles, points, **kwargs) ax.yaxis.set_label_text(top_ylabel) ax = fig.add_subplot(2, 1, 2) if kind.upper() == 'TPR': calculate_true_positive_fractions = np.frompyfunc( lambda p: np.count_nonzero(labels[risks >= p]) / num_positive, 1, 1) true_positive_fractions = calculate_true_positive_fractions(points) _set_axes(ax, lim, fontsize) ax.set_ylim(bottom=lim[0], top=lim[1]) ax.plot(risk_percentiles, true_positive_fractions, **kwargs) elif kind.upper() == 'EF': n = np.floor(risks.shape[0] * thresholds).astype('int32') if np.any(n == 0): warning_message = ( 'The plot of EF at the threshold value where the product with ' 'the sample data is less than 1 is not displayed.') warnings.warn(warning_message) thresholds = thresholds[n != 0] enrichment_factors = calculate_enrichment_factor(risks, labels, threshold=thresholds) _set_axes(ax, lim, fontsize) ax.plot(thresholds, enrichment_factors, **kwargs) ax.xaxis.set_label_text(xlabel) ax.yaxis.set_label_text(bottom_ylabel) return fig def calculate_enrichment_factor(scores, labels, classes=[0, 1], threshold=0.01): """ Calculate enrichment factor. Returns one as the value of enrichment factor when the product of sample data and threshold is less than one. Parameters ---------- scores : array_like, shape = [n_samples] Scores, risks or probabilities for something happens labels : array_like, shape = [n_samples] Labels for sample data. The argument classes can set negative and postive values respectively. In default, 0 means negative and 1 means positive. classes : array_like, default [0, 1] Represents the names of the negative class and the positive class. Give in the order of [negative, positive]. In default, 0 means negative and 1 means positive. threshold : int, float, array_like of int or float, default is 0.01 If the value of threshold is 1 or more, it means percent, and if it is less than 1, it simply assumes that it represents a ratio. In addition, it returns one value for int or float, and broadcast for array_like. Returns ------- enrichment factors : float or ndarray Return enrichment factors. If threshold is int or float, return one value. If threshold is array_like, return ndarray. """ def f(threshold): n = int(np.floor(scores.size * threshold)) if n == 0: return np.nan return (np.count_nonzero(labels[-n:]) / n) / positive_ratio scores = np.array(scores) labels = np.array(labels) threshold = np.array(threshold) if np.any(threshold <= 0) | np.any(threshold > 100): raise ValueError('Invalid value for threshold. Threshold should be ' 'either positive and smaller a int or ints than 100 ' 'or a float in the (0, 1) range') elif threshold.dtype.kind == 'f' and (np.any(threshold <= 0) or np.any(threshold > 1)): raise ValueError('Invalid value for threshold. Threshold should be ' 'either positive and a float or floats in the (0, 1) ' 'range') elif threshold.dtype.kind == 'i': threshold = threshold.astype('float32') / 100 if not np.all(np.unique(labels) == np.unique(classes)): raise ValueError('The values of labels and classes do not match') default_classes: Sequence = [0, 1] if not np.array_equal(classes, default_classes): labels = convert_label_to_zero_or_one(labels, classes) labels = labels[np.argsort(scores)] scores = np.sort(scores) positive_ratio = np.count_nonzero(labels) / scores.size _calculate_enrichment_factor = np.frompyfunc(f, 1, 1) enrichment_factors = _calculate_enrichment_factor(threshold) if isinstance(enrichment_factors, float): return_float: bool = True enrichment_factors = np.array([enrichment_factors], dtype='float32') else: return_float: bool = False enrichment_factors = enrichment_factors.astype('float32') if np.any(np.isnan(enrichment_factors)): warning_message = ( 'Returns one as the value of enrichment factor because ' 'the product of sample data and threshold is less than one') warnings.warn(warning_message) enrichment_factors[np.isnan(enrichment_factors)] = 1.0 if return_float: enrichment_factors = enrichment_factors[0] return enrichment_factors def convert_label_to_zero_or_one(labels, classes): """ Convert label data of specified class into 0 or 1 data. Parameters ---------- labels : array_like, shape = [n_samples] Labels for sample data. classes : array_like Represents the names of the negative class and the positive class. Give in the order of [negative, positive]. Returns ------- converted label : ndarray, shape = [n_samples] Return ndarray which converted labels to 0 and 1. """ if not np.all(np.unique(labels) == np.unique(classes)): raise ValueError('The values of labels and classes do not match') labels = np.asarray(labels) return (labels == classes[1]).astype('int16')
# remove() method - If the item to remove does not exist, it will throw an error set1 = {"apple", "banana", "cherry"} set1.remove("banana") print(set1) # discard() method - If the item to remove does not exist, it will not throw an error set2 = {"apple", "banana", "cherry"} set2.discard("banana") print(set2) # pop() method - This method will remove the last item. # Return value of the pop() method is the removed item. set3 = {"apple", "banana", "cherry"} x = set3.pop() print(x) print(set3) # clear() method - This empties the set set4 = {"apple", "banana", "cherry"} set4.clear() print(set4) # del keyword - Will delete the set completely set5 = {"apple", "banana", "cherry"} del set5 print(set5)
# Note: Both union() and update() will exclude any duplicate items. # union() method - used to join items from two sets and returns a new set set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set3 = set1.union(set2) print(set3) # update() method - inserts all the items from one set into another setA = {"a", "b" , "c"} setB = {1, 2, 3} setA.update(setB) print(setA) # intersection_update() - will keep only the items that are present in both sets x1 = {"apple", "banana", "cherry"} y1 = {"google", "microsoft", "apple"} x1.intersection_update(y1) print(x1) # intersection() - will return a new set, that only contains the items that are present in both sets x2 = {"apple", "banana", "cherry"} y2 = {"google", "microsoft", "apple"} z2 = x2.intersection(y2) print(z2) # symmetric_difference_udpate() - will keep only the elements that are NOT present in both sets x3 = {"apple", "banana", "cherry"} y3 = {"google", "microsoft", "apple"} x3.symmetric_difference_update(y3) print(x3) # symmetric_difference() - will return a new set, # that contains only the elements that are NOT present in both sets x4 = {"apple", "banana", "cherry"} y4 = {"google", "microsoft", "apple"} z4 = x4.symmetric_difference(y4) print(z4)
# if - else a = 90 if (a < 10): print ("a is less than 10") else: print ("a is greater than 10") # if - elif - else a = 50 if (a == 10): print(a) elif ( a == 50): print(a) else: print ("a is undefined") # Nested if a = 35 if (a != 0): if(a < 40): print("a is less than 40") else: print("a is greater than 40") else: print("a is zero")
# For loop tuple4 = ("summer", "winter", "spring") for x in tuple4: print (x) # Loop Through the Index Numbers - loop through the tuple items by referring to their index number. # Use the range() and len() functions to create a suitable iterable. tuple4 = ("summer", "winter", "spring") for x in range(len(tuple4)): print (str(x) +":"+ tuple4[x]) # While loop """ Use the len() function to determine the length of the tuple, then start at 0 and loop your way through the tuple items by referring to their indexes. increase the index by 1 after each iteration. """ tuple5 = ("summer", "winter", "spring") i = 0 while i < len(tuple5): print (tuple5[i]) i = i + 1
choice = raw_input('rock(r), paper(p),scissors(s), lizard(l), or spock(sp)? ') from random import randint com_choice = randint(1,5) if com_choice == 1: computer = 'r' elif com_choice == 2: computer = 'p' elif com_choice == 3: computer = 's' elif com_choice == 4: computer = 'l' elif com_choice == 5: computer = 'sp' #DRAW if choice == computer: print('We have a draw') #ROCK elif choice == 'r' and computer == 's': print('''Rock crushes scissors you win ''') elif choice == 'r' and computer == 'p': print('''paper covers rock you lose''') elif choice == 'r' and computer == 'l': print('''rock crushes lizard you win''') elif choice == 'r' and computer == 'sp': print('''Spock vaporizes rock you lose''') #SCISSORS elif choice == 's'and computer == 'r': print('''Rock crushes scissors you lose''') elif choice == 's' and computer == 'p': print('''Scissors cuts paper you win''') elif choice == 's' and computer == 'l': print('''Scissors decapitates lizard you win''') elif choice == 's' and computer == 'sp': print('''Spock smashes scissors you lose''') #PAPER elif choice == 'p' and computer == 's': print('''Scissors cuts paper you lose''') elif choice == 'p' and computer == 'r': print('''Paper covers rock you win''') elif choice == 'p' and computer == 'l': print('''Lizard eats paper you lose''') elif choice == 'p' and computer == 'sp': print('''paper disproves spock you win''') #LIZARD elif choice == 'l' and computer == 'r': print('''Rock crushes lizard you lose''') elif choice == 'l' and computer == 'p': print('''Lizard eats paper you win''') elif choice == 'l' and computer == 's': print('''Scissors decapitates lizard you lose''') elif choice == 'l' and computer == 'sp': print('''Lizard poisons spock you win''') #SPOCK elif choice == 'sp' and computer == 'r': print('''Spock vaporizes rock you win''') elif choice == 'sp' and computer == 'p': print('''Spock disproves paper you lose''') elif choice == 'sp' and computer == 's': print('''Spock crushes scissors you win''') elif choice == 'sp'and computer == 'l': print('''Lizard poisons spock you lose''')
#prueba para método resta def resta(num1, num2): return num1 - num2 resultado_1 = resta(num1 = 60, num2 = 30) resultado_2 = resta(num1 = 0, num2 = 0) resultado_3 = resta(num1 = 1000, num2 = 4000) print(f'El resultado de la resta 1 es: {resultado_1}') print(f'El resultado de la resta 2 es: {resultado_2}') print(f'El resultado de la resta 3 es: {resultado_3}')
print('0~100までの得点(整数値)を2つ入力して下さい') n1=int(input('1つ目の得点:')) n2=int(input('2つ目の得点:')) if n1>=80 and n2>=80: print('合格です') elif n1>=80 or n2>=80: print('補欠合格です') else: print('不合格です')
n=int(input('0~100までの得点(整数値)を入力して下さい')) if n>=80: print('合格です') n=int(input('0~100までの得点(整数値)を入力して下さい')) if n>=60: print('合格です') else: print('不合格です')
x=int(input('0~100までの国語の得点(整数値)を入力して下さい')) if x>80: y=int(input('0~100までの英語の得点(整数値)を入力して下さい')) if y>=80: print('合格です') else : print('不合格です') else: z=int(input('0~100までの数学の得点(整数値)を入力して下さい')) if z>=80: print('合格です') else: print('不合格です')
n=int(input('0~100までの得点(整数値)を入力して下さい')) if n<0 or n>100 : print('入力値が不正です') else : print('正しい入力値です')
a=0 b=100 while a<b: a+=1 if a%3==0: continue print(a)
def write(dic): for i,c in dic.items(): print(i,":",c) dic={"赤":"red", "白":"white", "黒":"black", "青":"blue", "緑":"green"} write(dic)
# ------------------- # Background Information # # In this problem, you will build a planner that helps a robot # find the shortest way in a warehouse filled with boxes # that he has to pick up and deliver to a drop zone. #For example: # #warehouse = [[ 1, 2, 3], # [ 0, 0, 0], # [ 0, 0, 0]] #dropzone = [2,0] #todo = [2, 1] # Robot starts at the dropzone. # Dropzone can be in any free corner of the warehouse map. # todo is a list of boxes to be picked up and delivered to dropzone. # Robot can move diagonally, but the cost of diagonal move is 1.5 # Cost of moving one step horizontally or vertically is 1.0 # If the dropzone is at [2, 0], the cost to deliver box number 2 # would be 5. # To pick up a box, robot has to move in the same cell with the box. # When a robot picks up a box, that cell becomes passable (marked 0) # Robot can pick up only one box at a time and once picked up # he has to return it to the dropzone by moving on to the cell. # Once the robot has stepped on the dropzone, his box is taken away # and he is free to continue with his todo list. # Tasks must be executed in the order that they are given in the todo. # You may assume that in all warehouse maps all boxes are # reachable from beginning (robot is not boxed in). # ------------------- # User Instructions # # Design a planner (any kind you like, so long as it works). # This planner should be a function named plan() that takes # as input three parameters: warehouse, dropzone and todo. # See parameter info below. # # Your function should RETURN the final, accumulated cost to do # all tasks in the todo list in the given order and this cost # must which should match with our answer). # You may include print statements to show the optimum path, # but that will have no effect on grading. # # Your solution must work for a variety of warehouse layouts and # any length of todo list. # Add your code at line 76. # # -------------------- # Parameter Info # # warehouse - a grid of values. where 0 means that the cell is passable, # and a number between 1 and 99 shows where the boxes are. # dropzone - determines robots start location and place to return boxes # todo - list of tasks, containing box numbers that have to be picked up # # -------------------- # Testing # # You may use our test function below, solution_check # to test your code for a variety of input parameters. warehouse = [[ 1, 2, 3], [ 0, 0, 0], [ 0, 0, 0]] dropzone = [2,0] todo = [2, 1] def compute_cost_to_goal(grid, init, goal, cost_step_adj, cost_step_diag): delta = [[-1, 0 ], # 0 go up [ 0, -1], # 1 go left [ 1, 0 ], # 2 go down [ 0, 1 ], # 3 go right [-1, -1], # 4 diag up-left [-1, 1], # 5 diag up-right [1, -1], # 6 diag down-left [1, 1],] # 7 diag down-right value = [[999 for row in range(len(grid[0]))] for col in range(len(grid))] value[goal[0]][goal[1]] = 0 open = [] open.append([ 0, goal[0], goal[1]]) visited = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] visited[goal[0]][goal[1]] = 1 while(1): if len(open) == 0: break; else: open.sort() open.reverse() next = open.pop() x = next[1] y = next[2] for i in range(len(delta)): x2 = x + delta[i][0] y2 = y + delta[i][1] if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 < len(grid[0]): if visited[x2][y2] == 0 and grid[x2][y2] == 0: if i < 4: cost = cost_step_adj else: cost = cost_step_diag value[x2][y2] = value[x][y] + cost open.append([value[x2][y2], x2, y2]) visited[x2][y2] = 1 #for i in range(len(value)): # print value[i] return value[init[0]][init[1]] # return cost to the goal from the init state def find_box_location(warehouse, box_number): for i in range(len(warehouse)): for j in range(len(warehouse[0])): if warehouse[i][j] == box_number: return [i, j] # ------------------------------------------ # plan - Returns cost to take all boxes in the todo list to dropzone # # ---------------------------------------- # modify code below # ---------------------------------------- def plan(warehouse, dropzone, todo): cost = 0 wh = warehouse wh[dropzone[0]][dropzone[1]] = 0 for i in range(len(todo)): box_number = todo[i] box_location = find_box_location(wh, box_number) #print '\nbox location', box_location[0], box_location[1] box_cost = compute_cost_to_goal(wh, dropzone, box_location, 1.0, 1.5); cost += 2. * box_cost #remove the box from the warehouse wh[box_location[0]][box_location[1]] = 0 return cost ################# TESTING ################## # ------------------------------------------ # solution check - Checks your plan function using # data from list called test[]. Uncomment the call # to solution_check to test your code. # def solution_check(test, epsilon = 0.00001): answer_list = [] import time start = time.clock() correct_answers = 0 for i in range(len(test[0])): user_cost = plan(test[0][i], test[1][i], test[2][i]) true_cost = test[3][i] if abs(user_cost - true_cost) < epsilon: print "\nTest case", i+1, "passed!" answer_list.append(1) correct_answers += 1 #print "#############################################" else: print "\nTest case ", i+1, "unsuccessful. Your answer ", user_cost, "was not within ", epsilon, "of ", true_cost answer_list.append(0) runtime = time.clock() - start if runtime > 1: print "Your code is too slow, try to optimize it! Running time was: ", runtime return False if correct_answers == len(answer_list): print "\nYou passed all test cases!" return True else: print "\nYou passed", correct_answers, "of", len(answer_list), "test cases. Try to get them all!" return False #Testing environment # Test Case 1 warehouse1 = [[ 1, 2, 3], [ 0, 0, 0], [ 0, 0, 0]] dropzone1 = [2,0] todo1 = [2, 1] true_cost1 = 9 # Test Case 2 warehouse2 = [[ 1, 2, 3, 4], [ 0, 0, 0, 0], [ 5, 6, 7, 0], [ 'x', 0, 0, 8]] dropzone2 = [3,0] todo2 = [2, 5, 1] true_cost2 = 21 # Test Case 3 warehouse3 = [[ 1, 2, 3, 4, 5, 6, 7], [ 0, 0, 0, 0, 0, 0, 0], [ 8, 9,10,11, 0, 0, 0], [ 'x', 0, 0, 0, 0, 0, 12]] dropzone3 = [3,0] todo3 = [5, 10] true_cost3 = 18 # Test Case 4 warehouse4 = [[ 1,17, 5,18, 9,19, 13], [ 2, 0, 6, 0,10, 0, 14], [ 3, 0, 7, 0,11, 0, 15], [ 4, 0, 8, 0,12, 0, 16], [ 0, 0, 0, 0, 0, 0, 'x']] dropzone4 = [4,6] todo4 = [13, 11, 6, 17] true_cost4 = 41 testing_suite = [[warehouse1, warehouse2, warehouse3, warehouse4], [dropzone1, dropzone2, dropzone3, dropzone4], [todo1, todo2, todo3, todo4], [true_cost1, true_cost2, true_cost3, true_cost4]] solution_check(testing_suite) #UNCOMMENT THIS LINE TO TEST YOUR CODE #print plan(warehouse1, dropzone1, todo1) #print plan(warehouse2, dropzone2, todo2)
def words(param): result = {} # Deal with multiple spaces proper_sentence = ' '.join(param.split()) # Create a list containing word items proper_words = proper_sentence.split(" ") for my_word in proper_words: if my_word in result: continue try: result[int(my_word)] = proper_words.count(my_word) except: result[my_word] = proper_words.count(my_word) return result
import Board import AIplayer class TicTacToe(): def __init__(self, initial_turn=True): self.board = Board.Board() self.board.reset self.initial_turn = initial_turn self.player_mark, self.ai_mark = None, None self.ai = None def setAI(self, mode, my_mark, opponent_mark): if mode == 'random': self.ai = AIplayer.RandomPlay(self.board, my_mark, opponent_mark) elif mode == 'minmax': self.ai = AIplayer.MinMaxPlay(self.board, my_mark, opponent_mark) else: print "Unknown ai mode is input." exit self.ai_mark = my_mark def setPlayerMark(self, mark): self.player_mark = mark def resetBoard(self): self.board.reset() def getInputFromStdin(self): print "It's your turn, please input the next position. ie 0 0." while True: input = raw_input().split() if len(input) != 2: print "incorrect input, incorrect input size." continue elif not input[0].isdigit() or not input[1].isdigit(): print "incorrect input, not integer input." continue row, col = map(int, input) ret = self.board.checkInput(row, col) if ret[0]: return(row, col) else: print ret[1] continue def play(self): player_turn = self.initial_turn # if true: player, false: ai while True: if player_turn: row, col = self.getInputFromStdin() self.board.setMark(row, col, self.player_mark) else: # ai turn row, col = self.ai.getInput() print row, col, "is input." self.board.setMark(row, col, self.ai_mark) self.board.dump() flg = self.board.checkGoal() if flg == 1: # one of the player win if player_turn: print "You win" else: print "You loose" break elif flg == -1: print "Draw" break player_turn = not player_turn if __name__ == '__main__': game = TicTacToe(True) game.setPlayerMark('o') #game.setAI("random", 'x', 'o') game.setAI("minmax", 'x', 'o') game.play()
while True: print(" ************MENU************ ") print("1.Pixel 1") print("2.Pixel 2") print("3.Pixel 3") print("4.Salir") op=int((input("INGRESE LA OPCION QUE DESEA EJECUTAR:"))) if op==1: print("1.Completa") print("2.En partes") op1 = input("Ingrese la opcion que desea: ") if op1==1: #pega el codigo completo else: #pega elcodigo por partes elif op==2: print("1.Completa") print("2.En partes") op1 = input("Ingrese la opcion que desea: ") if op1 == 1: # pega el codigo completo else: # pega elcodigo por partes elif op==3: print("1.Completa") print("2.En partes") op1 = input("Ingrese la opcion que desea: ") if op1 == 1: # pega el codigo completo else: # pega elcodigo por partes else: break
""" Interpreting Chi^2 Author: Sheila Kannappan excerpted/adapted from CAP REU tutorial September 2016 """ from __future__ import division import numpy as np import matplotlib.pyplot as plt import numpy.random as npr # experiment to illustrate Monte Carlo creation of chi^2 # distributions for two values of N #i=0 #if i == 0: for i in xrange(2): narr=30*(1+9*i) #30 first time, 300 second time chisqs=[] iters=1000 # experiment with rerunning the plots many times # to see how the random variations change the chi^2 # start w/ iters=100 then change iters to 1000 and repeat for j in xrange(iters): # create a data set with random errors whose underlying # functional form is y=1/x xvals = np.zeros(narr) yvals = np.zeros(narr) xvals = np.arange(narr)/(1.+9.*i) + 1. errs=0.1 yvals = 1./xvals + npr.normal(0,errs,narr) # what does npr.normal do? #It adds a certain amount of error to our "measurements" because in the #real world we may not know what that error might be, but we might know #it falls within a certain confidence interval. resids = np.abs(yvals - 1./xvals) # why are we subtracting 1./xvals? # because 1./xvals represents our expected values and the residual is #defined by the [(observed value)-(expected value)]. chisq = np.sum(resids**2 / errs**2) # roughly, how is chisq related to N? #chisq is approximately equal to N, and in this case N is equal to the #number of data points because there are no free parameters. # what if we didn't know the errors and overestimated # them as 0.2 -- how would chi^2 change? #chi^2 would decrease if we increased errs to 0.2 which would make it look #as if the reduced chi^2 had a better fit. chisqs.append(chisq) # building up iters trial values of chi^2 if i==0: redchisqdist1 = np.array(chisqs)/narr # compute array of "reduced chi^2" values found for 1st N # what does "reduced" mean? why are we dividing by narr? #"Reduced" chi^2 is a way of determining if a model is a good fit. #We are dividing by narr because in this model y=1/x has no free parameters, #so N=narr, or the number of data points. if i==1: redchisqdist2 = np.array(chisqs)/narr # same thing for 2nd N plt.figure(2) plt.clf() n1, bins1, patches1 = plt.hist(redchisqdist1,bins=0.05*iters,normed=1,histtype='stepfilled') n2, bins2, patches2 = plt.hist(redchisqdist2,bins=0.05*iters,normed=1,histtype='step') plt.setp(patches1,'facecolor','g','alpha',0.75) plt.xlim(0,2.5) plt.setp(patches2,'hatch','///','alpha',0.75,color='blue') # what good plotting strategies are being used here? #When overplotting the 2nd plot, N=300, the histogram was made such that it is hatched so you can #still see the first, N=30, plot beneath it. They are also labeled well so you can easily distinguish #between which plot represents which set of data. plt.title('comparison of reduced chi-squared distributions') #plt.title('reduced chi-squared distribution') # switch titles above when you add N=300 case plt.text(1.4,1,"N=30",size=11,color='g') plt.text(1.2,3,"N=300",size=11,color='b') # Q: how can we determine the confidence level associated with # a certain deviation of reduced chi^2 from 1? # A: we have to do the integral under the distribution -- # e.g. for 3sigma (99.8%) confidence find x such that # the integral up to x contains 99.8% of the area # how can you approximate this using np.argsort? #This can be approximated by using np.argsort to sort the data such that indices #assigned to each red chi^2 will be listed from least to greatest. Then we use the #998 element from the array inds, that is inds[998] that correspondes to the 99.8% #confidence interval. The output of inds[998] will be the element we have to search #for in redchisqdist1[inds[998]] & redchisqdist2[inds[998]] to obtain the reduced #chi^2 for 99.8% confidence for both N=30 and N=300. # make sure to set iters=1000 for this exercise.... inds=np.argsort(redchisqdist1) print("Reduced chi^2 for 99.8% confidence for N=30:", redchisqdist1[inds[998]]) # fill in to print red. chi^2 for 99.8% conf. for N=30 inds=np.argsort(redchisqdist2) print('Reduced chi^2 for 99.8% confidence for N=300:', redchisqdist2[inds[998]]) # fill in to print red. chi^2 for 99.8% conf. for N=300 # look at the graph and verify your answers make visual sense
import pygame import math amigo = [] # menuLetras q = 0 q == int(1) # cores rosa = (255, 228, 196) azul = (0, 0, 255) verde = (34, 139, 34) preto = (0, 0, 0) branco = (255, 255, 255) vermelho = (255, 0, 0) ouro = (218, 165, 32) magenta = (255, 0, 255) PI = math.pi pygame.init() largura = 640 altura = 480 pos_x = int(largura/2) pos_y = int(altura/2) # Seta o tamanho da janela fundo = pygame.display.set_mode((largura, altura)) # define um título na janela. pygame.display.set_caption("Desenhos geometricos") def menu(): while True: print('''Menu: Tecla ‘q’ para desenhar o primeiro retângulo. Tecla ‘w’ para desenhar o segundo retângulo. Tecla ‘e’ para desenhar a primeira elipse. Tecla ‘r’ para desenhar a segunda elipse. Tecla ‘t’ para desenhar o polígono. Tecla ‘y’ para desenhar o círculo. Tecla ‘u’ para desenhar o arco. Tecla 'x' para sair.''') op = input("Opção selecionada: ") if(op == 'q'): primerioRetangulo() elif(op == 'w'): segundoRetangulo() elif(op == 'e'): primeiraElipse() elif(op == 'r'): segundoElipse() elif(op == 't'): poligono() elif(op == 'y'): circulo() elif(op == 'u'): arco() else: break def primerioRetangulo(): fundo.fill(rosa) pygame.draw.rect(fundo, vermelho, (150, 10, 20, 50)) pygame.display.update() def segundoRetangulo(): fundo.fill(rosa) pygame.draw.rect(fundo, ouro, (150, 10, 20, 50)) pygame.display.update() def primeiraElipse(): fundo.fill(rosa) pygame.draw.ellipse(fundo, vermelho, [300, 10, 50, 20]) pygame.display.update() def segundoElipse(): fundo.fill(rosa) pygame.draw.ellipse(fundo, magenta, [300, 10, 50, 20]) pygame.display.update() def poligono(): fundo.fill(rosa) pygame.draw.polygon(fundo, preto, [[100, 100], [0, 200], [200, 200]], 2) pygame.display.update() def arco(): fundo.fill(rosa) pygame.draw.arc(fundo, vermelho, [250, 75, 150, 125], PI/2, 3*PI/2, 2) pygame.display.update() def circulo(): fundo.fill(rosa) pygame.draw.circle(fundo, azul, [60, 250], 40) pygame.display.update() def main(): menu() main()
import pandas as pd def calcfreq(mylist): freq={} for i,items in enumerate(mylist): freq[(i,items)]=mylist.count(items) for key,value in freq.items(): print(key,":",value) return freq doc1="Cosine similarity is a metric, helpful in determining, how similar the data objects are irrespective of their size." doc2="Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space." doc3="Cosine similarity is a metric used to measure how similar the documents are irrespective of their size." doc=[doc1,doc2,doc3] worddict={} i=1 for ele in doc: words=ele.split(" ") data=calcfreq(words) i=i+1 df=pd.DataFrame(data)
""" 容器序列:list、tuple、collections.deque 扁平序列:str、bytes、bytearray、memoryview、array.array 容器序列和扁平序列的区别? 容器序列可以存放不同类型的数据。即可以存放任意类型对象的引用。 扁平序列只能容纳一种类型。也就是说其存放的是值而不是引用。换句话说扁平序列其实是一段连续的内存空间,由此可见扁平序列其实更加紧凑。但是它里面只能存放诸如字符、字节和数值这种基础类型。 可变序列:列表,字典 不可变序列:元组,字符串 """ def my_map(func,iterables): if hasattr(iterables,'__iter__'): for i in iterables: yield func(i) else: raise TypeError('{} object is not iterable'.format(iterables.__class__.__name__)) import time from functools import wraps def timer(func,*args,**kwargs): def wrapper(*args,**kwargs): start_time = time.time() func(*args,**kwargs) end_time = time.time() print ("运行时间: {}".format(end_time-start_time)) return wrapper
# => SELECTION SORT ALGORITHM FILE def selection_sort(elements, change): for i in range(len(elements)): min_index = i for j in range(i + 1, len(elements)): if elements[min_index].size_Y > elements[j].size_Y: min_index = j elements[i], elements[min_index] = elements[min_index], elements[i] # => UPDATE A WINDOW change(elements[min_index], elements[i]) return True
class CoffeeMachine: def __init__(self, water_: int, milk_: int, coffee_beans_: int, disposable_cups_: int, money_: int, exit_: bool): self.water = water_ self.milk = milk_ self.coffee_beans = coffee_beans_ self.disposable_cups = disposable_cups_ self.money = money_ self.actual_state = 0 # 0 - choosing option, 1 - printing ingredient to add, 2 - adding ingredient # 3 - print with coffee to serve, 4 - serve coffee , 5 - back to options self.added_ingredients = 0 # status in order of added ingredient self.exit = exit_ def check_resources(self, water_c, milk_c, coffee_beans_c, disposable_cups_c) -> bool: """ Checking coffee machine if it has enough resources to server coffee :param water_c: int :param milk_c: int :param coffee_beans_c:int :param disposable_cups_c:int :return: bool """ if self.water < water_c: print("Sorry, not enough water!") return False elif self.milk < milk_c: print("Sorry, not enough milk!") return False elif self.coffee_beans < coffee_beans_c: print("Sorry, not enough coffee beans!") return False elif self.disposable_cups < disposable_cups_c: print("Sorry, not enough disposable cups!") return False else: return True def choose_option(self, option) -> None: """ Main menu """ if option == "buy": self.actual_state = 3 self.serve_coffee(option) elif option == "fill": self.actual_state = 1 self.print_ingredient_to_add() elif option == "take": self.take_money() elif option == "remaining": self.print_eq() elif option == "exit": self.on_off_machine() else: print("I don't know that command") self.print_menu() def fill_coffee_machine(self, option_) -> None: """ Fill coffee machine """ option = int(option_) if self.added_ingredients == 0: self.water += option self.added_ingredients += 1 self.print_ingredient_to_add() elif self.added_ingredients == 1: self.milk += option self.added_ingredients += 1 self.print_ingredient_to_add() elif self.added_ingredients == 2: self.coffee_beans += option self.added_ingredients += 1 self.print_ingredient_to_add() elif self.added_ingredients == 3: self.disposable_cups += option self.added_ingredients = 0 self.print_menu() self.actual_state = 0 else: self.added_ingredients = 0 self.print_menu() self.actual_state = 0 def on_off_machine(self): """ Switching state of the machine """ if not self.exit: self.exit = True else: self.exit = False def operate(self, user_input: str): """ Main operate function changing state of machine, and passing input """ if self.actual_state == 0: self.choose_option(user_input) elif self.actual_state == 1: self.print_ingredient_to_add() elif self.actual_state == 2: self.fill_coffee_machine(user_input) elif self.actual_state == 3 or 4: self.serve_coffee(user_input) else: self.actual_state = 0 @staticmethod def print_choose_coffee(): print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:") def print_eq(self) -> None: print(f"""The coffee machine has: {self.water}, of water {self.milk}, of milk {self.coffee_beans}, of coffee beans {self.disposable_cups}, of disposable cups {self.money}, of money""") self.print_menu() def print_ingredient_to_add(self): if self.added_ingredients == 0: print("Write how many ml of water do you want to add:") elif self.added_ingredients == 1: print("Write how many ml of milk do you want to add:") elif self.added_ingredients == 2: print("Write how many grams of coffee beans do you want to add:") elif self.added_ingredients == 3: print("Write how many disposable cups of coffee do you want to add:") else: print("Unknown error in 'print_ingredient_add'") self.actual_state = 2 @staticmethod def print_menu(): print("Write action (buy, fill, take, remaining, exit):") def serve_coffee(self, coffee_t_) -> None: if self.actual_state == 3: self.print_choose_coffee() self.actual_state = 4 elif self.actual_state == 4: if coffee_t_ == "back": self.actual_state = 0 self.print_menu() else: coffee_t = int(coffee_t_) cups = 1 # temporary if coffee_t == 1: # espresso if self.check_resources(250, 0, 16, cups): print("I have enough resources, making you a coffee!") self.water -= 250 * cups self.coffee_beans -= 16 * cups self.disposable_cups -= 1 self.money += 4 self.print_menu() self.actual_state = 0 else: self.print_menu() self.actual_state = 0 elif coffee_t == 2: # latte if self.check_resources(350, 75, 20, cups): print("I have enough resources, making you a coffee!") self.water -= 350 * cups self.milk -= 75 * cups self.coffee_beans -= 20 * cups self.money += 7 self.disposable_cups -= 1 self.print_menu() self.actual_state = 0 else: self.print_menu() self.actual_state = 0 elif coffee_t == 3: # cappuccino if self.check_resources(200, 100, 12, cups): print("I have enough resources, making you a coffee!") self.water -= 200 * cups self.milk -= 100 * cups self.coffee_beans -= 12 * cups self.money += 6 self.disposable_cups -= 1 self.print_menu() self.actual_state = 0 else: self.print_menu() self.actual_state = 0 else: print("No such coffee") self.print_menu() self.actual_state = 0 def take_money(self): print("I gave you", self.money) self.money = 0 self.print_menu() coffee_m = CoffeeMachine(400, 540, 120, 9, 550, False) print("Write action (buy, fill, take, remaining, exit):") while not coffee_m.exit: u_input = input() coffee_m.operate(u_input)
age = int(input('What is your age?\n')) if age < 18: print('You are still a child!') else: print('You are an adult now!')
print('Let\'s play a game! Try to guess my number...') try: guess = int(input('Enter a number between 0 and 100: ')) except NumberFormatException: print('Uh oh, that\'s not a number.') if not (guess <= 100 and guess >= 0): print('Hey! You\'re cheating! The number must be between 0 and 100.') elif guess < 78: print('Try entering a higher number...') elif guess > 78: print('Try entering a lower number...') else: print('You win!')
for i in range(34): if i % 2 = 0: print(i) else if i % 3 = 3: print(i % 3) else print(3)