text
stringlengths
37
1.41M
#!/usr/bin/env python """ Experiments about occur checking and unification algorithms, useful for haskell, lambda calculus and prolog """ class Subst(object): "Contains a variable and the term you want to substitute" def __init__(self, var, term): self.var = var self.term = term # see how a term could be constructed exactly class Term(object): "A term is a lambda expr and a term or just a term" def __init__(self): pass # redefine some operator to get the substitution working class Var(object): "Variable" pass class Constant(object): "Constant element" pass
import tkinter #import b as b # Описываю какие-то события def handler1(event): print('Hello World! x =', event.x, 'y =', event.y) def handler2(event): exit() # Инициализация root = tkinter.Tk() hello_label = tkinter.Label(root, text='Hello world!', font="Times 40") hello_label.pack() # Привязка обработчиков - к событию и виджету: # виджет.bind(событие, обработчик) bind - привязать hello_label.bind('<Button-1>', handler1) hello_label.bind('<Button-3>', handler2) # Главный проект root.mainloop()
# Import of the required packages import json import urllib from urllib.request import urlopen # This function returns URLs (for the "theMovieDB"-API) for all movie of an user given time span def linksYearCreater(): # "s" is the complete URL to get the 20 most succesful movies of a certan year, without the year s = "https://api.themoviedb.org/3/discover/movie?api_key=0ae744d3523ac83c17788b462e1af745&sort_by=revenue.desc&include_adult=false&include_video=false&page=1&primary_release_year=" linksWithYears =[] startYear = "a" print("We will always collect the 20 most succesful movies of each year.\n") # This while loop gets the start year from the user. The variable startYear is initially set to "a". With a try block, we catch ValueError's (because of the "int"-function, every input which is not an int will generate a Value Error). while startYear == "a": try: startYear = int(input("Please enter the start year:")) except ValueError: print("Please enter an integer") endYear = "a" # It's the same routine, like with the start year. Only that we catch (with an if-clause) the case, that the end year is lower than the start year. while endYear == "a": try: endYear = int(input("Please enter the end year:")) if endYear < startYear: print("The end year has to be lower than the start year. Please try again :)") endYear = "a" except ValueError: print("Please enter an integer") # Now we append all the links (we put together the basic link from "s" and all the years from start to end year) to the list "linksWithYears", which gets returned afterwards while startYear < endYear+1: number = str(startYear) linksWithYears.append(s + number) startYear += 1 return linksWithYears # This function creates the links, for the most succesful movies. It works pretty similar to the linksYearCreater-function. The only main difference is, that the links get put together with the page number # TheMovieDB-API can return always 20 movies on one page. So if we want to get the 20 most succesful movies, we get only page 1. If we want to get the 80 most succesful movies, we get pages 1,2,3 and 4. # Out of simplicity, we decided to don't do anything about the situation, that you can only choose a number dividible by 20. For a project/programm, which is supposed to go public, we would have considered our decision, but this progamm is for research-purposes only. def linksPopularityCreater(): s = "https://api.themoviedb.org/3/discover/movie?api_key=0ae744d3523ac83c17788b462e1af745&language=en-US&sort_by=revenue.desc&include_adult=false&include_video=false&page=" i = 1 notCorrect = True a = 0 out = [] while notCorrect: a = int(input("Please enter a number divisble by 20, which is at least 20:")) notCorrect = False if a < 20 or not(a % 20 == 0): notCorrect = True a /= 20 while i <= a: number = str(i) out.append(s + number) i += 1 return out # This function gets the "TheMovieDB"-ids for movies on API pages. # As parameters you can put in lists, which include links for API pages which, on the other hand, include movie-lists in the JSON-format # The output is a list with all movie ids. def getJSON(links): ids = [] for x in links: with urlopen(x) as url: response = urlopen(x) values = json.load(response) for i in range(0, len(values['results'])): ids.append(values['results'][i]['id']) return ids # This function creates a txt-file, based on a list with API movie ids, with a list of all names with their link to the movieDB def getMovies(ids): # temp is to check, if there are duplicates temp = "" names = open("movieNames.txt", "w") for i in ids: if i == temp: continue temp = i idLink = str(i) link = "https://api.themoviedb.org/3/movie/" + idLink + "?api_key=0ae744d3523ac83c17788b462e1af745" try: with urlopen(link) as url: response = urlopen(link) values = json.load(response) except urllib.error.HTTPError: print("") except urllib.error.URLError: print("") name = values['title'] names.write("{0} --> https://www.themoviedb.org/movie/{1}\n".format(values['title'], idLink)) print("We createt a text file called \"movieNames.txt\" with your chosen movies.") # This function creates 5 csv files (director, screenplay, editor, producer, directirOfPhotography), which include (for each profession) a table with a proportion of gender, divided by release-year # As parameter, the function works only with list which include movie ids, which are sorted uprising by year, and with always 20 movies per year, without one year missing # That's because of the way the MovieDB works. Here again it would be possible to change that, but we decided against it, because it would need way more system-recources and at that point, the only people who are using the programm, can look in the comments. # If we would think about releasing the programm, we definitely would do some changes in this part. def getCrew(ids): # We create all the needed files and allready write the first line of the csv-table director = open("director.csv", "w") director.write("Year, female, male, null") screenplay = open("screenplay.csv", "w") screenplay.write("Year, female, male, null") editor = open("editor.csv", "w") editor.write("Year, female, male, null") producer = open("producer.csv", "w") producer.write("Year, female, male, null") directorOfPhotography = open("directorOfPhotography.csv", "w") directorOfPhotography.write("Year, female, male, null") # We get the API link for the first index of the entered link to get the release year, of the first movie. linkFirstYear = "https://api.themoviedb.org/3/movie/" + str(ids[0]) + "?api_key=0ae744d3523ac83c17788b462e1af745" try: with urlopen(linkFirstYear) as url: response = urlopen(linkFirstYear) valuesFirstYear = json.load(response) except urllib.error.HTTPError: print("") except urllib.error.URLError: print("") # We get the JSON-value which includes the release date, but because it's in the "YYYY-MM-DD"-format, we split the returned string and parse it afterwards to an integer. year = valuesFirstYear["release_date"] year = int(year[0:4]) x = 0 # All these variable are counters for the gender ratio and get added 1, if a crew member, with the specific job and gender gets found. directorW = editorW = producerW = screenplayW = directorOfPhotographyW = 0 directorM = editorM = producerM = screenplayM = directorOfPhotographyM = 0 directorN = editorN = producerN = screenplayN = directorOfPhotographyN = 0 # This for loop goes through all the entered links. Another for loop, goes through the results of every movie. for j in ids: # x is to count. Every time it's dividible by 20, we now we can change the year-variable x += 1 idLink = str(j) # This link is the basic construct for a link, which includes al the credits of a movie link = "https://api.themoviedb.org/3/movie/" + idLink + "/credits?api_key=0ae744d3523ac83c17788b462e1af745" try: with urlopen(link) as url: response = urlopen(link) values = json.load(response) except urllib.error.HTTPError: print("") except urllib.error.URLError: print("") # This for loop goes through the whole crew part of the credits. # It basicaly goes through every job. Every time one of our determined jobs gets found, the int for the found gender gets added 1. for i in range(0, len(values['crew'])): if (values['crew'][i]['job'] == "Director"): if (values['crew'][i]['gender'] == 1): directorW += 1 if (values['crew'][i]['gender'] == 2): directorM += 1 else: directorN += 1 if (values['crew'][i]['job'] == "Writer"): if (values['crew'][i]['gender'] == 1): screenplayW += 1 if (values['crew'][i]['gender'] == 2): screenplayM += 1 else: screenplayN += 1 if (values['crew'][i]['job'] == "Screenplay"): if (values['crew'][i]['gender'] == 1): screenplayW += 1 if (values['crew'][i]['gender'] == 2): screenplayM += 1 else: screenplayN += 1 if (values['crew'][i]['job'] == "Producer"): if (values['crew'][i]['gender'] == 1): producerW += 1 if (values['crew'][i]['gender'] == 2): producerM += 1 else: producerN += 1 if (values['crew'][i]['job'] == "Editor"): if (values['crew'][i]['gender'] == 1): editorW += 1 if (values['crew'][i]['gender'] == 2): editorM += 1 else: editorN += 1 if (values['crew'][i]['job'] == "Director of Photography"): if (values['crew'][i]['gender'] == 1): directorOfPhotographyW += 1 if (values['crew'][i]['gender'] == 2): directorOfPhotographyM += 1 else: directorOfPhotographyN += 1 # when x reaches a number dividible by 20, the results get writen in to the csv-files and the different job-gender-counter get set back to zero. # the year-variable gets added 1 and the for loop goes again. if x % 20 == 0: director.write("\n") director.write("{0}, {1}, {2}, {3}".format(year, directorW, directorM, directorN)) editor.write("\n") editor.write("{0}, {1}, {2}, {3}".format(year, editorW, editorM, editorN)) producer.write("\n") producer.write("{0}, {1}, {2}, {3}".format(year, producerW, producerM, producerN)) screenplay.write("\n") screenplay.write("{0}, {1}, {2}, {3}".format(year, screenplayW, screenplayM, screenplayN)) directorOfPhotography.write("\n") directorOfPhotography.write("{0}, {1}, {2}, {3}".format(year, directorOfPhotographyW, directorOfPhotographyM, directorOfPhotographyN)) directorW = editorW = producerW = screenplayW = directorOfPhotographyW = 0 directorM = editorM = producerM = screenplayM = directorOfPhotographyM = 0 directorN = editorN = producerN = screenplayN = directorOfPhotographyN = 0 year += 1 director.close() editor.close() producer.close() screenplay.close() directorOfPhotography.close() print("The CSV-files were created succesfully.")
import sys class Variable: """docstring for Variable""" def __init__(self,name, datatype='Int', size=4,isArray=False): self.name = name self.datatype = datatype self.isArray = isArray self.size = size class Method: def __init__(self, name, datatype='Int'): self.name = name self.datatype = datatype class Symtab: """docstring for Symtab""" def __init__(self,parent,symtab_type, scope_name): self.variables = [] self.parent = parent self.methods = [] self.symtab_type = symtab_type # symbol table type class or method or let type self.scope_name = scope_name # name of class or method or let id self.lets = [] def enter(self,name,datatype='Int',size=4,isArray=False): if(self.search(name)): sys.exit("Variable %s already present in symbol table"%name) else: newvar = Variable(name,datatype,size,isArray) self.variables.append(newvar) def enter_method(self, name,datatype='Int'): if(self.search_method(name)): sys.exit("Method %s already present in symbol table"%name) else: newmethod = Method(name,datatype) self.methods.append(newmethod) def getVariable(self,name): current_sym_tab = self while current_sym_tab <> None: for variable_entry in current_sym_tab.variables: if(variable_entry.name == name): return variable_entry current_sym_tab = current_sym_tab.parent # sys.exit('Error no entry in Symbol table for : '+name) return None def getMethod(self,name): current_sym_tab = self while current_sym_tab <> None: for method_entry in current_sym_tab.methods: if(method_entry.name == name): return method_entry current_sym_tab = current_sym_tab.parent # sys.exit('Error no entry in Symbol table for : '+name) return None def search(self,name): for variable_entry in self.variables: if(variable_entry.name == name): return True return False def search_method(self, name): for method_entry in self.methods: if(method_entry.name == name): return True return False def getScope(self,name): current_sym_tab = self while current_sym_tab <> None: for variable_entry in current_sym_tab.variables: if(variable_entry.name == name): return current_sym_tab current_sym_tab = current_sym_tab.parent # sys.exit('Error no scope found for %s',name) return None def printsymtab(self): print "Symbol Table : ", self.scope_name if self.parent <> None: print "Parent : ", self.parent.scope_name for v in self.variables: print(v.name, v.datatype, v.size)
__author__ = "Sai Sujith Kammari" ''' CSCI-603: LAB 8 Author1: SAI SUJITH KAMMARI Author2: KEERTHI NAGAPPA PRADHANI Draws the balance with the weights provided. If the torque on the right doesn't match then exits ''' import sys import turtle # global constants for turtle window dimensions WINDOW_WIDTH = 2000 WINDOW_HEIGHT = 2000 class Beam: """ This class creates the beams with hangers and the distance of each hanger """ __slots__ = 'dist', 'hanger', 'beam_hang_index', 'scaling_factor' def __init__(self,beam_details): """ Creates the beam object :param beam_details: the list of hangers and their positions on the beam """ self.dist = [] self.hanger = [] for index in range(len(beam_details)): # Splitting the values to the distances and hangers if index%2 == 0: self.dist.append(int(beam_details[index])) else: if isinstance(beam_details[index], Beam): # Creating a beam self.hanger.append(beam_details[index]) else: # Creating the weight self.hanger.append(Weight(beam_details[index])) if len(self.hanger) != len(self.dist): # Validating the input provided print('Wrong input provided') else: # Validating if the input provided is balanced self.beam_hang_index = self.get_midindex() #Setting the scaling factor for the beam which is used while drawing self.scaling_factor = self.weight() * 10 # Adjusting the scaling factor so that the balance doesn't go out of screen if self.scaling_factor > WINDOW_WIDTH / 2: self.scaling_factor = WINDOW_WIDTH / 4 # Checking if a weight is missing if len([missing_weights for missing_weights in self.hanger if missing_weights.weight() == -1 ]) > 0: # Finding the missing weight self.find_missing_weight() if not self.isbalanced(): # Weights are not balanced print("It is not a balanced weights. Please provide a balance with equal torques") sys.exit(0) def get_total_torque(self): """ Returns the total torque on the beam :return: torque value """ return sum([abs(hang.weight() * dist) for hang, dist in zip(self.hanger[:], self.dist[:])]) def get_midindex(self): """ Returns the index on the hanger which where the hanger is hanging :return: middle index """ return len([left_numbers for left_numbers in self.dist if int(left_numbers) < 0]) def find_missing_weight(self): """ Finding and replacing the value of the empty weight in the balance to balance the weight :return: None """ # Finding the indexof the missing value missing_value_index = 0 for hang in self.hanger: if hang.weight() == -1: break else: missing_value_index += 1 # Finding the missing value total_torque = 0 for index in range(len(self.dist)): total_torque += self.dist[index] * self.hanger[index].weight() total_torque -= self.dist[missing_value_index] * self.hanger[missing_value_index].weight() missing_value = abs(total_torque // self.dist[missing_value_index]) # Replacing the missing value in the balance self.hanger[missing_value_index].set_weight(missing_value) print("Missing weight found and replaced with " + str(missing_value)) def weight(self): """ returns the total weight of the beam :return: total Weight """ return sum([weight.weight() for weight in self.hanger if not isinstance(weight, Beam)]) + \ sum([beam.weight() for beam in self.hanger if isinstance(beam, Beam)]) def isbalanced(self): """ Checks if the beam is balanced or not :return: True if balanced else False """ left_torque = abs(sum([hang.weight() * dist for hang,dist in zip(self.hanger[:self.beam_hang_index],self.dist[:self.beam_hang_index])])) right_torque = abs(sum([hang.weight() * dist for hang,dist in zip(self.hanger[self.beam_hang_index:],self.dist[self.beam_hang_index:])])) if left_torque != right_torque: # Not Balanced return False else: # Balanced return True def turtle_window_init (self,myWindowname): """ Initialize for drawing. :pre: pos (0,0), heading (east), up :post: pos (0,WINDOW_HEIGHT/3), heading (east), up :return: None """ turtle.setworldcoordinates(-WINDOW_WIDTH / 2, -WINDOW_WIDTH / 2, WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2) turtle.up() turtle.left(90) turtle.forward(WINDOW_HEIGHT/3) turtle.right(90) turtle.title(myWindowname) def drawBalance(self, beam, factor, vert_height = WINDOW_HEIGHT/10): """ Draws the Beam :pre: pos (0,0), heading (east), down :post: pos (0,0), heading (east), down :param beam: beam that has to be drawn :param vert_height: length that has to be suspended :return: None """ turtle.right(90) turtle.forward(vert_height) turtle.left(90) for d in range(len(beam.dist)): turtle.forward(factor * int(beam.dist[d])) if isinstance(beam.hanger[d],Beam): self.drawBalance(beam.hanger[d], factor/3) else: self.drawWeight(beam.hanger[d].weight()) for x in range(abs(int(beam.dist[d]))): # Drawing the beam factor indicators turtle.backward(factor * (int(beam.dist[d]) / abs(int(beam.dist[d] )))) turtle.right(90) turtle.forward(10) turtle.backward(10) turtle.left(90) # Returning back turtle.left(90) turtle.forward(vert_height) turtle.right(90) def drawWeight(self,weight, hanger_length = WINDOW_HEIGHT // 100 ): """ Draws the weights :pre: pos (0,0), heading (east), down :post: pos (0,0), heading (east), down :param weight: Weight that has to be written :return: None """ turtle.left(180) turtle.right(90) turtle.backward(hanger_length * 1.5) turtle.up() turtle.backward(hanger_length * 2.5) turtle.write(weight) turtle.forward(hanger_length * 4 ) turtle.right(90) turtle.down() def draw(self): """ Draws the Balance :pre: pos (0,0), heading (east), up :post: pos (0,0), heading (east), up :return: None """ self.turtle_window_init("Balance") turtle.down() self.drawBalance(self, self.scaling_factor ) turtle.up() turtle.mainloop() class Weight: """ Holds the values of the weight """ __slots__ = 'value' def __init__(self,weight): """ Creates the weight object :param weight: value of the weight that is being hanged """ self.value = int(weight) def weight(self): """ Returns the weight of the object :return value: The value of the weight """ return self.value def set_weight(self, weight): """ Sets the value :param weight: weight that has to be set :return: None """ self.value = weight def main(): """ Main Method :return: None """ beams = {} # Reading the file try: with open(input("Please provide the file location which have balance details"), mode='r') as input_file: for line in input_file: command = line.strip().split(' ') beams[command[0]] = command[1:] except: # Handling the wrong file name print("Bad file. Please check the file") sys.exit(1) # Replacing the beam values balance_arguments = ' '.join(beams['B']) while 'B' in balance_arguments: for key in beams.keys(): if key != 'B': balance_arguments = balance_arguments.replace(key, "ss*" +','.join(beams[key])+"*") balance_arguments = balance_arguments.replace('ss*','Beam([') balance_arguments = balance_arguments.replace('*', '])').split(' ') # Building the arguments for the main Balance arguments = [] count = 0 for index in range(len(balance_arguments)): if (balance_arguments[index] != ''): if count % 2 == 0: # adding the distances arguments.append(balance_arguments[index]) else: # creating the objects if 'Beam' in balance_arguments[index]: arguments.append(eval(balance_arguments[index])) else: arguments.append(int(balance_arguments[index])) count += 1 # Creating the main Balance balance = Beam(arguments) # Drawing the main balance balance.draw() if __name__ == '__main__': main()
# -*- coding: utf-8 -*- ''' Created on 2018年1月19日 @author: Jeff Yang ''' # 列表是可以修改的,而元组的值是不可变的 # 元组使用括号()标识 dimensions = (200, 50) print(dimensions[0]) # 访问元组元素和列表相似 print(dimensions[1]) # 单元素元组要加一个逗号避免歧义,如dimensions = (200,) dimensions = (200) print(type(dimensions)) # <class 'int'> # dimensions[0] = 250 修改元组的值会报错 dimensions = (200, 50) print("Original dimensions:") for dimension in dimensions: print(dimension) print("Modified dimensions:") dimensions = (400, 100) # 虽然不能修改元组的元素,但可以给存储元组的变量重新赋值 for dimension in dimensions: print(dimension) my_tuple = (1, [2, 3], 4, 5) my_tuple[1][0] = 3 # 元组本身的指向不可变,若指向list,就不能改成指向其他对象,但list本身是可变的 print(my_tuple) # (1, [3, 3], 4, 5)
# -*- coding: utf-8 -*- ''' Created on 2018年1月18日 @author: Jeff Yang ''' import random for value in range(1, 5): # 表示从1开始,到4位置 # 默认情况下,range()起始值是0,range(5)范围为0到4 print(value) numbers = list(range(1, 6)) # 使用函数list()将range()的结果直接转换为列表 print(numbers) even_numbers = list(range(2, 11, 2)) # 第三个参数2表示间隔,即从2开始,不断加2 print(even_numbers) squares = [] for value in range(1, 11): # 循环创建整数1到10的平方的列表 squares.append(value ** 2) print(squares) digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print(min(digits)) # 找出最小值 print(max(digits)) # 最大值 print(sum(digits)) # 求和 # 列表解析,这里的for没有冒号,for后面还可以嵌套如if判断的语句 squares = [value ** 2 for value in range(1, 11)] print(squares) x = list(range(1, 51)) # x.reverse() # 直接反转列表,没有返回值 y = x[::-1] # 创建反转的列表,赋值给y b = list(reversed(x)) # reversed()函数返回的是一个迭代器而非list,需要使用list函数转换 print(y) z = sorted(x, reverse=True) # 逆序排序列表 a = [random.randint(0, 50) for i in range(50)] # 创建50个随机数的列表
# -*- coding: utf-8 -*- ''' Created on 2018年1月18日 @author: Jeff Yang ''' players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:3]) # 切片,切除索引从0开始,到2为止的元素 print(players[:4]) # 默认从索引0开始,到索引为3的元素 print(players[2:]) # 从索引2开始,到列表最后 print(players[-3:]) # 从倒数第三个元素开始,到末尾 print("\nHere are the first three players on the team:") for player in players[:3]: # 切片也可以遍历 print(player.title()) # 另外,与列表类似,字符串和元组也有切片的操作 string = "test slice" print("\n" + string[5:])
# -*- coding: utf-8 -*- ''' Created on 2018年1月19日 @author: Jeff Yang ''' # python2中用raw_input(),它接收输入转换成string返回,输入数字也会当成string # python2中input()原理上是raw_input()调用eval()函数,输入字符串要用引号引起 # python3中raw_input()和input()进行了整合,仅保留了input()函数,其接收任意输入并返回字符串类型。 # eval():把字符串当成有效的python表达式求值并计算结果 # repr():把变量和表达式转换成字符串表示 # message = input("Tell me something, and I will repeat it back to you:") # print(eval(message)) prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " # message = "" # while message != 'quit': # 只要没有输入quit,循环就会一直继续下去 # message = input(prompt) # if message != 'quit': # 输入quit的话不会输出 # print(message) active = True while active: message = input(prompt) if message == 'quit': active = False # 注意要设定结束标志,避免无限循环 else: print(message)
from multiprocessing import Pool with open("./input.txt", "r") as f: lines = f.readlines() superline = lines[0].strip("\n") uniq_letters = set([x.lower() for x in superline]) print(uniq_letters) def calc_behaviour(line_uniq): line, uniq = line_uniq[0], line_uniq[1] done = False while True: for idx, letter in enumerate(line): if idx == 0: continue if line[idx-1].isupper() and letter.islower(): if line[idx-1].upper() == letter.upper(): line = line[:(idx-1)] + line[(idx+1):] break elif line[idx-1].islower() and letter.isupper(): if line[idx-1].lower() == letter.lower(): line = line[:(idx-1)] + line[(idx+1):] break if idx == (len(line) - 1): done = True if done: break return (len(line), uniq) def main(): results = [] pool = Pool(processes=4) list_of_line = [(superline.replace(uniq, "").replace(uniq.upper(), ""), uniq) for uniq in uniq_letters] print(len(list_of_line)) for i in pool.imap_unordered(calc_behaviour, list_of_line): print(i) main() #I am an idiot #dont ever let me program something important
n = int(input("Enter the length of the sequence: ")) # Do not change this line for i in range(1, n+1): if i == 1: new_number = num_1 = i elif i == 2: new_number = num_2 = i elif i == 3: new_number = num_3 = i else: new_number = num_1 + num_2 + num_3 num_1, num_2, num_3 = num_2, num_3, new_number print(new_number, end=" ")
import re from dataclasses import dataclass # Fermat's little theorem gives a simple inv: # Meaning (a * inv(a, n)) % n = 1 def inv(a, n): return pow(a, n - 2, n) assert (5 * inv(5, 7))%7 == 1 print([inv(i, 11) for i in range(11)]) @dataclass class Shuffle: a: int b: int def forward(self, idx, size): return (self.a * idx + self.b) % size def backward(self, idx, size): # inverting the forward equasion: # x' = (a * x + b) mod n return ((idx - self.b)*inv(self.a, size)) % size def compose(self, other, size): # la * (a * x + b) + lb == la * a * x + la*b + lb # The `% size` doesn't change the result, but keeps the numbers small. return Shuffle((self.a * other.a) % size, (self.a * other.b + self.b) % size) def apply(self, number_of_applications, size): # Now we want to run the linear function composition for each iteration: # la, lb = a, b # a = 1, b = 0 # for i in range(number_of_applications): # a, b = (a * la) % n, (la * b + lb) % n # For a, this is same as computing (a ** M) % n, which is in the computable # realm with fast exponentiation. # For b, this is same as computing ... + a**2 * b + a*b + b # == b * (a**(M-1) + a**(M) + ... + a + 1) == b * (a**M - 1)/(a-1) # That's again computable, but we need the inverse of a-1 mod n. Ma = pow(self.a, number_of_applications, size) Mb = (self.b * (Ma - 1) * inv(self.a - 1, size)) % size return Shuffle(Ma, Mb) @dataclass class Deck: shuffler: Shuffle size: int def __repr__(self): return f"Deck({self.size}, {self.shuffler})" def __getitem__(self, position): return self.at(position) def at(self, position): return self.shuffler.backward(position, self.size) def where(self, card): return self.shuffler.forward(card, self.size) def at_list(self): """ :return: an image of the deck, with cards in their respective positions """ return [self.at(i) for i in range(self.size)] def at_list2(self): """ Same semantic as at_list() but calculated with forward shuffler's function at_list2() should always == at_list() and is used to validate forward and backward (inverse) function """ result = list([0 for i in range(self.size)]) for i in range(self.size): result[self.where(i)] = i return result def where_list(self): """ :return: an array where each card ends up """ return [self.where(i) for i in range(self.size)] def debug(self): print(f"{self} => {self.at_list()}") return self @classmethod def new_deck(cls, size): return cls(identity_shuffle(), size) @staticmethod def parse_shuffler(line): line = line.strip() cut_n_match = re.compile('cut (.+)').match(line) deal_with_incr_match = re.compile('deal with increment (.+)').match(line) if line == 'deal into new stack': return new_stack_shuffle() elif cut_n_match: return cut_n_cards_shuffle(int(cut_n_match.group(1))) elif deal_with_incr_match: return with_n_increments_shuffle(int(deal_with_incr_match.group(1))) else: assert False, "Could not parse line" def shuffle(self, line): new_shuffle = Deck.parse_shuffler(line) combined = new_shuffle.compose(self.shuffler, self.size) return Deck(combined, self.size) def reshuffle(self, number_of_applications): return Deck(self.shuffler.apply(number_of_applications, self.size), self.size) def identity_shuffle(): return Shuffle(1, 0) def new_stack_shuffle(): return Shuffle(-1, -1) def cut_n_cards_shuffle(n): return Shuffle(1, -n) def with_n_increments_shuffle(n): return Shuffle(n, 0) # IMPORTANT! Need to use a prime size for the deck, otherwise the inverse transform does not work deck = Deck.new_deck(11) assert deck[0] == 0 assert deck[9] == 9 assert deck.where(0) == 0 assert deck.where(9) == 9 deck = Deck.new_deck(11).shuffle('deal into new stack') print(deck) assert deck.at_list() == [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] assert deck.at_list2() == [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] assert deck.where_list() == [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] deck = Deck.new_deck(11).shuffle('cut 3') print(deck) assert deck.at_list() == [3, 4, 5, 6, 7, 8, 9, 10, 0, 1, 2] assert deck.at_list2() == [3, 4, 5, 6, 7, 8, 9, 10, 0, 1, 2] assert deck.where_list() == [8, 9, 10, 0, 1, 2, 3, 4, 5, 6, 7] deck = Deck.new_deck(11).shuffle('deal with increment 3') print(deck) assert deck.at_list() == [0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7] assert deck.at_list2() == [0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7] assert deck.where_list() == [0, 3, 6, 9, 1, 4, 7, 10, 2, 5, 8] deck = ( Deck.new_deck(11) .shuffle('deal with increment 7') .debug() .shuffle('deal into new stack') .debug() .shuffle('deal into new stack') .debug() ) assert deck.at_list() == [0, 8, 5, 2, 10, 7, 4, 1, 9, 6, 3] deck = ( deck .shuffle('cut 6') .debug() .shuffle('deal with increment 7') .debug() .shuffle('deal into new stack') .debug() ) assert deck.at_list() == [6, 8, 10, 1, 3, 5, 7, 9, 0, 2, 4] def part1(): lines = [line.strip() for line in open("day22/input1.txt").read().splitlines() if len(line)] deck = Deck.new_deck(10007) for line in lines: deck = deck.shuffle(line) return deck deck = part1() assert deck.where(2019) == 4775 assert deck.at(4775) == 2019 def part2(deck_size, number_of_applications): lines = [line.strip() for line in open("day22/input1.txt").read().splitlines() if len(line)] deck = Deck.new_deck(deck_size) for line in lines: deck = deck.shuffle(line) deck = deck.reshuffle(number_of_applications) return deck DECK_SIZE = 119315717514047 NUMBER_OF_INTERATIONS = 101741582076661 deck = part2(DECK_SIZE, NUMBER_OF_INTERATIONS) print(f"At position 2020 there will be {deck.at(2020)} card") # 37889219674304
def fahrenheit_convert(C): fahrenheit = int(C) * 9/5 + 32 return str(fahrenheit) + 'F' print(fahrenheit_convert(30)) def trapezoid_area(base_up, base_down, height): return 1/2 * (base_down + base_up) * height print(trapezoid_area(1,2,3)) print(trapezoid_area(height=3,base_up=1,base_down=2))
import pandas as pd # Read the csv df = pd.read_csv('auto-mpg.txt', delim_whitespace=True, header=None) columns = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'model year', 'origin', 'car name'] df.columns = columns def normalise(val): f_val = float(val) return 1/f_val for col in columns: if col != 'car name': df[col] = df[col].apply(normalise) # Drop the irrelevant column df = df.drop('car name', axis=1) # Save the dataframe to a file df.to_csv('norm_auto_mpg.csv', sep=',', index=False)
class Bot: def __init__(self, pieces, colour): self.colour = colour self.pieces = pieces def calculate_trade(self, mypiece, otherpiece): return otherpiece.value - mypiece.value # sort_list_of_pieces sorts list of potential pieces can be captured def sort_list_of_pieces(self, losing_pieces, losing_pieces_value): list_of_values = [] sorted_list = [] for tuples in losing_pieces: list_of_values.append(tuples[1]) list_of_values.sort() for tuples in losing_pieces: if tuples[1] == list_of_values[0]: list_of_values.pop(0) sorted_list.append(tuples) return sorted_list def __str__(self): result = f"I am a bot, my colour is {self.colour} and my pieces are:\n" for piece in self.pieces: result += f"{piece}\n" return result
import pygame import random pygame.init() # Colors white = (255, 255, 255); red = (255, 0, 0); black = (0, 0, 0); green=(123,43,43); Font=pygame.font.SysFont('Purisa', 30, bold=True, italic=False) Font1=pygame.font.SysFont('DejaVu Sans', 40, bold=True, italic=False) #text display # def screen_text(text,color,x,y): # Creating window screen_width = 900 screen_height = 600 gameWindow = pygame.display.set_mode((screen_width, screen_height)) # Game Title pygame.display.set_caption("Game of Snake"); pygame.display.update(); # Game specific variables clock = pygame.time.Clock(); def snake_plot(lst): for x,y in lst: pygame.draw.rect(gameWindow, black, [x, y, 25, 25]); def gameloop(): exit_game = False; game_over = False; snake_x = 45 ; snake_y = 55; velocity_x = 0; velocity_y = 0; lst=[]; for i in range(50,76,5): lst.append([i,55]); snake_length=1; food_x = random.randint(20, screen_width//2); food_y = random.randint(20, screen_height//2); score = 0; init_velocity = 5; snake_size = 25; fps = 30; while not exit_game: if game_over: gameWindow.fill(white); screen_text=Font1.render("Your Game is Over",True,green); gameWindow.blit(screen_text,[200,250]); screen_text1=Font1.render("Press Enter To Play Again",True,green); gameWindow.blit(screen_text1,[160,300]); for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game = True if event.type==pygame.KEYDOWN: if event.key==pygame.K_RETURN: gameloop(); else: for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: velocity_x = init_velocity velocity_y = 0 if event.key == pygame.K_LEFT: velocity_x = - init_velocity velocity_y = 0 if event.key == pygame.K_UP: velocity_y = - init_velocity velocity_x = 0 if event.key == pygame.K_DOWN: velocity_y = init_velocity velocity_x = 0 if event.key == pygame.K_q: score*=score; snake_x+= velocity_x snake_y+= velocity_y if abs(snake_x - food_x)<6 and abs(snake_y - food_y)<6: score +=1 # print("Score: ", score * 10) food_x = random.randint(20, screen_width // 2) food_y = random.randint(20, screen_height // 2) snake_length+=5; gameWindow.fill(white) screen_text=Font.render("SCORE: "+str(score),True,green); gameWindow.blit(screen_text,[10,10]); pygame.draw.rect(gameWindow, red, [food_x, food_y, snake_size, snake_size]); head=[]; print(snake_x,snake_y); # head.append(snake_x); # head.append(snake_y); lst.append([snake_x,snake_y]); if len(lst)>snake_length: del lst[0] print(lst); snake_plot(lst); for i in range(len(lst)): for j in range(i+1,len(lst)): if(lst[i][0]==lst[j][0] and lst[i][1]==lst[j][1]): game_over=True; pygame.display.update(); clock.tick(fps) pygame.quit() quit() gameloop();
#!/usr/bin/python #CS 68, Bioinformatics: Lab 4 #By Elana Bogdan and Emily Dolson import pygraphviz as pgv import sys, os, copy def main(): #Make sure command-line arguments are valid if len(sys.argv) < 2: print "Usage: NJTree.py distances" exit() if not os.path.exists(sys.argv[1]): print "Invalid distances file entered" exit() #Parse input and run algorithm distances = readDistances(sys.argv[1]) tree = neighborJoining(distances) #Output results printGraph(tree, "tree.png") printTree(tree) def printTree(tree): """ Prints the distances between all connected nodes in the given tree. """ keys = tree.keys() keys.sort() #print in alphabetical order for key in keys: #each value dictionary only has one entry, so this works print key, tree[key].keys()[0], tree[key].values()[0] def printGraph(tree, filename): """ Generates a png image of the inputted tree. Inputs: tree - a dictionary of dictionaries in which the value of the second key is the distance between the first key and the second key. filename - the name of the file in which to save the image. Returns nothing """ G = pgv.AGraph() #Constructs a graph object for key in tree.keys(): G.add_node(key) for subkey in tree[key].keys(): G.add_node(subkey) G.add_edge(key,subkey,label=str(tree[key][subkey]),\ len=max(1, tree[key][subkey])) #length can't be less than 1, so that labels are readable G.draw(filename,prog="neato") def neighborJoining(distances): """ Peforms the neigbor joining algorithm on the given distance matrix. Inputs: distances - a dictionary of dictionaries in which the value of the second key is the distance between the first key and the second key. Returns: a dictionary of dictionaries representing the tree generated by the algorithm. The keys for the first dictionary are the names of child nodes and their values are dictionaries representing their parent. The values of parent dictionaries are the distances between the child and parent. """ tree = {} while(len(distances.keys()) > 2): r = calcRs(distances) M = makeMMatrix(distances, r) smallest = 10000 smallestKey = ("","") #Find nearest neighbors for key in M.keys(): for subkey in M[key].keys(): if M[key][subkey] < smallest: smallest = M[key][subkey] smallestKey = (key, subkey) #Add new node and update distances to rest of tree newname = smallestKey[0] + "-" + smallestKey[1] distances[newname] = {} tree[smallestKey[0]] = {} tree[smallestKey[1]] = {} dij = distances[smallestKey[0]][smallestKey[1]] for key in M.keys(): if key in smallestKey: continue distances[newname][key] = .5*(distances[smallestKey[0]][key] \ + distances[smallestKey[1]][key] - dij) distances[key][newname] = distances[newname][key] #Update distances to parents of node dik = (dij + r[smallestKey[0]] - r[smallestKey[1]])/2 tree[smallestKey[0]][newname] = dik tree[smallestKey[1]][newname] = dij-dik detachDict(distances, smallestKey[0], smallestKey[1]) #Connect final two nodes tree[distances.keys()[0]] = {} tree[distances.keys()[0]][distances[distances.keys()[0]].keys()[0]] =\ distances[distances.keys()[0]][distances[distances.keys()[0]].keys()[0]] return tree def detachDict(dict, key1, key2): """ Remove key1 and key2 from dict. Inputs: dict - a dictionary, key1 and key2 - keys in the dictionary to be removed Returns: nothing """ for key in dict.keys(): if key == key1 or key == key2: del dict[key] else: for subkey in dict[key].keys(): if subkey == key1 or subkey == key2: del dict[key][subkey] def calcRs(distances): """ Calculates the r values for the neighbor-joining algorithm. Input: distances - a dictionary of dictionaries in which the value of the second key is the distance between the first key and the second key. Returns: a dictionary containing the r values for each of the keys in the distances dictionary. """ r = {} for key in distances.keys(): summedDistances = 0 for subkey in distances[key].keys(): summedDistances += distances[key][subkey] r[key] = summedDistances/(len(distances.keys())-2) return r def makeMMatrix(distances, r): """ Calculates M, the matrix of adjusted distances for the neighbor-joining algorithm. Input: distances - a dictionary of dictionaries in which the value of the second key is the distance between the first key and the second key. r - a dictionary containing the r values for each of the keys in the distances dictionary. Returns: the M matrix """ M = copy.deepcopy(distances) for key in M.keys(): for subkey in M[key].keys(): M[key][subkey] -= (r[key] + r[subkey]) return M def readDistances(fileName): """ Reads a file containing distances between groups. Expected format for lines in the file is: group1name group2name distance Input: filename - the name of the file containing distances Returns: a dictionary of dictionaries in which the value of the second key is the distance between the first key and the second key. """ infile = open(fileName, "r") distances = {} for line in infile: line = [i.strip() for i in line.split()] if not distances.has_key(line[0]): distances[line[0]] = {} distances[line[0]][line[1]] = float(line[2]) if not distances.has_key(line[1]): distances[line[1]] = {} distances[line[1]][line[0]] = float(line[2]) infile.close() return distances if __name__ == "__main__": main()
#!/usr/bin/env python ''' Davis-Putnam-LL SAT solver in plain format as specified by the assignment. For a version with metrics/logging, check SAT_for_analysis.py. Implemented by Kim de Bie ''' import sys import random from collections import Counter from itertools import chain import csv heuristic = sys.argv[1] def main(): # read puzzle from command line puzzle = sys.argv[2] # save the file as ruleset ruleset = read_DIMACS(puzzle) # remove tautologies (this only has to be done once) ruleset = check_tautologies(ruleset) # call into algorithm solution = DP_algorithm(ruleset, []) # test whether the algorithm has returned a solution if solution: print('Success!') with open(puzzle + '.out', 'w') as outfile: for literal in solution: outfile.write(str(literal) + ' 0\n') else: print('This problem is unsatisfiable.') with open(puzzle + '.out', 'w') as outfile: outfile.write("") def DP_algorithm(ruleset, assigned_literals): '''The DPLL algorithm. It consists of a simplifcation stage and a stage in which literals are assigned according to a heuristic. If the ruleset is not satisfied, the algorithm recursively calls itself.''' # first run the simplifcation rules ruleset, pure_assigned = check_pure_literals(ruleset) ruleset, unit_assigned = check_unit_clauses(ruleset) assigned_literals = assigned_literals + pure_assigned + unit_assigned # if we have received a -1, we have failed if ruleset == -1: return [] # if the ruleset is empty, we have found a solution if len(ruleset) == 0: return assigned_literals # we have not yet found a solution, so we assign a new literal # by the determined method and run the algorithm with it if heuristic == "JW": new_literal = assign_new_literal_JW(ruleset) elif heuristic == "JWTS": new_literal = assign_new_literal_JWTS(ruleset) elif heuristic == "nishio": new_literal = assign_new_literal_nishio(ruleset) elif heuristic == "MOMS": new_literal = assign_new_literal_MOMs(ruleset) else: new_literal = assign_new_literal_random(ruleset) # recursively call into the algorithm with the new literal assigned solution = DP_algorithm(update_ruleset(ruleset, new_literal), assigned_literals + [new_literal]) # if we fail to find a solution, we try again with the negated literal if not solution: solution = DP_algorithm(update_ruleset(ruleset, -new_literal), assigned_literals + [-new_literal]) return solution def update_ruleset(ruleset, literal): '''Updating the ruleset: remove clauses that contain the literal, and remove the negation of the literal from the clauses.''' updated_ruleset = [] for clause in ruleset: # a clause that contains the literal can now be removed if literal in clause: continue # a clause that contains the negated literal is updated if -literal in clause: clause = set(lit for lit in clause if lit != -literal) # if we have an empty clause, we have failed if len(clause) == 0: return -1 updated_ruleset.append(clause) return updated_ruleset def check_pure_literals(ruleset): '''Check for pure literals and return them as a list, plus updated ruleset.''' # extracting all literals present all_literals = set(chain.from_iterable(ruleset)) # storing pure literals pure_literals = [] # a literal is pure if its negative does not occur for literal in all_literals: if -literal not in all_literals: pure_literals.append(literal) # update the ruleset: all clauses containing pure literals are now # satisfied, so they can be removed for literal in pure_literals: ruleset = update_ruleset(ruleset, literal) return ruleset, pure_literals def check_unit_clauses(ruleset): '''Checking for unit clauses and return them as a list, plus updated ruleset.''' assigned_literals = [] # select all unit clauses: those with length 1 unit_clauses = [clause for clause in ruleset if len(clause) == 1] while len(unit_clauses) > 0: # select the first unit clause that is still available unit_clause1 = unit_clauses[0] # awkwardly select the (only) element from the set for unit in unit_clause1: unit_clause = unit # update the ruleset: remove the unit clauses, and their negated # literals from within other clauses ruleset = update_ruleset(ruleset, unit_clause) assigned_literals.append(unit_clause) # if instead of a ruleset we received -1, we have failed (empty clause) if ruleset == -1: return -1, [] # if the returned ruleset is empty, we have succeeded (so return it) if len(ruleset) == 0: return ruleset, assigned_literals # update the unit clauses unit_clauses = [clause for clause in ruleset if len(clause) == 1] return ruleset, assigned_literals def check_tautologies(ruleset): '''Check for tautologies. If any, the clause may be removed.''' ruleset = [clause for clause in ruleset if not has_tautology(clause)] return ruleset def has_tautology(clause): '''Checks if a clause has a tautology: a literal and its negated form both occur.''' for literal in clause: if -literal in clause: return True else: return False def assign_new_literal_random(ruleset): '''Randomly select a new literal to be assigned.''' all_literals = list(chain.from_iterable(ruleset)) return random.choice(all_literals) def assign_new_literal_MOMs(ruleset): '''Select a new literal to be assigned based on the MOMs heuristic.''' # determine minimum clause size minsize = min([len(clause) for clause in ruleset]) # selecting the clauses with minimum size rules_selection = [clause for clause in ruleset if len(clause) == minsize] literal_counts = Counter() for clause in rules_selection: for literal in clause: literal_counts[literal] += 1 # select the literal with the highest occurrence count in the shortest clauses selected_lit = max(literal_counts, key=lambda key: literal_counts[key]) return selected_lit def assign_new_literal_JW(ruleset): '''Select a new literal to be assigned based on the Jeroslow-Wang 1-sided heuristic.''' literal_counts = Counter() for clause in ruleset: for literal in clause: # the added value for a literal is weighted by the length of its clause addition = 2 ** -len(clause) literal_counts[literal] += addition # getting the literal with the highest summed-up value selected_lit = max(literal_counts, key=lambda key: literal_counts[key]) return selected_lit def assign_new_literal_JWTS(ruleset): '''Select a new literal to be assigned based on the Jeroslow-Wang 2-sided heuristic.''' literal_counts = Counter() abs_counts = Counter() for clause in ruleset: for literal in clause: # the added value for a literal is weighted by the length of its clause addition = 2 ** -len(clause) abs_counts[abs(literal)] += addition literal_counts[literal] += addition # getting the literal with the highest summed-up value lit = max(abs_counts, key=lambda key: abs_counts[key]) # now extract the polarity that has the heighest weight selected_lit = lit if literal_counts[lit] > literal_counts[-lit] else -lit return selected_lit def assign_new_literal_nishio(ruleset): '''Returns the literal for which there are the fewest options left. This is equivalent to the positive literal that has the fewest negative constraints.''' literal_counts = Counter() for clause in ruleset: for lit in clause: # count only negative occurrences if lit < 0: literal_counts[lit] += 1 selected_lit = min(literal_counts, key=lambda key: literal_counts[key]) # return the negation of the selected literal, so the positive version! return -selected_lit def read_DIMACS(filename): '''Read in the DIMACS file format to list of lists.''' DIMACS = [] with open(filename) as file: data = file.readlines() for line in data: if line[0].isdigit() or line[0] == '-': line = set(int(x) for x in line[:-2].split()) DIMACS.append(line) return DIMACS if __name__ == '__main__': main()
#!/usr/bin/python3 import sys def nextFootprint(footprints, step): # Our current location is the last entry in the list of footprints. here = footprints[-1].split(',') # print('Next step: ' + str(step) + ' from ' + str(here)) # Split here into x and y coordinates x = int(here[0]) y = int(here[1]) # Split step into direction and distance direction = str(step[:1]) distance = int(step[1:]) # Record steps by direction for n in range(distance): if direction == 'D': y -= 1 if direction == 'L': x -= 1 if direction == 'R': x += 1 if direction == 'U': y += 1 footprints.append(str(x) + ',' + str(y)) return footprints def readInputs(filename): paths = [] with open(filename) as file: for line in file: subset = line.replace('\n','').split(',') paths.append(subset) file.closed return paths def takeFootprints(steps): footprints = [] footprints.append('0,0') for step in steps: footprints = nextFootprint(footprints, step) # print(str(footprints)) return footprints if __name__ == "__main__": print('Reading inputs...') paths = readInputs(sys.argv[1]) print('') print('Wire paths:') print(str(paths)) print('') print('Logging footprints') footprints = [takeFootprints(path) for path in paths] print('') print('Comparing footprints') # print(str(footprints)) pathA = set(footprints[0]) pathB = set(footprints[1]) pathsMeet = pathA & pathB pathsMeet.remove('0,0') # Don't consider the shared origin print('') print('Measuring the Manhattan distance to each crossing') winner = '' winnerDistance = 9999999 print(str(pathsMeet)) for intersect in pathsMeet: test = intersect.split(',') distance = abs(int(test[0])) + abs(int(test[1])) print('Intersection ' + str(intersect) + ' at ' + str(test[0]) + ',' + str(test[1]) + ' = ' + str(distance)) if distance < winnerDistance: print('New closest intersection!') winnerDistance = distance winner = test print(str(winner) + ' at distance ' + str(winnerDistance)) print('') print('Measuring fewest steps to an intersection') winner = '' winnerDistance = len(footprints[0]) + len(footprints[1]) for intersect in pathsMeet: stepsA = footprints[0].index(intersect) stepsB = footprints[1].index(intersect) distance = stepsA + stepsB if distance < winnerDistance: print('New fewest steps!') winnerDistance = distance winner = intersect print(str(winner) + ' after ' + str(winnerDistance) + ' combined steps') print('')
#02-011.py def power(base, n): return (base) ** n def power_base(base): def power_without_name(n): return power(base, n) return power_without_name power_2 = power_base(2) power_3 = power_base(3) print(type(power_2), type(power_3)) print(id(power_2), id(power_3)) #print(id(power_2), id(power_3)) print(power_2(10)) print(power_3(3))
#04-002.py a = (1, 2, 'go', 4, 5, 6, 7, 8, 9, 10) print(type(a), a) print(type(a[0]), a[0]) print(type(a[2]), a[2]) b = a[2:5] print(type(b), b) print(a[3:]) print(a[:5]) print(a[::3]) print(a[1:-2]) print(a[-4:-1]) a = [1, 2, 'go', 4, 5, 6, 7, 8, 9, 10] b = a[2:5] b[1] = 'go' print(type(b), b) print(a) a = [1, 2, [10, 20, 30], 4, 5, 6, 7, 8, 9, 10] b = a[2:5] print(type(b), b) print(type(b[0]), b[0]) b[0][0] = 100 print(a)
#03-012.py for i in range(10): if not (i % 3) or not (i % 2) : continue for j in range(10): if i == j : break print(i, j) def func() : for i in range(10): for j in range(10): if (i+2) == j : return print(i, j) print('---------------') func()
#02-022.py value = 3 def add_num(value, num=1): value += num print(value) return value value = add_num(value) print(value) a = [1, 2, 3, 4] print(a)
#04-039.py a = [x*2 for x in range(1, 6)] #iterable g = (x*2 for x in range(1, 6)) #iterator print(a) print(g) for i in range(5) : print(a[i], end=' ') for i in range(5) : print(g[i], end=' ') print() print (next(a)) print (next(g)) c = iter(a) print (next(c))
#06-002.py import re def check(pw): if len(pw) < 8: return False bs = ( r'[0-9]+', r'[A-Z]+', r'[~!@#$%^&*]+') for x in bs: if re.search(x, pw) == None : return "NO" return "YES" print(check(input()))
class WhatClass(object): def __new__(cls, **pVK): if len(pVK) > 3 : return None for x in pVK: if x not in ('a', 'b', 'c') : return None return super().__new__(cls) def __init__(self, a=None, b=None, c=None): self.a = a self.b = b self.c = c def __str__(self): return f'a = {self.a}, b = {self.b}, c = {self.c}' w = WhatClass() print(w) w = WhatClass(a=10, x=20) print(w) w = WhatClass(b=10, a=5) print(w) w = WhatClass(c=10, a=5, b=20) print(w) w = WhatClass(10, 20) print(w)
from node import Node # print ('hello world') storedWords= open('words.txt','r') # print(storedWords) storedWords = storedWords.read().splitlines() storedWords = [item.lower() for item in storedWords] # print(storedWords) print (ord(storedWords[0])%26) root = Node(None) node = Node(1) node.children[5] = Node(5) print('') def add_val(val, node): print('val: '+str(val)+' node cargo: '+str(node.cargo)) if len(val) > 1: node.children[ord(val[0])%26] = Node(None) print('children: '+ str(node.children[ord(val[0])%26])) add_val(val[1:],node.children[ord(val[0])%26]) elif len(val) == 1: node.isWord = True if val[0] == node.cargo: # print('repeated node', node) return node else: node.cargo = val[0] # print('created node', node) return node def is_word(word, node) -> bool: if len(word)>1: # node.children[ord(word[0])%26] = Node(None) if node.children[ord(word[0])%26] != None: is_word(word[1:],node.children[ord(word[0])%26]) else: return False elif len(word)==1: if node.is_word == True: return True else: return False for word in storedWords: root = add_val(word,root) print('Done with tree building') testWord = 'aa' print('Is '+testWord+' a word?: ') # print(is_word(testWord, root)) # def printTree(node, word): # if node.children == [None]*26: # print(node.cargo) # else: # for nodes in node.children: # if nodes != None: # printTree(nodes,word+node.cargo) # printTree(root," ")
import random userGuess = 0 counter = 0 a = random.randint(1, 9) while userGuess != a: userGuess = input("What's your guess: ") if userGuess == "exit": break userGuess = int(userGuess) counter = counter + 1 if userGuess < a: print("Too low") elif userGuess > a: print("Too high") else: print("You guessed it correctly") print("It took you:", counter, "tries")
game = True while game: player = input("Write rock, paper, scissors: ") player2 = "rock" tie = False if player == player2: print("Tie") tie = True elif player == "rock" or player == "Rock": if player2 == "paper" or player2 == "Paper": print("You lose") else: print("You win") elif player == "paper" or player == "Paper": if player2 == "scissors" or player2 == "Scissors": print("You lose") else: print("You win") elif player == "scissors" or player == "Scissors": if player2 == "rock" or player2 == "Rock": print("You lose") else: print("You win") else: print("Somethings wrong. Check your spelling") tie = True if not tie: game = False
'''#1 def del_list(list): del list[0] letter = ['a', 'b', 'c'] print 'before_list' print letter del_list(letter) print letter #2 def dict_loop(dict): for name in dict: print name, dict[name] sunghwan_info = {'name':'sunghwan', 'age':20} dict_loop(sunghwan_info) ''' #exercise 1 data = {'minsu':43, 'jisu':33, 'john':21, 'david':33, 'hary':36, 'messi':33, 'ronaldo':27} def classifyAge(value): age_str = '%d0s'%(value/10) return age_str def makeDict(makedDict): makeDict = {} for key in makedDict.keys(): ages = classifyAge(makedDict[key]) if makeDict.has_key(ages): makeDict[ages].append(key) else: makeDict[ages] = [key] return makeDict print makeDict(data)
__author__ = '3tral' def reverorder(): st = raw_input("please input a string you want to reverse:\n") result = st.split() ab = st.split()[::-1] return ab print reverorder() #but my result is a list format, not a string format. it's not big deal, but i care. #so it can be change like the answer: # return ' '.join(ab) # clean answer: def reverseWord(w): return ' '.join(w.split()[::-1]) #another answer: def reverse_v1(x): y = x.split() result = [] for word in y: result.insert(0,word) #always insert the words at list[0] return " ".join(result) def reverse_v4(x): y = x.split() y.reverse() #python already builtin the function return " ".join(y) #https://www.practicepython.org/exercise/2014/05/21/15-reverse-word-order.html
__author__ = '3tral' import random l1 = random.sample(range(1,1000), random.randint(10,20)) print(l1) l2 = [1,2,3,4,5,6,7] i = input("input a number:\n") print('ha') if i not in l1: print('bingo') else: print('cao') if i in l2: print('ainiyo') else: print('qunima')
__author__ = '3tral' with open('file_to_write.txt', 'w') as open_file: open_file.write('A string is your mom') open_file.write("\nhow's your single day?") open_file = open('s2ndfile.txt','w') open_file.write('laozi shi dier pa') open_file.close() #reading file official web https://docs.python.org/3.3/tutorial/inputoutput.html#reading-and-writing-files #https://www.practicepython.org/exercise/2014/11/30/21-write-to-a-file.html
# Mikael Hinton # Project 7 # iRand from Project 5 # InsertionSort from Project 6 https://www.geeksforgeeks.org/insertion-sort/ # BinarySearch https://stackoverflow.com/questions/38346013/binary-search-in-a-python-list # irand is a function given to the students that generates a list of length # is the random selection of the integers from 0 to 1-m without replacement def irand(n,m): # generate an array of length n made up of random integers import random # between 0 and m without replacement b = list(range(n)) b = random.sample(range(m), n) return b A = irand(100, 200) def insertionSort(arr): for i in range(1, len(arr)): k =arr[i] j = i -1 while j >=0 and k < arr[j]: arr[j+1] = arr[j] j -= 1 arr[j+1] = k insertionSort(A) print("InsertionSort ==", A) # if the number if found then then it prints out the number and position # if the number if not found and the f is less than or equal to the length of the list then if keeps searching and either incrementing the # midpoint up or down by 1 if the number is more or less than the midpoint until its either found or it runs out of number and then # will print that the number is not in the sequence def binarySearch(list, number): f = 0 l = len(list)-1 found = False while f<=l and not found: pos = 0 midpoint = (f + l)//2 if list[midpoint] == number: pos = midpoint found = True print( number, "is in position", pos) else: if number < list[midpoint]: l = midpoint-1 else: f = midpoint+1 if found == False: print(number, "is not in the sequence") num = input("What number would you like to search for?\n") convertedNum = int(num) print("You have chosen to search for: ", convertedNum) binarySearch(A, convertedNum)
import unittest from src.card import Card from src.card_game import CardGame class TestCardGame(unittest.TestCase): def setUp(self): self.card_game = CardGame() card_1 = Card("clubs", 2) card_2 = Card("diamonds", 1) card_3 = Card("spades", 5) card_4 = Card("hearts", 8) self.card_set = [card_1, card_2, card_3, card_4] def test_check_for_ace_true(self): self.assertEqual(True, self.card_game.check_for_ace(self.card_set[1])) def test_check_for_ace_false(self): self.assertEqual(False, self.card_game.check_for_ace(self.card_set[2])) def test_highest_card(self): first_card = self.card_set[0] second_card = self.card_set[1] self.assertEqual(second_card, self.card_game.highest_card(first_card, second_card)) def test_cards_total(self): self.assertEqual('You have a total of 16', self.card_game.cards_total(self.card_set))
# Import the OS module: This allows us to create file paths across operating systems import os # Module for opening & reading CSV files import csv #Determine working directory csvpath=os.path.join(r"C:\Users\eliza\Desktop\Data Analytics\Git Hub Repositories\03-Python-Challenge\PyPoll\Resources\election_data.csv") with open(csvpath, newline='') as csvfile: # Tell Python how to read the info from the file csvreader = csv.reader(csvfile, delimiter=',') print(csvreader) csv_header = next(csvreader) # Create lists to store data votes = [] county = [] candidates = [] khan = [] correy = [] li = [] otooley = [] # Determine votes, counties & candidates in the data set: for row in csvreader: votes.append(int(row[0])) county.append(row[1]) candidates.append(row[2]) # Find the total votes cast: total_votes = (len(votes)) # Determine the votes per candidate: for candidate in candidates: if candidate == "Khan": khan.append(candidates) khan_votes = len(khan) elif candidate == "Correy": correy.append(candidates) correy_votes = len(correy) elif candidate == "Li": li.append(candidates) li_votes = len(li) else: otooley.append(candidates) otooley_votes = len(otooley) # Determine the percentage of votes each candidate won khan_percent = round(((khan_votes / total_votes) * 100), 2) correy_percent = round(((correy_votes / total_votes) * 100), 2) li_percent = round(((li_votes / total_votes) * 100), 2) otooley_percent = round(((otooley_votes / total_votes) * 100), 2) # The winner of the election if khan_percent > max(correy_percent, li_percent, otooley_percent): winner = "Khan" elif correy_percent > max(khan_percent, li_percent, otooley_percent): winner = "Correy" elif li_percent > max(correy_percent, khan_percent, otooley_percent): winner = "Li" else: winner = "O'Tooley" #Print Statements print(f'Election Results') print(f'-----------------------------------') print(f'Total Votes: {total_votes}') print(f'-----------------------------------') print(f'Khan: {khan_percent}% ({khan_votes})') print(f'Correy: {correy_percent}% ({correy_votes})') print(f'Li: {li_percent}% ({li_votes})') print(f"O'Tooley: {otooley_percent}% ({otooley_votes})") print(f'-----------------------------------') print(f'Winner: {winner}') print(f'-----------------------------------') # Print/Export the following information into a text file: output_path = os.path.join(r"C:\Users\eliza\Desktop\Data Analytics\Git Hub Repositories\03-Python-Challenge\PyPoll\Analysis\poll_analysis.txt") with open(output_path, 'w') as outputHeader: outputHeader.write(f'-----------------------------------') outputHeader.write('\n') outputHeader.write(f'Election Results') outputHeader.write('\n') outputHeader.write(f'-----------------------------------') outputHeader.write('\n') outputHeader.write(f'Total Votes: {total_votes}') outputHeader.write('\n') outputHeader.write(f'-----------------------------------') outputHeader.write('\n') outputHeader.write(f'Khan: {khan_percent}% ({khan_votes})') outputHeader.write('\n') outputHeader.write(f'Correy: {correy_percent}% ({correy_votes})') outputHeader.write('\n') outputHeader.write(f'Li: {li_percent}% ({li_votes})') outputHeader.write('\n') outputHeader.write(f"O'Tooley: {otooley_percent}% ({otooley_votes})") outputHeader.write('\n') outputHeader.write(f'-----------------------------------') outputHeader.write('\n') outputHeader.write(f'Winner: {winner}') outputHeader.write('\n') outputHeader.write(f'-----------------------------------')
#declare and initiate variables import csv import os #declare totals variables tot = 0 totMnth = 0 totMnthAvgDenom = 0 #declare profit and loss variables and get avg change curPL = 0 prevPL = 0 curChange = 0 #used for the currect total change prevChange = 0 #used to hold the previous total change totChange = 0 #used to get the sum of the total change avgChange = 0 #user to get the ave of the total change #declare to hold max and min change values maxInc = 0 maxDec = 0 #declare file paths csvPath = os.path.join('Resources','budget_data.csv') fileOutput = os.path.join('Analysis','budget_data.txt') with open(csvPath,'r') as csvFile: csvReader = csv.reader(csvFile, delimiter = ',') next(csvReader) #Read in file and loop through for row in csvReader: #increm the total month counter totMnth += 1 #convert second element of row list to Int try: curPL = int(row[1]) tot += curPL except ValueError: print(row[1]+" will not convert to int") #Get profit/loss change for the current period if totMnth != 1: mnth = row[0] curChange = (curPL - prevPL) totChange += curChange totMnthAvgDenom += 1 #look for max and min changes if curChange > maxInc: maxInc = curChange maxIMnth = mnth if curChange < maxDec: maxDec = curChange maxDMnth = mnth #set prevChange to curChange for next evalution in loop prevChange = curChange #set previous profit loss to the current so that it can be evaluated next time prevPL = curPL avgChange = (totChange)/(totMnthAvgDenom) #capture all output into a variable that will be used later for both output to screen and file output = ( f"Financial Analysis\n" f"-----------------------\n" f"Total Months: {totMnth}\n" f"Total: ${tot:,}\n" f"Average Change: ${avgChange:,.2f}\n" f"Greatest Increase in Profits: {maxIMnth} (${maxInc:,})\n" f"Greatest Decrease in Profits: {maxDMnth} (${maxDec:,})\n" ) #print to screen and file print(output) with open(fileOutput, "w", newline="") as textFile: textFile.write(output)
import random output = None def loadMenu(): print("1. Roll Die") print("2. Roll Dice") print("3. Settings") menuSelection = int(input("Enter menu selection: ")) if (menuSelection == 1): rollDie() elif (menuSelection == 2): numOfDies = int(input("How many dice would you like to roll: ")) x = 0 while x < numOfDies: rollDie() x = x + 1 elif (menuSelection == 3): print("natta") def rollDie(): output = random.randint(1,6) print(str(output)) loadMenu()
import math, abs class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __iadd__(self, other): self.x += other.x self.y += other.y return self def __sub__(self, other): return Point(self.x - other.x, self.y - other.y) def __isub__(self, other): self.x -= other.x self.y -= other.y return self def __mul__(self, other): return Point(self.x * other, self.y * other) def __imul__(self, other): self.x *= other self.y *= other return self def __truediv__(self, other): return Point(self.x / other, self.y / other) def __itruediv__(self, other): self.x /= other self.y /= other return self def __floordiv__(self, other): return Point(self.x // other, self.y // other) def __ifloordiv__(self, other): self.x //= other self.y //= other return self @property def distance_from_origin(self): return math.hypot(self.x, self.y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __repr__(self): return ('{0.__class__.__name__}({0.x!r},{0.y!r}'.format(self)) def __str__(self): return "({0.x!r}, {0.y!r})".format(self) class Circle(Point): def __init__(self, radius, x=0, y=0): super().__init__(x, y) self.radius = radius @property def area(self): return math.pi * (self.radius ** 2) @property def edge_distance_from_origin(self): return abs(self.distance_from_origin - self.radius) @property def circumference(self): return 2 * math.pi * self.radius @property def radius(self): return self.__radius @radius.setter def radius(self, radius): assert radius > 0, "radius must be nonzero and non-negative" self.__radius = radius def __eq__(self, other): return self.radius == other.radius and super().__eq__(other) def __repr__(self): return ("{0.__class__.name__}({0.radius!r},{0.x!r},{0.y!r})".format(self)) if __name__ == '__main__': import doctest doctest.testmod()
name1 = str(input("First name ")) day1 = int(input("First day ")) month1 = int(input("First month ")) year1 = int(input("First year ")) name2 = str(input("Second name ")) day2 = int(input("Second day ")) month2 = int(input("Second month ")) year2 = int(input("Second year ")) name3 = str(input("Third name ")) day3 = int(input("Third day ")) month3 = int(input("Third month ")) year3 = int(input("Third year ")) name4 = str(input("Fourth name ")) day4 = int(input("Fourth day ")) month4 = int(input("Fourth month ")) year4 = int(input("Fourth year ")) print("Names".ljust(20),"Birthdays".ljust(10)) print(name1.ljust(20),month1,"/",day1,"/",year1) print(name2.ljust(20),month2,"/",day2,"/",year2) print(name3.ljust(20),month3,"/",day3,"/",year3) print(name4.ljust(20),month4,"/",day4,"/",year4)
from http.server import BaseHTTPRequestHandler, HTTPServer import json #What is BaseHTTPRequestHandler --> Handle HTTP reqs that arrive at server. Must be subclassed to handle each request. Important instance var of this class is server and client-address which is a tuples of the form (host, port), rfile and wfile(IO streams) #What is HTTPServer -->Class that builds on the TCPServer class by storing server address as instance vars named server_name and server_port. The server is accessed by the handler through the handlers server instance var. #Format --> HTTPServer(server_address, req_handler_class) #BaseHTTPRequestHandler(request, client_address, server) #json load --> from string, bytes or bytes_array #json loads --> from file #json dump --> to file #json dumps --> to string hostName = "localhost" server_port = 8000 ''' SimpleHTTPRequestHandler (now called just http.server) defines methods like do_GET() if you get a GET request then do this. wfile is an instance var and write is a function from class BufferedIOBase with format write(bytes-like object) and returns # of bytes written. Similarly, read(N bytes). read and write returns bytes self.headers["content-length"] --> Data from form POST ''' class MySimpleServer(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(bytes("<html><form action = '#' method='POST'><input type='text' name='firstname'></input><input type='text' name='lastname'></input><input type='submit' value='Submit'></input></form></html>", "utf-8")) def do_POST(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() print("Content Length: ", int(self.headers["Content-Length"])) data = self.rfile.read(int(self.headers["Content-Length"])) print(data.decode("utf-8")) try: print(json.loads(data)) except: pass def run(server_class=HTTPServer, handler_class=MySimpleServer, addr="localhost", port=8000): server_address = (addr, port) httpd = server_class(server_address, handler_class) print(f"Starting httpd server on {addr}:{port}") try: httpd.serve_forever() except KeyboardInterrupt: httpd.socket.close() run()
import math def part_one(): masses = [] with open("input.txt") as f: for line in f: masses.append(int(line)) return [math.floor(m / 3) - 2 for m in masses] def part_two(fuels): recursive_fuel_req = [recursive_mass(fuel_mass) for fuel_mass in fuels] return sum(recursive_fuel_req) def recursive_mass(fuel): fuel_req_by_fuel = math.floor(fuel / 3) - 2 if fuel_req_by_fuel <= 0: return fuel return fuel + recursive_mass(fuel_req_by_fuel) fuel_req = part_one() print(f"part one:\n{sum(fuel_req)}") print() total_fuel = part_two(fuel_req) print(f"part two:\n{total_fuel}")
# This class SHOULD NEVER be instantiated # BUT logic common to both types of nodes can be placed here e.g. distance class Node(object): def __init__(self): self.id = '' self.x = 0.0 self.y = 0.0 self.demand = 0.0 self.serviceTime = 0.0 self.windowStart = 0.0 self.windowEnd = 0.0 self.waiting_time = 0 def __hash__(self): return hash(self.id) def __str__(self): return self.id def __repr__(self): return self.id def __eq__(self, other): if type(self) != type(other): return False else: return self.id.__eq__(other.id)
numero = int(input("Digite o numero da tabuada: ")) for count in range(1, 11): multiplica = numero * count print("{} x {} = {}".format(numero, count, multiplica))
frase = str(input("Digite a sua frase: ")).strip().upper() palavra = frase.split() junto = ''.join(palavra) inverso = '' '''inverso = junto[::-1] - Está linha faz a mesma função do FOR abaixo''' for letra in range(len(junto) - 1, -1, -1): inverso += junto[letra] print(junto, inverso) if inverso == junto: print("A frase é um Palíntromo!") else: print("Não é Palíntromo!")
n1 = int(input("Primeiro valor: ")) n2 = int(input("Segundo valor: ")) opcao = 0 while opcao != 5: print(''' [1] Somar [2] Multiplicar [3] Maior [4] Novos Números [5] Sair''') opcao = int(input("Qual é a sua opção: ")) if opcao == 1: soma = n1 + n2 print("A soma de {} e {} é: {}".format(n1, n2, soma)) elif opcao == 2: multiplica = n1 * n2 print("A multiplicação de {} e {} é: {}".format(n1, n2, multiplica)) elif opcao == 3: if n1 > n2: print("O Maior é: {}".format(n1)) else: print("O Maior é: {}".format(n2)) elif opcao == 4: n1 = int(input("Primeiro valor: ")) n2 = int(input("Segundo valor: ")) else: print("Opção Invalida,\nTente Novamente...") print("Fim !!!")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 13 11:52:15 2019 In this function a neural network is created to determine if the masses of gives usefull values of the minimums to find. @author: ug """ import tensorflow as tf import numpy as np import pandas as pd data_input_T = np.load('dataPython.npy') data_input_T = data_input_T[:,[2,1,3,0,6,5,7,4,9,12]] np.savetxt('data_T.txt',data_input_T) data_input = np.load('train_input_rand.npy') np.savetxt('./train_input_rand.txt',data_input) data_output = np.load('train_output_rand.npy').reshape(22000,1) np.savetxt('./train_output_rand.txt',data_output) def normalize(data): min_d = np.min(data,axis = 0) max_d = np.max(data,axis = 0) data_N = (data - min_d)/(max_d - min_d+0.01) return data_N data_input_n = normalize(data_input) model = tf.keras.models.Sequential([tf.keras.layers.Dense(10, input_dim=10, activation='relu'), tf.keras.layers.Dense(10,activation=tf.nn.relu), tf.keras.layers.Dense(1,activation='sigmoid')]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics = ['accuracy']) model.fit(data_input_n,data_output,epochs = 10) random_data = normalize(np.load('input_train.npy')) prediction = model.predict(random_data) result = np.load('train_output.npy')
from random import randrange from sys import exit import sqlite3 connection = sqlite3.connect('card.s3db') cursor = connection.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS card (id INTEGER PRIMARY KEY, number TEXT, pin TEXT, balance INTEGER DEFAULT 0);') connection.commit() login_account_number = 0 class Customer: def __init__(self): self.card_number = str(400000) + ''.join([str(randrange(0, 10)) for _ in range(9)]) self.pin_code = ''.join([str(randrange(0, 10)) for _ in range(4)]) self.balance = 0 def print_menu(): print('1. Create an account\n2. Log into account\n0. Exit') def last_number(card_number_without_last): list_sum = 0 last_digit = 0 counter = 1 card_list = list(card_number_without_last) for numbers in card_list: numbers = int(numbers) if counter % 2 != 0: numbers *= 2 if numbers > 9: numbers -= 9 list_sum += numbers counter += 1 card_number_sum = list_sum while card_number_sum % 10 != 0: last_digit += 1 card_number_sum = list_sum + last_digit return str(last_digit) def pass_luhn(card_number): list_sum = 0 last_digit = card_number[-1] counter = 1 card_number = list(card_number) del card_number[-1] card_number_without_last = card_number for numbers in card_number_without_last: numbers = int(numbers) if counter % 2 != 0: numbers *= 2 if numbers > 9: numbers -= 9 list_sum += numbers counter += 1 if (list_sum + int(last_digit)) % 10 == 0: return True else: return False def sql_execution(command): cursor.execute(command) return connection.commit() def sql_fetchone(select_command): cursor.execute(select_command) return cursor.fetchone() def sql_fetchall(select_command): cursor.execute(select_command) return cursor.fetchall() def account_creation(): user = Customer() user.card_number = user.card_number + last_number(user.card_number) print(f'Your card has been created\nYour card number:\n{user.card_number}\nYour card PIN:\n{user.pin_code}') cursor.execute('INSERT INTO card (number, pin, balance) VALUES (?, ?, ?);', (user.card_number, user.pin_code, user.balance)) connection.commit() print_menu() user_choice(int(input())) def login(): print('Enter your card number:') input_number = input() print('Enter your PIN:') input_pin = input() login_check(input_number, input_pin) def user_choice(option): if option == 1: account_creation() elif option == 2: login() elif option == 0: print('Bye!') cursor.close() exit() else: print_menu() user_choice(int(input())) def login_check(card, pin): cursor.execute('''SELECT id, number, pin, balance FROM card WHERE number = ? AND pin = ? ;''', (str(card), str(pin))) result = cursor.fetchone() if result is None: print('Wrong card number or PIN!') print_menu() user_choice(int(input())) else: print('You have successfully logged in!') print_login_menu() user_choice_login(int(input()), card, pin) def print_login_menu(): print('1. Balance\n2. Add income\n3. Do transfer\n4. Close account\n5. Log out\n0. Exit') def user_choice_login(variant, card, pin): cursor.execute('''SELECT balance FROM card WHERE number = ? AND pin = ? ;''', (str(card), str(pin))) if variant == 1: print(f'Balance: {cursor.fetchone()[0]}') print_login_menu() user_choice_login(int(input()), card, pin) elif variant == 2: print('Enter income:') cursor.execute('UPDATE card SET balance = balance + (?) WHERE number = (?) AND pin = (?)', (int(input()), card, pin)) connection.commit() print("Income was added!") print_login_menu() user_choice_login(int(input()), card, pin) elif variant == 3: print('Transfer:\nEnter card number') card_input = input() cursor.execute('SELECT COUNT(*) FROM card WHERE number = (?);', (card_input, )) connection.commit() if card == card_input: print("You can't transfer money to the same account!") print_login_menu() user_choice_login(int(input()), card, pin) elif pass_luhn(card_input) is False: print('Probably you made a mistake in the card number. Please try again!') print_login_menu() user_choice_login(int(input()), card, pin) elif cursor.fetchone()[0] == 0: print('Such a card does not exist.') print_login_menu() user_choice_login(int(input()), card, pin) else: print('Enter how much money you want to transfer:') transfer_amount = int(input()) cursor.execute('''SELECT balance FROM card WHERE number = ? AND pin = ?;''', (str(card), str(pin))) balance = cursor.fetchone()[0] if transfer_amount > balance: print('Not enough money!') print_login_menu() user_choice_login(int(input()), card, pin) else: cursor.execute('UPDATE card SET balance = balance + (?) WHERE number = (?)', (transfer_amount, card_input)) connection.commit() cursor.execute('UPDATE card SET balance = balance - (?) WHERE number = (?)', (transfer_amount, card)) connection.commit() print('Income was added!') print_login_menu() user_choice_login(int(input()), card, pin) elif variant == 4: cursor.execute('DELETE FROM card WHERE number = (?) AND pin = (?)', (card, pin)) connection.commit() print('The account has been closed!') print_menu() user_choice(int(input())) elif variant == 5: print('You have successfully logged out!') print_menu() user_choice(int(input())) elif variant == 0: print('Bye!') cursor.close() exit() else: print_menu() user_choice(int(input())) print_menu() user_choice(int(input()))
# get training data, validation data, test data, layer neuron numbers, learning rate, mini-batch size, number of training epochs # function for mini-batch stochastic gradient descent # function for updating each mini batch # function for backpropagation # function for sigmoid computation # function for sigmoid derivative computation # function for output for a given input # function for accuracy # function for neuron cost calculation # function for activation import numpy as np import random import mnist_loader class ANN(object): def __init__(self, layer_sizes, init_biases=None, init_weights=None): # create layers of nn self.layer_sizes = np.array(layer_sizes) if(init_biases != None and init_weights != None): self.biases = init_biases self.weights = init_weights else: # create biases for all neurons except for input neurons self.biases = [np.random.randn(neurons, 1) for neurons in layer_sizes[1:]] # create weight matrices for neurons accessible by [neuron in layer x, neuron in layer x-1] (for ease in calculations) self.weights = [np.random.randn(dest_neuron, source_neuron) for dest_neuron, source_neuron in zip(layer_sizes[1:], layer_sizes[:-1])] def train(self, learning_rate, mini_batch_size, epochs_to_train, training_data, validation_data=None, test_data=None, periodically_evaluate=False, epochs_between_evaluation=1): # uses mini-batch stochastic gradient descent print "Started training neural network..." # outer for loop to keep track of epochs trained for curr_epoch in xrange(epochs_to_train): # shuffle data for better performance shuffled_training_data = np.array(training_data) random.shuffle(shuffled_training_data) # inner loop for training all mini_batches in randomized data for curr_mini_batch in [shuffled_training_data[x: x + mini_batch_size] for x in xrange(0, len(shuffled_training_data), mini_batch_size)]: self.train_mini_batch(learning_rate, curr_mini_batch) np.save("nn_biases.npy", self.biases) np.save("nn_weights.npy", self.weights) print "Finished epoch " + str(curr_epoch) + "/" + str(epochs_to_train) # periodically evaluate accuracy of nn if desired using test data if given if(test_data != None and periodically_evaluate): if(curr_epoch % epochs_between_evaluation == 0): print "Calculating current accuracy..." percent_accurate = self.evaluate_accuracy(test_data) print "Current accuracy is " + str(percent_accurate) + "% (" + str(percent_accurate/100.0 * len(training_data)) + "/" + str(len(training_data)) + ")" def train_mini_batch(self, learning_rate, mini_batch): # create matrix to store sum of bias and weight cost gradient components del_bias_sum = [np.zeros(np.shape(b)) for b in self.biases] del_weight_sum = [np.zeros(np.shape(w)) for w in self.weights] for set in mini_batch: # use backpropagation to get matrices of weight and bias cost gradient components for the neurons del_bias, del_weight = self.backpropagate(set[0], set[1]) # add to total gradients for bias and weight #del_bias_sum = np.add(del_bias_sum, del_bias) #del_weight_sum = np.add(del_weight_sum, del_weight) del_bias_sum = [nb+dnb for nb, dnb in zip(del_bias, del_bias_sum)] del_weight_sum = [nw+dnw for nw, dnw in zip(del_weight, del_weight_sum)] # update the weights and the biases simultaneously scaled_lr = 1.0 * learning_rate / len(mini_batch) #self.biases = [b - np.multiply(dbs, scaled_lr) for b, dbs in zip(self.biases, del_bias_sum)] self.biases = [b-(learning_rate/len(mini_batch))*nb for b, nb in zip(self.biases, del_bias_sum)] self.weights = [w - (learning_rate / len(mini_batch)) * nw for w, nw in zip(self.weights, del_weight_sum)] #self.weights = [w - np.multiply(dws, scaled_lr) for w, dws in zip(self.weights, del_weight_sum)] def backpropagate(self, x_in, y_in): # calculate activation matrix weighted_inputs, activations = self.feedforward(x_in) # compute output layer error #errors = [np.zeros(np.shape(b)) for b in self.biases] #errors[-1] = self.del_activation_cost(activations[-1], y_in) * self.sigmoid_derivative(weighted_inputs[-1]) bias_errors = [np.zeros(np.shape(b)) for b in self.biases] weight_errors = [np.zeros(np.shape(w)) for w in self.weights] error = self.del_activation_cost(activations[-1], y_in) * self.sigmoid_derivative(weighted_inputs[-1]) bias_errors[-1] = error weight_errors[-1] = np.dot(error, np.transpose(activations[-2])) # backpropagate error, finding error for all layers #for layer_index in xrange(len(errors) - 2, 0, -1): # errors[layer_index] = (np.dot(np.transpose(self.weights[layer_index + 1]), errors[layer_index + 1]) * # self.sigmoid_derivative(weighted_inputs[layer_index])) for layer_index in xrange(2, len(self.layer_sizes)): weighted_input = weighted_inputs[-layer_index] sigmoid_weighted_input = self.sigmoid_derivative(weighted_input) error = np.dot(np.transpose(self.weights[-layer_index + 1]), error) * sigmoid_weighted_input bias_errors[-layer_index] = error weight_errors[-layer_index] = np.dot(error, np.transpose(activations[-layer_index - 1])) # compute cost gradient matrices using activation and error matrices #del_weight = [np.zeros(np.shape(dw)) for dw in self.weights] #for layer_index in xrange(len(self.weights)): # del_weight[layer_index] = np.dot(errors[layer_index], np.transpose(activations[layer_index])) return bias_errors, weight_errors def feedforward(self, inputs): # set input layer #activations = [np.zeros(neurons, 1) for neurons in self.layer_sizes] #activations[0] = np.array(inputs) #weighted_inputs = [np.zeros(np.shape(b)) for b in self.biases] activations = [inputs] activation = inputs weighted_inputs = [] # compute activations #for layer_index in xrange(len(weighted_inputs)): # weighted_inputs[layer_index] = np.dot(self.weights[layer_index], activations[layer_index]) + self.biases[layer_index] # activations[layer_index + 1] = self.sigmoid(weighted_inputs[layer_index]) for bias, weight in zip(self.biases, self.weights): weighted_input = np.dot(weight, activation) + bias weighted_inputs.append(weighted_input) activation = self.sigmoid(weighted_input); activations.append(activation) return weighted_inputs, activations def feedforward_out(self, inputs): for b, w in zip(self.biases, self.weights): inputs = self.sigmoid(np.dot(w, inputs) + b) return inputs def sigmoid(self, to_sigmoid): sigmoided = 1 / (1 + np.exp(-1 * to_sigmoid)) return sigmoided def del_activation_cost(self, activations, y): return activations - y def sigmoid_derivative(self, to_sigmoid): return self.sigmoid(to_sigmoid) * (1 - self.sigmoid(to_sigmoid)) def evaluate_accuracy(self, test_data): num_correct = 0.0 for set in test_data: activation = self.feedforward_out(set[0]) #print "Predicted " + str(np.argmax(activation)) #print "Actual " + str(set[1]) #print if(np.argmax(activation) == set[1]): num_correct += 1 return (100.0 * num_correct) / (len(test_data)) if __name__ == '__main__': np.set_printoptions(threshold=np.inf) training, validation, test = mnist_loader.load_data_wrapper() layer_sizes = ([784, 30, 10]) """ try: init_biases = np.load("nn_biases.npy") init_weights = np.load("nn_weights.npy") nn = ANN(layer_sizes, init_biases, init_weights) print "Loaded predetermined weights and biases." except IOError: print "Could not load predetermined weights and biases." nn = ANN(layer_sizes) """ nn = ANN(layer_sizes) #nn.evaluate_accuracy(test) nn.train(3.0, 10, 30, training, validation, test, True, 1)
#!/usr/bin/env python3 """ Name: player_wolfe.py Desc: Mr. Wolfe's player AI, uses minimax and AB pruning Author: Alex Wolfe """ from copy import deepcopy from constants import * class Player(): def __init__(self, color): self.name = "WolfeBot" self.type = "AI" self.color = color def next_move(self, board): """ Given a board, decides and returns the next move desired. :param board: The current Othello board. :return: a move as (row, col) """ # move = self.mini_max_decision(board) move = self.ab_search(board) # print("decision:", move) return move def mini_max_decision(self, board): successors = board.get_valid_moves(board.current_player) self.board = board if board.current_player is BLACK: #print("Playing as {}, max".format(BLACK)) max_move = successors[0] max_state = deepcopy(board) max_state.make_move(max_move) value = self.max_value(max_state) for move in successors: temp = deepcopy(board) temp.make_move(move) if value < self.max_value(temp): max_move = move return max_move else: min_move = successors[0] min_state = deepcopy(board) min_state.make_move(min_move) value = self.min_value(min_state) for move in successors: temp = deepcopy(board) if value > self.min_value(temp): min_move = move return min_move def cutoff_test(self, state, depth): if state.terminal_test() or state.depth is depth: # print("reached cutoff.") return True return False def utility(self, state): return state.scores[BLACK]-state.scores[WHITE] def max_value(self, state): if self.cutoff_test(state, self.board.depth+3): return self.utility(state) else: max_value = float("-inf") successors = state.get_valid_moves(self.color) for move in successors: temp = deepcopy(state) temp.make_move(move) max_value = max(self.min_value(temp), max_value) return max_value def min_value(self, state): if self.cutoff_test(state, self.board.depth+3): return self.utility(state) else: min_value = float("inf") successors = state.get_valid_moves(self.color) for move in successors: temp = deepcopy(state) temp.make_move(move) min_value = min(self.min_value(temp), min_value) return min_value def ab_search(self, board): successors = board.get_valid_moves(self.color) self.board = board if board.current_player is BLACK: max_move = successors[0] max_state = deepcopy(board) max_state.make_move(max_move) value = self.ab_max_value(max_state, float("-inf"), float("inf")) for move in successors: temp = deepcopy(board) temp.make_move(move) if value < self.ab_max_value(temp, float("-inf"), float("inf")): max_move = move return max_move else: min_move = successors[0] min_state = deepcopy(board) min_state.make_move(min_move) value = self.ab_min_value(min_state, float("-inf"), float("inf")) for move in successors: temp = deepcopy(board) temp.make_move(min_move) if value > self.ab_min_value(temp, float("-inf"), float("inf")): min_move = move return min_move def ab_max_value(self, state, alpha, beta): if self.cutoff_test(state, self.board.depth + 3): return self.utility(state) else: max_value = float("-inf") successors = state.get_valid_moves(state.current_player) for move in successors: temp = deepcopy(state) temp.make_move(move) max_value = max(self.ab_min_value(temp, alpha, beta), max_value) if max_value > beta: return max_value alpha = max(alpha, max_value) return max_value def ab_min_value(self, state, alpha, beta): if self.cutoff_test(state, self.board.depth + 3): return self.utility(state) else: min_value = float("inf") successors = state.get_valid_moves(state.current_player) for move in successors: temp = deepcopy(state) temp.make_move(move) min_value = min(self.ab_max_value(temp, alpha, beta), min_value) if min_value < alpha: return min_value beta = min(beta, min_value) return min_value
#!/usr/bin/env python # coding: utf-8 # In[2]: # ============================================================= # Copyright © 2020 Intel Corporation # # SPDX-License-Identifier: MIT # ============================================================= # # XGBoost Getting Started Example on Linear Regression # ## Importing and Organizing Data # In this example we will be predicting prices of houses in California based on the features of each house using Intel optimized XGBoost shipped as a part of the oneAPI AI Analytics Toolkit. # Let's start by **importing** all necessary data and packages. # In[3]: import xgboost as xgb from sklearn.metrics import mean_squared_error from sklearn.datasets import fetch_california_housing from sklearn.model_selection import train_test_split import pandas as pd import numpy as np # Now let's **load** in the dataset and **organize** it as necessary to work with our model. # In[4]: #loading the data california = fetch_california_housing() #converting data into a pandas dataframe data = pd.DataFrame(california.data) data.columns = california.feature_names #setting price as value to be predicted data['PRICE'] = california.target #extracting rows X, y = data.iloc[:,:-1],data.iloc[:,-1] #using dmatrix values for xgboost data_dmatrix = xgb.DMatrix(data=X,label=y) #splitting data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1693) # **Instantiate and define XGBoost regresion object** by calling the XGBRegressor() class from the library. Use hyperparameters to define the object. # In[5]: xg_reg = xgb.XGBRegressor(objective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = 5, alpha = 10, n_estimators = 10) # ## Training and Saving the model # **Fitting and training model** using training datasets and predicting values. # In[6]: xg_reg.fit(X_train,y_train) preds = xg_reg.predict(X_test) # **Finding root mean squared error** of predicted values. # In[7]: rmse = np.sqrt(mean_squared_error(y_test, preds)) print("RMSE:",rmse) # ##Saving the Results # Now let's **export the predicted values to a CSV file**. # In[8]: pd.DataFrame(preds).to_csv('foo.csv',index=False) # In[9]: print("[CODE_SAMPLE_COMPLETED_SUCCESFULLY]") # In[ ]:
from collections import deque class node: def __init__(self,val): self.l = None self.r = None self.v = val self.color = 0 self.d = 0 class tree: def __init__(self): self.root = None self.l = None self.r = None self.h = 0 def fromlist(self, alist): for i in alist: self.add_val(i) def get_root(self): return self.root def add_val(self, val): root = self.get_root() # Create a root if there is no root if not root: root = node(val) self.root = root self.root.color = 0 else: parent = root while(root): parent = root if val <= root.v: root = root.l else: root = root.r if val <= parent.v: parent.l = node(val) else: parent.r = node(val) def search(self,val): root = self.get_root() parent = None branch = None # left or right print "\nsearch path to ", val, ":", while root: print root.v, if val == root.v: print '\n' return parent, branch, root elif val <= root.v: print 'left', parent = root root = root.l branch = 'l' if not root: print 'not found' return elif val >= root.v: print 'right', parent = root root = root.r branch = 'r' if not root: print 'not found' return return None # Find the height of a (sub)tree (DFS) # This function changes node.h on its way. # When this is not desired, use find_height_recursion def find_height(self,root): height = 0 stack = list() # use list() to simulate a queue stack.append(root) root.h = 0 while(len(stack)>0): node = stack.pop() if node.l or node.r: if node.l: node.l.h = node.h + 1 stack.append(node.l) if node.r: node.r.h = node.h + 1 stack.append(node.r) else: # when a leaf is reached height = max(height, node.h) return height def find_height_recursion(self, root, height): height_l = height # The two lines prevent errors when left or right height_r = height # branch is missing if root.l: height_l = self.find_height_recursion(root.l, height+1) # Increment in height if a new branch is found. # The height is incremented only in stack if root.r: height_r = self.find_height_recursion(root.r, height+1) return max(height_l, height_r) # Traverse a tree (BFS) def traverse_and_print(self): root = self.get_root() queue = deque() # list() is not good for simulating the a queue layer = dict() ith = 0 at_color = 0 layer[0] = [] if root: queue.append(root) root.color = 0 else: return None print "Traverse the tree", while len(queue)>0: node = queue.popleft() if at_color != node.color: ith +=1 at_color = node.color layer[ith]= [] layer[ith].append(node.v) print node.v, if node.l: node.l.color = not node.color queue.append(node.l) if node.r: node.r.color = not node.color queue.append(node.r) return layer def find_first_imbalanced_node(self): depth = min(depth,node.h) # tbd def right_rotate(z): """ z x / \ / \ x T4 y z / \ --> / \ / \ y T3 T1 T2 T3 T4 / \ T1 T2 """ x = z.l tmp = x.r x.r = z z.l = tmp return x def left_rotate(z): """ z x / \ / \ T1 x z y / \ --> / \ / \ T2 y T1 T2 T3 T4 / \ T3 T4 """ x = z.r tmp = x.l x.l = z z.r = tmp return x
from abc import ABC, abstractmethod from tkinter import * from tkinter import filedialog """ The App class defines the behaviour of a GUI application to select the file paths. """ class App: shape_path = "" image_path = "" def __init__(self, delegate): # Sets the delegate object self.delegate = delegate # Creates the main window self.app = Tk(screenName="Select map data") # creates the labels self._shape_label = Label(self.app) self._image_label = Label(self.app) # Instantiates the button with its method and places it on the window Button(self.app, text="Choose Shapefile", width=30, command=self.set_shape_path).pack() # places the label self._shape_label.pack() # instantiates the second button Button(self.app, text="Choose Image", width=30, command=self.set_image_path).pack() # places the second label self._image_label.pack() # instantiates the last button Button(self.app, text="Plot!", width=30, command=self.plot).pack() # starts the app main loop self.app.mainloop() def set_shape_path(self): # uses a function dialog to select file file = filedialog.askopenfile() # gets the file path self.shape_path = file.name # defines the label text self._shape_label.__setattr__("text", self.shape_path) self._shape_label.pack() def set_image_path(self): # uses a function dialog to select file file = filedialog.askopenfile() # gets the file path self.image_path = file.name # defines the label text self._image_label.__setattr__("text", self.image_path) self._image_label.pack() # this method is called when the Plot button is pressed def plot(self): # sends the paths to the delegate self.delegate.get_shape_path(self.shape_path) self.delegate.get_image_path(self.image_path) # quits the application self.app.quit() """ This is an abstract class that defines the Delegate protocol of the GUI app. Only determines the implementation of the two methods, both for obtaining the file paths. """ class AppDelegate(ABC): @abstractmethod def get_shape_path(self, file_path): pass @abstractmethod def get_image_path(self, file_path): pass
#importamos biblioteca y declaramos variable import random caracteres = ['!','#','$','%','&','?','¿','¡','*','+','"'] frase = (input('Ingrese su contraseña: ')) #primera condicion hacer fuincion while (4 > (len(frase.split())) or 10 < (len(frase.split()))): frase = input ("Ingrese una contraseña que este en el rango de 4 a 10 en palabras: ") #segunda condicion (hacer funcion) while ( (6 > len(frase.replace (" ",""))) or (50 < len(frase.replace (" ","")))): frase = input ('Ingresa una contraseña que este en el rango de 6 a 50 caracteres: ') #Quitar espacios a frase contrasena = frase.replace(' ','') #Poner dos simbolos aleatorios contrasena = (random.choice(caracteres)+random.choice(caracteres)+contrasena+random.choice(caracteres)+random.choice(caracteres)) #cambiar letras a numeros letras_mayus = 'AEIOTB' letras_minus = 'aeiotb' numeros = '431078' cambio = contrasena.maketrans(letras_mayus,numeros) contrasena = contrasena.translate(cambio) cambio = contrasena.maketrans(letras_minus,numeros) print (frase) print (contrasena.translate(cambio))
import pygame # Inicializando o pygame e criando a janela pygame.init() display = pygame.display.set_mode([840, 480]) pygame.display.set_caption("Palavras Cruzadas") drawGroup = pygame.sprite.Group() guy = pygame.sprite.Sprite(drawGroup) guy.image = pygame.image.load("Data/pixil-frame-0.png") guy.image = pygame.transform.scale(guy.image, [100, 100]) guy.rect = pygame.Rect(50, 50, 50, 50) # Desenhando def draw(): display.fill([19, 173, 235]) player = pygame.Rect(50, 50, 100, 100) # player.center = [50, 50] pygame.draw.rect(display, [255, 255, 255, 255], player) drawGroup.draw(display) GameLoop = True if __name__ == "__main__": while GameLoop: for event in pygame.event.get(): if event.type == pygame.QUIT: GameLoop = False # Analizando as teclas que foram pressionadas """elif event.type == pygame.KEYDOWN: if event.key == pygame.K_w: print("Apertou w")""" # Analizando as teclas que foram soltadas """elif event.type == pygame.KEYUP: print("Soltou w")""" # Analizando as teclas que estam sendo pressionadas Keys = pygame.key.get_pressed() if Keys[pygame.K_d]: guy.rect.x += 1 # print("Segurando w") if Keys[pygame.K_a]: guy.rect.x -= 1 if Keys[pygame.K_s]: guy.rect.y += 1 if Keys[pygame.K_w]: guy.rect.y -= 1 draw() pygame.display.update()
# Swap with and without temp a=4 b=7 temp=a a=b b=temp print("Swapped with temp :") print("a=",a," b=",b) a=a+b b=a-b a=a-b print("Swapped without temp :") print("a=",a," b=",b)
string=input("Enter a string:") rev='' for i in string: rev = i + rev print(rev,"is the reverse of",string)
string1=input("Enter main string: ") string2=input("Enter the string to be added: ") stringf="" for i in range(0,int(len(string1)/2)): stringf = stringf + string1[i] stringf=stringf + string2 for i in range(int(len(string1)/2),len(string1)): stringf = stringf + string1[i] print(stringf)
print("Enter Tuple of Numbers. Any character to end.") try: my_tup=() while True: m except: print("List of Numbers:",my_tup)
num1 = 6 num2 = 10 if num1 < num2: print("less than") elif num1 == num2: print("elual to") else: print("greater than") progName = "Python" answer = "I love {}!".format(progName) print(answer) myList = ('Pink', 'Black', 'Green', 'Teal', 'Red', 'Blue') for color in myList: if color == 'Blue': print('The chosen color is Pink.') truth1 = True truth2 = False print("the truth is always {}.".format(truth2))
##Creating a class that will be encapsulated class protected: def __init__(self,number): #Creating a nurmal attribute self.a = 10 #Creating a protected attribute self._b = 20 #creating a private attribute self.__c = 30 protected = protected('number') print(protected.a) print(protected._b) print(protected.__c)
from statistics import mean import numpy as np import matplotlib.pyplot as plt from matplotlib import style import random style.use('fivethirtyeight') xs=np.array([1,2,3,4,5,6], dtype=np.float64) ys=np.array([5,4,6,5,6,7], dtype=np.float64) def best_fit_slope_and_intercept(xs,ys): print(xs,ys) m=(mean(xs)*mean(ys)-mean(xs*ys))/((pow(mean(xs),2))-mean(pow(xs,2))) b=mean(ys)-(m*mean(xs)) return m,b #function for squared error def squared_error(ys_orig, ys_line): return sum(pow((ys_line-ys_orig),2)) def coefficient_of_determination(ys_orig, ys_line): y_mean_line=[mean(ys_orig) for y in ys_orig] squared_error_regr=squared_error(ys_orig,ys_line) squared_error_y_mean = squared_error(ys_orig, y_mean_line) return 1-(squared_error_regr/squared_error_y_mean) m,b=best_fit_slope_and_intercept(xs,ys) print(m,b) regression_line=[(m*x)+b for x in xs] # making prediction based on the given function predict_x=8 predict_y=(m*predict_x+b) print(predict_y) print('This is testing of two factor') #Calling R Squared r_squared=coefficient_of_determination(ys, regression_line) print(r_squared) plt.scatter(xs, ys) plt.scatter(predict_x,predict_y, color='green') plt.plot(xs,regression_line) plt.show()
#!/usr/bin/env python2.7 """ Columbia W4111 Intro to databases Example webserver To run locally python server.py Go to http://localhost:8111 in your browser A debugger such as "pdb" may be helpful for debugging. Read about it online. """ import os from sqlalchemy.exc import IntegrityError, DataError from sqlalchemy import * from sqlalchemy.pool import NullPool from flask import Flask, request, render_template, g, redirect, Response order ={} tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') app = Flask(__name__, template_folder=tmpl_dir) # # The following uses the postgresql test.db -- you can use this for debugging purposes # However for the project you will need to connect to your Part 2 database in order to use the # data # # XXX: The URI should be in the format of: # # postgresql://USER:PASSWORD@<IP_OF_POSTGRE_SQL_SERVER>/postgres # # For example, if you had username ewu2493, password foobar, then the following line would be: # # DATABASEURI = "postgresql://ewu2493:foobar@<IP_OF_POSTGRE_SQL_SERVER>/postgres" # # Swap out the URI below with the URI for the database created in part 2 #DATABASEURI = "sqlite:///test.db" #104.196.175.120 DATABASEURI = "postgresql://sz2624:46zyq@104.196.175.120/postgres" # # This line creates a database engine that knows how to connect to the URI above # engine = create_engine(DATABASEURI) # # START SQLITE SETUP CODE # # after these statements run, you should see a file test.db in your webserver/ directory # this is a sqlite database that you can query like psql typing in the shell command line: # # sqlite3 test.db # # The following sqlite3 commands may be useful: # # .tables -- will list the tables in the database # .schema <tablename> -- print CREATE TABLE statement for table # # The setup code should be deleted once you switch to using the Part 2 postgresql database # #engine.execute("""DROP TABLE IF EXISTS test;""") #engine.execute("""CREATE TABLE IF NOT EXISTS test ( # id serial, # name text #);""") #engine.execute("""INSERT INTO test(name) VALUES ('grace hopper'), ('alan turing'), ('ada lovelace');""") # # END SQLITE SETUP CODE # @app.before_request def before_request(): """ This function is run at the beginning of every web request (every time you enter an address in the web browser). We use it to setup a database connection that can be used throughout the request The variable g is globally accessible """ try: g.conn = engine.connect() except: print "uh oh, problem connecting to database" import traceback; traceback.print_exc() g.conn = None @app.teardown_request def teardown_request(exception): """ At the end of the web request, this makes sure to close the database connection. If you don't the database could run out of memory! """ try: g.conn.close() except Exception as e: pass # # @app.route is a decorator around index() that means: # run index() whenever the user tries to access the "/" path using a GET request # # If you wanted the user to go to e.g., localhost:8111/foobar/ with POST or GET then you could use # # @app.route("/foobar/", methods=["POST", "GET"]) # # PROTIP: (the trailing / in the path is important) # # see for routing: http://flask.pocoo.org/docs/0.10/quickstart/#routing # see for decorators: http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/ # @app.route('/') def index(): """ request is a special object that Flask provides to access web request information: request.method: "GET" or "POST" request.form: if the browser submitted a form, this contains the data in the form request.args: dictionary of URL arguments e.g., {a:1, b:2} for http://localhost?a=1&b=2 See its API: http://flask.pocoo.org/docs/0.10/api/#incoming-request-data """ # DEBUG: this is debugging code to see what request looks like print request.args # # example of a database query # ''' cursor = g.conn.execute("SELECT address FROM address") addresses = [] for result in cursor: addresses.append(result['address']) # can also be accessed using result[0] cursor.close() ''' # # Flask uses Jinja templates, which is an extension to HTML where you can # pass data to a template and dynamically generate HTML based on the data # (you can think of it as simple PHP) # documentation: https://realpython.com/blog/python/primer-on-jinja-templating/ # # You can see an example template in templates/index.html # # context are the variables that are passed to the template. # for example, "data" key in the context variable defined below will be # accessible as a variable in index.html: # # # will print: [u'grace hopper', u'alan turing', u'ada lovelace'] # <div>{{data}}</div> # # # creates a <div> tag for each element in data # # will print: # # # # <div>grace hopper</div> # # <div>alan turing</div> # # <div>ada lovelace</div> # # # {% for n in data %} # <div>{{n}}</div> # {% endfor %} # #context = dict(addresses = addresses) # # render_template looks in the templates/ folder for files. # for example, the below file reads template/index.html # return render_template("index.html")#, **context) # This is an example of a different path. You can see it at # # localhost:8111/another # # notice that the functio name is another() rather than index() # the functions for each app.route needs to have different names # @app.route('/login', methods=['POST']) def login(): email = request.form['email'] password = request.form['password'] cmd = "select uid from users where email = :email1" cuid = g.conn.execute(text(cmd),email1 = email) cuids=[] for result in cuid: cuids.append(result['uid']) cuid.close() if cuids: cmd2 = "select uid from users where email = :email1 and password = :password1" uid = g.conn.execute(text(cmd2),email1 = email, password1=password) uids=[] for result in uid: uids.append(result['uid']) uid.close() if uids: uuid=int(uids[0]) global order if 'uid' in order: del order['uid'] order['uid']=uuid if 'email' in order: del order['email'] order['email']=email cursor = g.conn.execute("SELECT name, type, dollar_range FROM restaurants") rnames = [] for result in cursor: rest = result[0]+' Type: '+result[1]+' '+'$'*result[2] rnames.append(rest) # can also be accessed using result[0] #rtypes.append(result['type']) #rdollar_ranges.append(result['dollar_range']) cursor.close() context = dict(restaurant = rnames)#+rtypes+rdollar_ranges) return render_template("restaurant.html", **context) else: return render_template("anotherfile.html") else: return render_template("not_registered.html") @app.route('/another') def another(): return render_template("anotherfile.html") @app.route('/restaurant') def restaurant(): cursor = g.conn.execute("SELECT name, type, dollar_range FROM restaurants") rnames = [] rtypes = [] rdollar_ranges = [] for result in cursor: rest = result[0]+' Type: '+result[1]+' '+'$'*result[2] rnames.append(rest) cursor.close() context = dict(restaurant = rnames) return render_template("restaurant.html", **context) @app.route('/create_account') def create_account(): return render_template("create_account.html") @app.route('/rate') def rate(): return render_template("rate.html") @app.route('/reserve') def reserve(): return render_template("reserve.html") # Example of adding new data to the database @app.route('/add', methods=['POST']) def add(): address = request.form['address'] zipcode = request.form['zipcode'] state = request.form['state'] email = request.form['email'] password = request.form['password'] card_number = request.form['card_number'] card_type = request.form['card_type'] name_on_card = request.form['name_on_card'] cmd = 'INSERT INTO address (address, zipcode, state) VALUES (:address1, :zipcode1, :state1)'; cmd2 = "SELECT aid FROM address where address = :address1"; g.conn.execute(text(cmd), address1 = address, zipcode1=zipcode, state1 = state); aid = g.conn.execute(text(cmd2), address1 = address); aids=[] for result in aid: aids.append(result['aid']) aid.close() aaid=int(max(aids)) try: cmd3 = 'INSERT INTO users (uid, email, aid, password) VALUES (:uid1, :email1, :aid1, :password1)'; g.conn.execute(text(cmd3), uid1 = aaid+210000, email1=email, aid1 = aaid, password1=password); except (IntegrityError, DataError): deletecmd = 'delete from address where aid = :aid2'; g.conn.execute(text(deletecmd),aid2=aaid); return render_template("wrong.html") try: cmd4 = 'INSERT INTO cards (uid, card_number, card_type, name_on_card) VALUES (:uid1, :card_number1, :card_type1, :name_on_card1)'; g.conn.execute(text(cmd4), uid1 = aaid+210000, card_number1=card_number, card_type1 = card_type, name_on_card1=name_on_card); except (IntegrityError, DataError): deletecmd2 = 'delete from address where aid = :aid2'; g.conn.execute(text(deletecmd),aid2=aaid); deletecmd2 = 'delete from users where uid = :uid2'; g.conn.execute(text(deletecmd2),uid2=aaid+210000); return render_template("wrong.html") cursor = g.conn.execute("SELECT name, type, dollar_range FROM restaurants") rnames = [] rtypes = [] rdollar_ranges = [] for result in cursor: rest = result[0]+' Type: '+result[1]+' '+'$'*result[2] rnames.append(rest) cursor.close() context = dict(restaurant = rnames) return render_template("restaurant.html", **context) @app.route('/add2', methods=['POST']) def add2(): restaurant = request.form['restaurant'] cmd = 'SELECT rid FROM restaurants where name = :restaurant1'; rid = g.conn.execute(text(cmd), restaurant1 = restaurant); rids = [] for result in rid: rids.append(result['rid']) rid.close() rrid=int(rids[0]) global order if 'rid' in order: del order['rid'] order['rid']=rrid if 'restaurant' in order: del order['restaurant'] order['restaurant']=restaurant cmd2 = 'select delivery_company.name, delivery_company.did, delivery_company.price from (delivery_company inner join hire on (delivery_company.did = hire.did)) where hire.rid = :rid1'; cmd3 = 'select food.fid, food.name from ((restaurants inner join provide on (restaurants.rid = provide.rid)) inner join food on (food.fid=provide.fid)) where restaurants.rid = :rid1'; did = g.conn.execute(text(cmd2), rid1 = rrid); dids=[] dprices=[] dnames=[] for result in did: dids.append(result['did']) dprices.append(result['price']) dnames.append(result['name']) did.close() ddid=int(dids[0]) ddprice=int(dprices[0]) ddname = dnames[0] if 'did' in order: del order['did'] order['did']=ddid if 'dprice' in order: del order['dprice'] order['dprice']=ddprice if 'dname' in order: del order['dname'] order['dname']=ddname fid = g.conn.execute(text(cmd3), rid1 = rrid); fids=[] fnames=[] for result in fid: fids.append(result['fid']) fnames.append(result['name']) fid.close() context = dict(fids = fids, fnames = fnames, dids= dids, dprices=dprices) return render_template("food.html", **context) @app.route('/add3', methods=['POST']) def add3(): food = request.form['food'] quantity = request.form['quantity'] cmd = 'SELECT fid,price FROM food where name = :food1'; ofid = g.conn.execute(text(cmd), food1 = food); ofids = [] prices = [] for result in ofid: ofids.append(result['fid']) prices.append(result['price']) ofid.close() offid=int(ofids[0]) pprice=float(prices[0]) context = dict(ofids = ofids, prices = prices) global order if 'fid' in order: del order['fid'] order['fid']=offid if 'price' in order: del order['price'] order['price']=pprice if 'food' in order: del order['food'] order['food']=food if 'quantity' in order: del order['quantity'] order['quantity']=int(quantity) if 'total_price' in order: del order['total_price'] order['total_price']=order['dprice']+order['price']*order['quantity'] cmd2 = 'INSERT INTO orders (did, rid, uid, fid, total_price, order_date,order_time) VALUES (:did1, :rid1, :uid1, :fid1, :total_price1, current_date, current_time)'; g.conn.execute(text(cmd2), did1=order['did'], rid1=order['rid'], uid1=order['uid'], fid1=order['fid'], total_price1=order['total_price']); cmd3 = 'select address, state, zipcode from address join users on address.aid = users.aid where email= :email1' address = g.conn.execute(text(cmd3),email1 = order['email']) #addresses = [] for result in address: add = result[0]+', '+result[1]+', '+str(result[2]) #addresses.append(add) address.close() if 'address' in order: del order['address'] order['address']=add return render_template("order.html", order=order) @app.route('/dorate', methods=['POST']) def dorate(): stars = request.form['stars'] comments = request.form['comments'] cmd = 'INSERT INTO rate (uid, rid, stars, comments) VALUES (:uid1, :rid1, :stars1, :comments1)'; g.conn.execute(text(cmd), uid1 = order['uid'], rid1=order['rid'], stars1=stars, comments1=comments); cursor = g.conn.execute("SELECT name, type, dollar_range FROM restaurants") rnames = [] rtypes = [] rdollar_ranges = [] for result in cursor: rest = result[0]+' Type: '+result[1]+' '+'$'*result[2] rnames.append(rest) cursor.close() context = dict(restaurant = rnames) return render_template("restaurant.html", **context) @app.route('/doreserve', methods=['POST']) def doreserve(): number = request.form['number'] date = request.form['date'] time = request.form['time'] cmd = 'INSERT INTO reserve (uid, rid, number, date, time) VALUES (:uid1, :rid1, :number1, :date1, :time1)'; g.conn.execute(text(cmd), uid1 = order['uid'], rid1=order['rid'], number1=number, date1=date, time1=time); cursor = g.conn.execute("SELECT name, type, dollar_range FROM restaurants") rnames = [] for result in cursor: rest = result[0]+' Type: '+result[1]+' '+'$'*result[2] rnames.append(rest) cursor.close() context = dict(restaurant = rnames) return render_template("restaurant.html", **context) @app.route('/order_history') def order_history(): cmd = 'select restaurants.name, food.name,orders.order_date from (orders join food on food.fid=orders.fid) join restaurants on restaurants.rid=orders.rid where orders.uid=:uid1'; orders = g.conn.execute(text(cmd), uid1 = order['uid']); oorder=[] for result in orders: tmp = 'Restaurant: '+result[0]+' food: '+result[1]+' order date: '+str(result[2]) oorder.append(tmp) orders.close() context = dict(orders = oorder) return render_template("order_history.html", **context) @app.route('/seerate') def seerate(): cmd = 'select stars, comments from rate where rid = :rid1'; rates = g.conn.execute(text(cmd), rid1 = order['rid']); rrates=[] for result in rates: rate = 'Stars: '+'*'*result[0]+' Comments: '+result[1] rrates.append(rate) rates.close() context = dict(rate = rrates) return render_template("seerate.html", **context) #@app.route('/login') #def login(): # abort(401) # this_is_never_executed() ''' @app.route('/login', methods=['GET', 'POST']) def login(): cursor = g.conn.execute("SELECT email,password FROM users") emails = [] passwords = [] for result in cursor: emails.append(result['email']) # can also be accessed using result[0] passwords.append(result['password']) cursor.close() context = dict(emails = emails, passwords = passwords) error = None if request.method == 'POST': get_email= request.form['email'] if get_email in emails: cmd = "SELECT password from users where email=\'"+get_email+"\'" get_pw = g.conn.execute(text(cmd)) if request.form['password'] == get_pw: session['logged_in'] = True flash('You were logged in') return redirect(url_for('restaurant')) error = 'Invalid email' else: error = 'Invalid email or password' return render_template('login.html', error=error) @app.route('/login', methods=['GET', 'POST']) def login(): error = None if request.method == 'POST': if request.form['username'] != 'admin' or request.form['password'] != 'admin': error = 'Invalid Credentials. Please try again.' else: return redirect(url_for('home')) return render_template('login.html', error=error) ''' if __name__ == "__main__": import click @click.command() @click.option('--debug', is_flag=True) @click.option('--threaded', is_flag=True) @click.argument('HOST', default='0.0.0.0') @click.argument('PORT', default=8111, type=int) def run(debug, threaded, host, port): """ This function handles command line parameters. Run the server using python server.py Show the help text using python server.py --help """ HOST, PORT = host, port print "running on %s:%d" % (HOST, PORT) app.run(host=HOST, port=PORT, debug=debug, threaded=threaded) run()
# Level 1 # 음양 더하기 # https://programmers.co.kr/learn/courses/30/lessons/76501 def solution(absolutes, signs): sum = 0 for i in range(len(absolutes)): if signs[i]: sum += absolutes[i] else: sum -= absolutes[i] return sum
# Binary Search # 고정점 찾기 # Amazon 인터뷰 import sys def binary_search(arr, start, end): if start > end: return None mid = (start + end) // 2 if int(arr[mid]) == mid: return mid # 중앙값보다 index가 더 작다면 elif int(arr[mid]) > mid: return binary_search(arr, start, mid - 1) # 중앙값보다 index가 더 크다면 else: return binary_search(arr, mid + 1, end) n= int(input()) arr = list(sys.stdin.readline().rstrip().split()) pin = binary_search(arr, 0, n-1) if pin == None: print(-1) else: print(pin)
# 시간초과 # def solution(s): # s_list = list(s) # i = 0 # while True: # if s_list[i] == s_list[i+1]: # s_list.pop(i) # s_list.pop(i) # i = 0 # else: # i += 1 # if i >= len(s_list)-1: # break # if len(s_list)==0: # answer = 1 # else: # answer = 0 # return answer # print(solution("baabaa")) def solution(s): stack = [] for letter in s: # 만약 스택이 비어있으면 한 단어 넣고 반복문 초기로 간다 if len(stack) == 0: stack.append(letter) #리스트의 마지막 letter가 이번에 들어온 letter와 같으면 pop한다. elif stack[-1] == letter: stack.pop() else: stack.append(letter) if len(stack) == 0: return 1 else: return 0 print(solution("baabaa"))
# Level 2 # 2021-09-15 11:50- # https://programmers.co.kr/learn/courses/30/lessons/42586 # 진도가 적힌 정수 배열 progress # 작업의 개발 속도가 적힌 정수 배열 speeds import math progress = [93, 30, 55] speeds = [1, 30, 5] day = [] answer = [] #progress = [95, 90, 99, 99, 80, 99] #speeds = [1, 1, 1, 1, 1, 1] for i in range(len(progress)): day.append(math.ceil((100 - progress[i]) / speeds[i])) print(day) target = day[0] cnt = 1 for idx in range(1, len(day)): if target >= day[idx]: cnt += 1 else: answer.append(cnt) cnt = 1 target = day[idx] idx += 1 answer.append(cnt) print(answer)
# Graph # 행성 터널 # https://www.acmicpc.net/problem/2887 def find_parent(parent, x): if parent[x] != x: parent[x] = find_parent(parent, parent[x]) return parent[x] def union_parent(parent, a, b): a = find_parent(parent, a) b = find_parent(parent, b) if a < b: parent[b] = a else: parent[a] = b v = int(input()) e = v*(v+1) -1 parent = [0] * (e-1) nodes = [] total = 0 for i in range(1, v+1): parent[i] = i def calCost(a, b): xa, ya, za = a xb, yb, zb = b return min(abs(xa-xb), abs(ya-yb), abs(za-zb)) for _ in range(v): x, y, z = map(int, input().split()) nodes.append((x,y,z)) edges = [] for i in range(len(nodes)-1): for j in range(i+1, len(nodes)): a, b, cost = i, j, calCost(nodes[i], nodes[j]) edges.append((cost, a, b)) edges.sort() for edge in edges: cost, a, b = edge if find_parent(parent, a) != find_parent(parent, b): union_parent(parent, a, b) total += cost print(total)
# BFS,DFS # 괄호 변환 # https://programmers.co.kr/learn/courses/30/lessons/60058 def checkBalance(word): l = 0 r = 0 for i in range(len(word)): if word[i] == '(': l += 1 else: r += 1 if l == r: return word[:i + 1], i + 1 def checkCorrect(word): stack = [] for w in word: # )이 더 많은 경우 stack pop 오류를 막고, false반환 try: if w == '(': stack.append(w) elif w == ')': stack.pop() except: return False if len(stack) == 0: return True else: return False def solution(p): if p == "": return "" u, idx = checkBalance(p) v = p[idx:] if checkCorrect(u): return u + solution(v) else: tmp = '(' tmp += solution(v) tmp += ')' u = u[1:-1] u = u.replace("(", ",") u = u.replace(")", "(") u = u.replace(",", ")") tmp += u return tmp print(solution("(()())()"))
# Level 2 # 뉴스 클러스터링 # https://programmers.co.kr/learn/courses/30/lessons/17677 import copy def union(l1, l2): result = l1 for i in range(len(l2)): if l2[i] in result: if l2.count(l2[i]) > result.count(l2[i]): cnt = l2.count(l2[i]) - result.count(l2[i]) for _ in range(cnt): result.append(l2[i]) else: result.append(l2[i]) return len(result) def intersect(l1, l2): result = [] for i in range(len(l1)): if l1[i] in l2: result.append(l1[i]) del l2[l2.index(l1[i])] return len(result) def solution(str1, str2): str1 = str1.upper() str2 = str2.upper() list1 = [] list2 = [] for i in range(len(str1) - 1): if str1[i: i + 2].isalpha(): list1.append(str1[i:i + 2]) for i in range(len(str2) - 1): if str2[i: i + 2].isalpha(): list2.append(str2[i:i + 2]) if len(list1) == 0 and len(list2) == 0: return 1*65536 return int(intersect(copy.deepcopy(list1), copy.deepcopy(list2)) / union(list1, list2) * 65536) print(solution("aa1+aa2", "AAAA12"))
# Binary Search # 정렬된 배열에서 특정 수의 개수 구하기 # Zoho인터뷰 import sys def binary_search(arr, target, start, end): if start > end: return None mid = (start + end) // 2 if int(arr[mid]) == target: return mid elif int(arr[mid]) > target: return binary_search(arr, target, start, mid - 1) else: return binary_search(arr, target, mid + 1, end) e, x = list(map(int, input().split())) arr = list(sys.stdin.readline().rstrip().split()) # 찾는 수의 인덱스 idx = binary_search(arr, x, 0, e-1) result = 1 if idx == None: result = -1 else: i = 1 while True: flag = 0 # index 에러 오류처리 try: if int(arr[idx - i]) == x: result += 1 flag += 1 except: pass try: if int(arr[idx + i]) == x: result += 1 flag += 1 except: pass if flag == 0: break i +=1 print(result)
# Level 1 # 숫자 문자열과 영단어 # https://programmers.co.kr/learn/courses/30/lessons/81301 def solution(s): dic = {"zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five" : 5, "six": 6, "seven": 7, "eight": 8, "nine": 9} for key in dic.keys(): while key in s: s = s.replace(key, str(dic[key])) return int(s) print(solution("one4seveneight"))
import turtle from random import randrange ## ##def tree(branch_len, t): ## if branch_len > 5: ## t.forward(branch_len) ## t.right(20) ## tree(branch_len - 15, t) ## t.left(40) ## tree(branch_len - 15, t) ## t.right(20) ## t.backward(branch_len) ## ## ##def main(): ## t = turtle.Turtle() ## wn = turtle.Screen() ## wn.bgcolor('lightgreen') ## t.left(90) ## t.up() ## t.backward(100) ## t.down() ## t.color('black') ## tree(75, t) ## wn.exitonclick() ##main() def tree(branchLen,t, width=5, color="brown"): if branchLen > 5: t.width(width) t.color(color) t.forward(branchLen) t.right(20) tree(branchLen-15, t, width-1, "green") t.left(50) tree(branchLen-15, t, width-1) t.right(30) t.backward(branchLen) t = turtle.Turtle() myWin = turtle.Screen() t.left(90) t.up() t.backward(300) t.down() tree(75,t) myWin.exitonclick()
"""reduce(func,iterable)合并减少 来自functools """ from functools import reduce scores = [88,74,67,53,24,78] summ = 0 for x in scores: summ += x print(summ) def func(x,y): return x+y print(reduce(func,scores)) print(sum(scores)) print(reduce(lambda x,y:x+y,scores))
def get_available_directions(x,y) : """ In: x and y Out: available directions This function is only used by other functions to get the direction the player is allowed to move in. """ south = True north = True east = True west = True if y == 1 or (x == 3 and y == 2) : east, west = False, False if y == 3: north = False if y == 2 and x == 2 : north, east = False, False if y == 1 or (x == 2 and y == 3) : south = False if x == 1 : west = False if x == 3 : east = False avail_dir = [north, south, east, west] return avail_dir def get_directions_string(x,y) : """ In: x and y position Out: string with available direction This function gets the available directions from the function: "available_directions" and returns a nicely readable string """ avail_dir = get_available_directions(x,y) direction_string = "You can travel: " directions = [] if avail_dir[0] : directions.append("(N)orth") if avail_dir[2] : directions.append("(E)ast") if avail_dir[1] : directions.append("(S)outh") if avail_dir[3] : directions.append("(W)est") for i in range(len(directions)) : direction_string += directions[i] + "" if len(directions) > i+1 : direction_string += " or " else : direction_string += "." return direction_string def move_the_player_if_valid(direction, x, y) : """ In: string with desired direction and the current position of the player Out: x and y (prints out if the desired direction is unavailable) This function checks if the player chose a valid direction and returns the position of the player. """ direction = direction.lower() avail_dir = get_available_directions(x,y) if direction == "n" and avail_dir[0] : y += 1 elif direction == "s" and avail_dir[1] : y -= 1 elif direction == "e" and avail_dir[2] : x += 1 elif direction == "w" and avail_dir[3] : x -= 1 else : print("Not a valid direction!") new_direction = input("Direction: ") [x,y] = move_the_player_if_valid(new_direction, x, y) return [x,y] def check_if_game_is_won(x,y) : """ In: position of the player Out: A boolean value This function checks if the game is won! """ if x == 3 and y == 1 : return True else : return False
""" This module provide a class to manage IO files """ import re import os import sys import subprocess class FileManager: """ This class is used to manage the files that can be read or write by the generator """ def __init__(self, filename="", path="", extension="", content="", encoding="utf-8"): """ this function is used to init some variable and read or write one file if the parameter are provided @param filename: the name of the file that have to be opened @param path: the path where to find the file @param extension: can be extra informations for the filename like a creation date or juste the file extention @param content: this is the content that is to be write to the file. Used only when writing a file @param encoding: this is the file encoding, default in utf-8. Used only when reading a file """ self.fs_comp = re.compile(r'(?u)[^-\w.]') self.create_storage_dir() self.stream = None if filename != "" and content != "": self.io(filename, path=path, extension=extension, content=content, encoding=encoding) @staticmethod def get_valid_filename(filename): """ This function is from the django framework: (https://github.com/django/django/blob/master/django/utils/text.py): Return the given string converted to a string that can be used for a clean filename. Remove leading and trailing spaces; convert other spaces to underscores; and remove anything that is not an alphanumeric, dash, underscore, or dot. @param filename: filename string to process @return: The converted string """ filename = str(filename).strip().replace(' ', '_') return re.sub(r'(?u)[^-\w.]', '', filename) @staticmethod def create_storage_dir(): """ Create the root storage directory where are generated xml and svg files if they didn't exist Exit the program if one directory can not be created """ try: if not os.path.isdir('../xml'): os.makedirs('../xml') except OSError as err: print(err) sys.exit('Fatal: output directory ./xml does not exist and cannot be created') try: if not os.path.isdir('../pdf'): os.makedirs('../pdf') except OSError as err: print(err) sys.exit('Fatal: output directory ./pdf does not exist and cannot be created') def io(self, filename, path="", extension="", content="", encoding="utf-8"): """ Depends on the provided params, read or write a file Warn the user if a file can not be open @param filename: the name of the file that have to be opened @param path: the path where to find the file @param extension: can be extra informations for the filename like a creation date or juste the file extention @param content: this is the content that is to be write to the file. Used only when writing a file @param encoding: this is the file encoding, default in utf-8. Used only when reading a file @return: when reading the content of the read file is returned otherwise nothing is returned """ try: mode = "r" if content != "": mode = "w" if type(content) == bytes: mode += "b" self.stream = open(path + self.get_valid_filename(filename) + extension, mode) else: self.stream = open(path + self.get_valid_filename(filename) + extension, mode, encoding=encoding) if content != "": self.stream.write(content) self.close() return return self.stream.read() except OSError as err: sys.stderr.write("[ERR] File Manager: " + err.strerror) except ValueError as err: sys.stderr.write("[ERR] File Manager:") print(err) def close(self): """ close the actual opened file stream """ self.stream.close() @staticmethod def generate_svg_from_xml(): """ Loop through all the xml files that are generated and transform it into an svg diagram using node js package called drawio-batch that is a package wrapper of the draw.io app and launched it using naked toolshed's function execute_js drawio-batch: https://github.com/languitar/drawio-batch Naked toolshed's: https://naked.readthedocs.io/toolshed_shell.html """ print("Converting xml files to pdf") print(subprocess.run(['C:/Program Files/draw.io/draw.io.exe', '--export', '--output=../pdf/', '--format=png', '--crop', '../xml/'], stdout=True))
# -*- coding: utf-8 -*- # AUTHOR = "tylitianrui" class Solution: """ @param a: An integer @param b: An integer @return: The sum of a and b """ def aplusb(self, a, b): # write your code here carry = 1 while carry: s = a ^ b carry = 0xFFFFFFFF & ((a & b) << 1) carry = -(~(carry - 1) & 0xFFFFFFFF) if carry > 0x7FFFFFFF else carry a = s b = carry return a if __name__ == '__main__': solution = Solution() print(solution.aplusb(1, 2)) print(solution.aplusb(1, -2))
def is_sub_without_mistake(trie, sentence): for letter in sentence: if letter == " ": place_in_word = 0 if letter in trie.keys(): trie = trie[letter] else: return [] if "end" in trie: return trie["end"] def intersection(lst1, lst2): return list(set(lst1) & set(lst2)) def get_sentence_by_id(id, data): return data[f"{id}"]["completed_sentence"] def swap_minus_score(letter): minus = [5, 4, 3, 2] return minus[letter] if letter <= 3 else 1 def is_sub(res, sentence): mistake = 0 if len(sentence) > len(res): return 0 for letter in range(len(sentence)): if res[letter] != sentence[letter]: mistake += 1 return mistake == 1 def is_sub_with_one_swap(sentence, intersect, data): correct = [] for id in intersect: res = get_sentence_by_id(id, data) iter = 0 for letter in range(len(res)): while res[iter] != sentence[0]: iter += 1 if is_sub(res[iter+letter:], sentence): correct.append(id) break return correct def update_swap_score(trie, sentence,data, tmp, letter): for item in tmp: if data[f"{item}"]["score"] == 0: data[f"{item}"]["score"] = -swap_minus_score(letter) + len(sentence)*2 if data[f"{item}"]["offset"] == -1: data[f"{item}"]["offset"] = get_offset(trie, sentence[:letter], data[f"{item}"]["completed_sentence"]) def sub_with_swap(trie, sentence, data): res = [] for letter in range( len(sentence) - 1): prefix = is_sub_without_mistake(trie, sentence[:letter]) suffix = is_sub_without_mistake(trie, sentence[letter + 1:]) intersect = intersection(prefix, suffix) if intersect != []: tmp = is_sub_with_one_swap(sentence, intersect, data) if tmp != []: update_swap_score(trie, sentence, data, tmp, letter) res += tmp if len(sentence) > 1: tmp = is_sub_without_mistake(trie, sentence[:len(sentence) - 1]) update_swap_score(trie, sentence, data, tmp, len(sentence) -1) res += tmp tmp = is_sub_without_mistake(trie, sentence[1:]) update_swap_score(trie, sentence, data, tmp, 0) res += tmp return res def delete_insert_minus_score(char): minus = [10, 8, 6, 4] if char <= 3: return minus[char] else: return 2 def update_delete_insert_score_(trie, data, sentence, arr, char): for item in arr: if data[item]["score"] == 0: data[item]["score"] = -delete_insert_minus_score(char) + len(sentence) * 2 if data[item]["offset"] == -1: data[item]["offset"] = get_offset(trie, sentence[:char], data[item]["completed_sentence"]) def do_update_delete_insert_score_(trie,data, sentence, arr, letter): update_delete_insert_score_(trie, data, sentence, arr, letter) return arr def sub_with_delete(trie, sentence,data): res = [] for letter in range(1, len(sentence) - 1): prefix = is_sub_without_mistake(trie, sentence[:letter]) suffix = is_sub_without_mistake(trie, sentence[letter:]) intersect = intersection(prefix, suffix) if intersect: arr = is_sub_with_one_swap(sentence[:letter] + ' ' + sentence[letter:], intersect, data) res += do_update_delete_insert_score_(trie,data, sentence, arr, letter) arr = is_sub_without_mistake(trie, sentence[:len(sentence) - 1]) res += do_update_delete_insert_score_(trie, data, sentence, arr, len(sentence) - 1) arr = is_sub_without_mistake(trie, sentence[1:]) res += do_update_delete_insert_score_(trie, data, sentence, arr, 0) return res def sub_with_insert(data,trie, sentence): res = [] for char in range(len(sentence)): arr = is_sub_without_mistake(trie, sentence[:char] + sentence[char + 1:]) res += do_update_delete_insert_score_(trie, data, sentence, arr, char) return res def get_offset(trie, word, sentence): return sentence.find(word) def update_high_score(trie, founded, data, sentence): for found in founded: data[f"{found}"]["score"] += len(sentence)*2 if data[f"{found}"]["offset"] == -1: data[f"{found}"]["offset"] = get_offset(trie, sentence, data[f"{found}"]["completed_sentence"]) def search_in_tree(trie, sentence, data): founded = [] if len(sentence) > 0: founded += is_sub_without_mistake(trie, sentence) update_high_score(trie, founded, data, sentence) if len(sentence) > 1: if len(founded) < 5: founded += sub_with_swap(trie, sentence, data) if len(founded) < 5: founded += sub_with_delete(trie, sentence, data) if len(founded) < 5: founded += sub_with_insert(data, trie, sentence) return set(founded)
# import pandas as pd """ IE Titanic utils. """ __version__ = "0.1.0" import pandas as pd def tokenize(text, lower=False, remove_stopwords=False, remove_punctuation=False): if lower: text=text.lower() if remove_stopwords: stopwords = ["a", "the", "or", "and"] words= text.split() non_stopwords = [w for w in words if not w.lower() in stopwords] text = " ".join(non_stopwords) if remove_punctuation: punctuation = [".", ",", "!"] for p in punctuation: text = text.replace(p, '') return text.split() if __name__ == "__main__": print(tokenize("Hello World!"))
# -*- coding: utf-8 -*- """ Created on Tue Nov 5 12:56:29 2019 @author: yihua """ import numpy as np array = lambda n=100: list(np.random.randint(1,100,n)) ''' 3. 快速排序 - Quicksort 快速排序的基本思想:通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均 比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。 时间复杂度:O(nlogn) 空间复杂度:O(nlogn) ''' def quick_sort(array):
import tempfile # Create a temporary file and write some date to it fp = tempfile.TemporaryFile() fp.write(b'Hello world') # Read data from file fp.seek(0) print(fp.read()) # Close the file, it will be removed fp.close() # Create a temporary file using a context manager with tempfile.TemporaryFile() as f_p: f_p.write(b'Hello') f_p.seek(0) print(f_p.read()) # File is now closed and removed # Create a temporary directory using context manager with tempfile.TemporaryDirectory() as tmpdirname: print('created temporary directory', tmpdirname) # Directory and contents have been removed
x = int(input("Введите натуральное число: ")) n = "" while x > 0: y = str(x % 2) n = y + n x = int(x / 2) print(y, n, x) print(n)
# -*- coding: utf-8 -*- """ Created on Tue Apr 2 22:45:19 2019 @author: yangq """ #Add argument exercise import argparse parser=argparse.ArgumentParser(description="This is an exercise") parser.add_argument("integer",help="Add an integer",type=int) parser.add_argument("--verbose","-v",action="count",help="print out information") args=parser.parse_args() print(args.integer**2) if args.verbose>=1: print("The process is complicated")
''' automatic operation 1.summation 2.subtraction 3.multiplication 4.Quotient 5.remainder 6.Quotient + remainder ''' x,y = input().split() a = int(x) b = int(y) k = a/b print(a + b) print(a - b) print(a * b) print(a // b) print(a % b) print('%.2f'%(k))
''' find the maximum number of swap in heap sort ''' ''' To find the maxmimum number of swap in heap the smallest integer which is 1 has to be located in the last spot and the maximum value has to be located right next one and change to parent node ''' # Size of heap n = int(input()) # Default size of heap heap = [0,1] # swap the x and y in arr def swap(arr, x, y): temp = arr[x] arr[x] = arr[y] arr[y] = temp # range of heap for i in range(2, n+1): # add new value into the heap array heap.append(i) # swap the value the last element and the right before the last # Because 1 has to be located at the last spot swap(heap, i, i-1) # This is maximum value in the heap # J is location j = i-1 while j != 1: # the maximum value is located at the j # j has to move to the top because this is maximum heap # parent node has to be greater than equal to the child node swap(heap, j, j//2) j = j // 2 # print from index 1 in heap # Because idex 0 is 0. for i in heap[1:]: print(i, end = ' ')
''' The input consists of N cases. The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add. Two integers are less than 100,000,000. ''' # Decide how many input we will be received x = int(input()) for i in range(x): # iterate a, b = input().split() reverse_a = a[::-1] # reversed first input reverse_b = b[::-1] # reversed second input reverse_a = int(reverse_a) # When user type number it is string type so reverse_b = int(reverse_b) # if we want to calculate we have to convert to integer result = reverse_a + reverse_b # calculation result = str(result)[::-1] # reverse result of sum reuslt_final = int(result) # convert to integer to remove zero when zero leads the result #reuslt_final = result.strip('0') # this is another option when zero leads number print(reuslt_final)
''' find hamming distance and DNA which has the smallest hamming distance ''' # two values # x is how many DNA will be typed # y is size of DNA x,y = map(int,input().split()) # Empty list dna = [] # Empty string result = '' hamming_D = 0 for i in range(x): dna.append(input()) for i in range(y): # Becuase we have four dna stem which are ACGT count = [0,0,0,0] # check each column for j in range(x): if dna[j][i] == 'A' count[0] += 1 elif dna[j][i] == 'C' count[1] += 1 elif dna[j][i] == 'G' count[2] += 1 elif dna[j][i] == 'T' count[3] += 1 # Find the largest value in the cnt list # To find the letter and calculate Hamming distance largest_num = max(cnt) #find the location in the cnt list idx = cnt.index(largest_num) if idx == 0: result += 'A' elif idx == 1: result += 'C' elif idx == 2: result += 'G' elif idx == 3: result += 'T' hamming_D += x-largest_num print(result) print(hamming_D)
''' Return bigger number Q1063 ''' def biggerNum(arg1, arg2): a = int(arg1) b = int(arg2) if a > b: print(a) else: print(b) #x,y = input().split() #biggerNum(x,y) ''' Return the smallest number among three different int Q1064 ''' def smallerNum(arg1, arg2, arg3): a = int(arg1) b = int(arg2) c = int(arg3) if a > b: if b > c: print(c) else: print(b) elif a < b: if a < c: print(a) else: print(c) else: print(a) ''' Return even number ''' def evenNum(arg1, arg2, arg3): a = int(arg1) b = int(arg2) c = int(arg3) even = [a,b,c] for i in range(len(even)): if even[i] % 2 == 0: print(even[i]) else: pass ''' Q1066 print as even if number is even print as odd if number is odd ''' def evenOdd(arg1, arg2, arg3): a = int(arg1) b = int(arg2) c = int(arg3) x_list = [a,b,c] for i in range(len(x_list)): if x_list[i] % 2 == 0: print('even') else: print('odd') x,y,z = input().split() #smallerNum(x,y,z) #evenNum(x,y,z) evenOdd(x,y,z)
''' Cutting cable We have K cables but We want to make N cables with same length by using K cable. Find the maximum length of cable to make N cables. input example 4 11 802 743 457 539 output example ''' # import sys # sys.stdin = open('input.txt') def check(a): cnt = 0 for i in num: cnt += ((i // a)) return cnt # a = the number of cable # b = the number of cable that I want to make a,b = map(int, input().split()) num = [] for _ in range(a): x = int(input()) num.append(x) rt = max(num) lt = 1 res = 0 while lt <= rt: mid = (lt + rt) // 2 if check(mid) >= b: res = mid lt = mid + 1 else: rt = mid - 1 print(res)
import numpy as np from scipy import optimize #input data X = np.array(([3,5],[5,1],[10,2]), dtype = float) #output data Y = np.array(([75],[82],[93]), dtype = float) #scaling of the data X = X/(np.amax(X, axis=0)) Y = Y/100.0 class Neural_Network(object): def __init__ (self): #hyperparameters self.inputLayerSize = 2 self.hiddenLayerSize = 3 self.outerLayerSize = 1 self.W1 = np.random.randn(self.inputLayerSize,self.hiddenLayerSize) self.W2 = np.random.randn(self.hiddenLayerSize,self.outerLayerSize) def sigmoid(self,z): return 1.0/(1.0+np.exp(-z)) def sigmoidPrime(self,z): return self.sigmoid(z)*(1-self.sigmoid(z)) def forward (self, X): #propagates input through networks self.z2 = np.dot(X,self.W1) self.a2 = self.sigmoid(self.z2) self.z3 = np.dot(self.a2, self.W2) yHat = self.sigmoid(self.z3) return yHat def costFunction(self, X, Y): #parabolic cost function #also allows to explot convexity of the function self.yHat = self.forward(X) J = 0.5*sum((Y-self.yHat)**2) return J def costFunctionPrime(self, X, Y): #computing derivative with respect to W1 and W2 self.yHat = self.forward(X) delta3 = np.multiply(-(Y-self.yHat), self.sigmoidPrime(self.z3)) dJdW2 = np.dot(self.a2.T, delta3) delta2 = np.dot(delta3, self.W2.T)*self.sigmoidPrime(self.z2) dJdW1 = np.dot(X.T, delta2) return dJdW1, dJdW2 #numerical gradient checking #helper function to interact with other function def getParams(self): #rolling W1 and W2 rolled into a single vector params = np.concatenate((self.W1.ravel(),self.W2.ravel())) return params def setParams(self, params): #set W1 and W2 rolled into vectors W1_start = 0 W1_end = self.inputLayerSize*self.hiddenLayerSize self.W1 = np.reshape(params[W1_start:W1_end], (self.inputLayerSize, self.hiddenLayerSize)) W2_end = W1_end + self.hiddenLayerSize*self.outerLayerSize self.W2 = np.reshape(params[W1_end:W2_end], (self.hiddenLayerSize, self.outerLayerSize)) def computeGradients(self, X,Y): #returns a single vector containg gradients with respect to different weights dJdW1, dJdW2 = self.costFunctionPrime(X, Y) return np.concatenate((dJdW1.ravel(),dJdW2.ravel())) def computeNumericalGradients(self, X, Y): paramsIntial = self.getParams() numgrad = np.zeros(paramsIntial.shape) perturb = np.zeros(paramsIntial.shape) e = 1e-4 #I will perturb each weight one by one and calculate the #corresponding gradient #by the end we will get a vector having numericaly #gradients calculated for p in range(len(paramsIntial)): perturb[p] = e self.setParams(paramsIntial+perturb) loss2 = self.costFunction(X,Y) self.setParams(paramsIntial-perturb) loss1 = self.costFunction(X,Y) numgrad[p] = (loss2-loss1)/(2*e) perturb[p] = 0 self.setParams(paramsIntial) return numgrad def gradCheck(self, X, Y): grad = self.computeGradients(X,Y) numgrad = self.computeNumericalGradients(X,Y) return ((np.linalg.norm(grad-numgrad)/np.linalg.norm(grad+numgrad))<1e-8) class trainer(object): def __init__(self, N): #local refernce to Neural_Network self.N = N #wrapper functions which returns the output which satisfies #the semantics of the minimize function def wrapper(self, params, X, Y): self.N.setParams(params) cost = self.N.costFunction(X, Y) grad = self.N.computeGradients(X,Y) return cost, grad def callbackF(self, params): self.N.setParams(params) self.J.append(self.N.costFunction(self.X, self.Y)) def train(self, X, Y): self.X = X self.Y = Y self.J = [] paramsI = self.N.getParams() options = {'maxiter': 200, 'disp':True} #minimize function from optimize requires a function #as parameter which accepts 2 vectors output and input #and returns the cost function and the gradients _res = optimize.minimize(self.wrapper, paramsI, jac = True, method='BFGS',\ args = (X,Y), options = options, callback = self.callbackF) self.N.setParams(_res.x) self.optimizationResult = _res NN = Neural_Network() T = trainer(NN) T.train(X,Y) y = NN.forward(X) cost1 = NN.costFunction(X,Y) dJdW1,dJdW2 = NN.costFunctionPrime(X,Y) #to demo the effect of moving along and opposite to the gradient #slr = 3.0 #NN.W1 = NN.W1 + slr*dJdW1 #NN.W2 = NN.W2 + slr*dJdW2 #cost2 = NN.costFunction(X,Y) #NN.W1 = NN.W1 - 2*slr*dJdW1 #NN.W2 = NN.W2 - 2*slr*dJdW2 #cost3 = NN.costFunction(X,Y) gradient = NN.computeGradients(X,Y) numGradient = NN.computeNumericalGradients(X,Y) check = NN.gradCheck(X,Y) #to check whether gradients are calculated correctly print("X is:",X) print("prediction is:",y) print("cost1 is:",cost1) #print("cost2 is:",cost2) #print("cost3 is:",cost3) print("gradient is:", gradient) print("Numerical Gradient is:", numGradient) print("check passed:", check) print("W1 is:",NN.W1) print("W2 is:",NN.W2)
# return a dictionary with squares as the keys and the square value of the values as the values squares = ["one", "two", "three", "four", "five"] values = [1, 2, 3, 4, 5] def number_square(squares, values): squares1 = {} for x, y in zip(squares, values): squares1[x] = y **2 return squares1 def main(): print(number_square(squares, values)) main()
# (Fill in the Missing Code?) Replace the ***s in the seconds_since_midnight function so that # it returns the number of seconds since midnight. The function should receive # three integers representing the current time of day. Assume that the hour is a value from # 0 (midnight) through 23 (11 PM) and that the minute and second are values from 0 to 59. # Test your function with actual times. For example, if you call the function for 1:30:45 PM # by passing 13, 30 and 45, the function should return 48645. # def seconds_since_midnight(***): # hour_in_seconds = *** # minute_in_seconds = *** # return *** # def seconds_since_midnight( seconds): # hour_in_seconds = (hour) # minute_in_seconds = (minutes) # # my_list = [2,3,6,8] # # for element in my_list: # # print( element ,end= ' ') # # my_list[0] = (27) # print # chidi_list = "chidi is a software engineer".split() # string_elements = chidi_list.split() # print(chidi_list) # reversed_elements = [] # for elements in string_elements: # reversed_elements.append{elements[::-1]} # name = ['chidi', 'james', 'chike', 'damilola'] # print # write a Python function (pig_latin) that takes a string as input, # assumed to be an English word. The function should return the translation of this word # into Pig Latin. You may assume that the word contains no capital letters or punctuation. # def pig_latin(word): # if word[0] in 'aeiou': # return f'{word}way' # return f'{word[1:]}{word[0]}ay' # # print(pig_latin('python')) # mylist = ['orange', 'mango', 'apple', 'guava'] # print(mylist[:-1]) # t = (10, 20, 30, 40 ,50) # # first = t[1:3] # last = t[3:5] # # print(first, last) # Given that we’re trying to retrieve the first and last elements of sequence and then # join them together, it might seem reasonable to grab them both (via indexes) and # then add them together: # def first_last(sequence): # return sequence[:1] + sequence[-1:] # t1 = ('chidi', 'janes', 'gideon', 'mark') # names = first_last(t1) # print(f'{names}') # # t2 = (1,2,3,4,27) # numbers = first_last(t2) # print(numbers)me # number guessing game import random # def guessing_game(): # answer = random.randint(0,50) # # while True: # user_guess = int(input("Guess a number?")) # if user_guess == answer : # print(f'Correct! The answer is {user_guess}' ) # break # # if user_guess < answer : # print(f'Your guess of{user_guess} is too low') # # # else: # print(f'your guess of{user_guess} is too high') # # # guessing_game()
# 3.6 (Turing Test) The great British mathematician Alan Turing proposed a simple test # to determine whether machines could exhibit intelligent behavior. A user sits at a computer and does the same text chat with a human sitting at a computer and a computer operating by itself. The user doesn’t know if the responses are coming back from the human # or the independent computer. If the user can’t distinguish which responses are coming # from the human and which are coming from the computer, then it’s reasonable to say that # the computer is exhibiting intelligence. # Create a script that plays the part of the independent computer, giving its user a simple medical diagnosis. The script should prompt the user with 'What is your problem?' # When the user answers and presses Enter, the script should simply ignore the user’s input, # then prompt the user again with 'Have you had this problem before (yes or no)?' If # the user enters 'yes', print 'Well, you have it again.' If the user answers 'no', print # 'Well, you have it now.' # Would this conversation convince the user that the entity at the other end exhibited # intelligent behavior? Why or why not? user1 = str(input("what is your problem?")) # print(user1) user1 = input("have you got this problem before(yes or no?)") if user1 == "yes": print("well you have it again") elif user1 == 'no': print("well you have it now")
from Calculator import * def run_test(): """test all the functions""" assert add(2, 3) == 5, "2 + 3 is 5" assert subtract(2, 3) == -1, "2 - 3 is -1" assert multiply(2, 3) == 6, "2 * 3 is 6" assert division(6, 3) == 2, " 6 / 3 is 2" assert square_root(9) == 3, "square_root of 9 is 3" assert square(2) == 4, "square of two is 4" if __name__ == "_main_": run_test()
import random board = [" "]*9 winners = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7,], [2,5,8], [0,4,8], [2,4,6]] xwin = 0 owin = 0 catwin = 0 userRecord = 0 compRecord = 0 catRecord = 0 def userPick(): while True: loc = input("Pick a square (1-9): ") try: int(loc) except Exception: print("Invalid Input") else: loc = int(loc) if loc < 1 or loc > 9: print("Out of Range") elif board[loc-1] != ' ': print("This square is taken, try a different one") else: return loc-1 def randPick(): while True: loc = random.randint(0,8) if board[loc] == ' ': return loc def print_board(): print(" %c | %c | %c " % (board[0], board[1], board[2])) print("___|___|___") print(" %c | %c | %c " % (board[3], board[4], board[5])) print("___|___|___") print(" %c | %c | %c " % (board[6], board[7], board[8])) print(" | | ") def check_win(): global xwin, owin for i in winners: xscore = 0 oscore = 0 for j in i: if board[j] == 'X': xscore += 1 if board[j] == 'O': oscore += 1 if xscore == 3: xwin = 1 if oscore == 3: owin = 1 def check_cat(): global catwin n = 0 for i in board: if i != ' ': n += 1 if n == 9: catwin = 1 def smartPick(): for row in winners: oscore = 0 for i in row: if board[i] == 'O': oscore += 1 if oscore == 2: for loc in row: if board[loc] == ' ': return loc for row in winners: xscore = 0 for i in row: if board[i] == "X": xscore += 1 if xscore == 2: for loc in row: if board[loc] == ' ': return loc return randPick() def gameReset(): global board, xwin, owin, catwin board = [' ']*9 xwin = 0 owin = 0 catwin = 0 while True: order = random.randint(0,2) if order != 1: print("User plays first") while xwin == 0 and owin == 0: print_board() board[userPick()] = 'X' check_win() if xwin == 1: break check_cat() if catwin == 1: break print("Computer move:") board[smartPick()] = 'O' check_win() if owin == 1: break else: print("Computer plays first") while xwin == 0 and owin == 0: board[smartPick()] = 'O' check_win() if owin == 1: break check_cat() if catwin == 1: break print_board() board[userPick()] = 'X' check_win() if xwin == 1: break print_board() print() if owin == 1: print("O has won") compRecord += 1 elif xwin == 1: print("X has won") userRecord += 1 else: print("The cat has won") catRecord += 1 print("You are %s-%s-%s" % (userRecord, compRecord, catRecord)) gameReset() replay = input("Type anything to play again or 'q' to quit: ") if replay.upper() == 'Q': quit()
nombre = input("Ingrese un nombre :") verbo = input("Ingrese verbo :") advervio = input("Ingrese advervio :") adjetivo = input("Ingrese adjetivo :") if verbo == "matar" or "ejecutar" or "eliminar": historia2 = ("Miles de años llevan los gatos preparando la conquista del planeta.\n" "Han sido laboriosos los esfuerzos por encontrar las debilidades de otras espécies.\n" "{},el lider supremo ha convocado una reunión extraordinaria\n" "Después de la reunión del Clan de la Zarpa de este año salieron dos conclusiones :\n" "1:Se determina una acción contra la raza humana :{}\n" "Cuando se decida {}, la acción 1 se pasará a fase 2: la asignación del agente\n" "el designado será Executus al ser el más {}. Comienza el extermínio".format(nombre,verbo,advervio,adjetivo)) print("-------------------------------------------") print("\n") print(historia2) print("\n") print("-------------------------------------------") else: historia = ("Miles de años llevan los gatos preparando la conquista del planeta.\n" "Han sido laboriosos los esfuerzos por encontrar las debilidades de otras espécies.\n" "{},el lider supremo ha convocado una reunión extraordinaria\n" "Después de la reunión del Clan de la Zarpa de este año salieron dos conclusiones :\n" "1:Se determina una acción contra la raza humana :{}\n" "Cuando se decida {}, la acción 1 se pasará a fase 2: la asignación de agentes\n" "2:Los designados para el comienzo de tal función son Executus y Apocalipsis\n" "El que tomará las decisiones será Executus al ser el más {}".format(nombre,verbo,advervio,adjetivo)) print("-------------------------------------------") print("\n") print(historia) print("\n") print("-------------------------------------------")
import operator def binaryBytesToHex(byteString) -> str: return hex(int("".join([str(b) for b in byteString]), 2)) def hamming(str1, str2): assert len(str1) == len(str2) # ne = str.__ne__ ## this is surprisingly slow ne = operator.ne return sum(map(ne, str1, str2))
import csv from itertools import zip_longest #Create rows row_one = [1,2,3,4,5,6,7,8,9,10] row_two = [11,12,13,14,15,16,17,18,19,20] combined_list = [] combined_list.append(row_one) combined_list.append(row_two) print(combined_list) #zip longest is used for transpose of a column data = zip_longest(*combined_list) #Save in a file the values with open('new_file.csv', 'w', newline='') as f: wr = csv.writer(f) wr.writerows(data) print('\nFile written successfully') f.close()
class ListNode: def __init__(self, x): self.value = x self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: # 利用快慢指针确定是否存在环 # 遍历改变节点的值 slow = fast = head while fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: return True return False def main(): head = [3, 2, 0, -4] pos = 1 start = frontNode = ListNode(head[0]) for i, num in enumerate(head[1:]): tempNode = ListNode(num) frontNode.next = tempNode frontNode = frontNode.next cycleNode = start for i in range(pos): cycleNode = cycleNode.next if pos: frontNode.next = cycleNode a = Solution() print(a.hasCycle(start)) if __name__ == '__main__': main()
"""" Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays """ from typing import * class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: k1 = (len(nums1) + len(nums2) + 1) // 2 k2 = (len(nums1) + len(nums2) + 2) // 2 def helper(nums1, nums2, k): if len(nums1) < len(nums2): # 保证nums2为较短的数组 nums1, nums2 = nums2, nums1 if len(nums2) == 0: return nums1[k-1] if k == 1: return min(nums1[0], nums2[0]) t = min(k//2, len(nums2)//2) if nums1[t-1] <= nums2[t-1]: return helper(nums1[t:], nums2, k-t) else: return helper(nums1, nums2[t:], k-t) return (helper(nums1, nums2, k1) + helper(nums1, nums2, k2)) / 2 sol = Solution() result = sol.findMedianSortedArrays([1,3,5,6,7,23], [2,54,102]) print(result)