text
stringlengths
37
1.41M
""" Design a class called Sentence that has a constructor that takes a string representing the sentence as input. The class should have the following methods: get_first_word(): returns the first word as a string get_all_words(): returns all words in a list. replace(index, new_word): Changes a word at a particular index to "new_word". For example, if sentences is "I'm going back", then replace(2, "home") results in "I'm going home". If the index is not valid, the method does not do anything. """ class Sentence(object): def __init__(self, sentence=""): self.__sentence = sentence def get_first_word(self): a = self.__sentence.split() return a[0] def get_all_words(self): return self.__sentence.split() def replace(self, index, new_word): word = self.__sentence.split() word[index] = new_word self.__sentence = " ".join(word) return self.__sentence sent = Sentence('This is a test') print(sent.get_first_word()) assert str(sent.get_first_word()) == "This" print(sent.get_all_words()) assert sent.get_all_words() == 'This is a test'.split() sent.replace(3, "must") print(sent.get_all_words()) assert sent.get_all_words() == 'This is a must'.split()
def size(i: int): value = [] for x in range(i): value.append(input("Enter some value: ")) return value def check_target(value): v = [] for z in value: if z not in v: v.append(z) return v s = size(int(input("Enter size of list: "))) print(check_target(s))
def size(i: int): value = [] for x in range(i): value.append(input("Enter some value: ")) return value def check_target(x, value): if x in value: v = x + " is in the list" else: v = x + " is not in the list" return v s = size(int(input("Enter size of list: "))) print(check_target(input("Search for target: "), s))
# ch03 # The Boston Housing Price dataset (p.92) from keras.datasets import boston_housing (train_data, train_targets), (test_data, test_targets) = boston_housing.load_data() # Preprocessing mean = train_data.mean(axis=0) train_data -= mean std = train_data.std(axis=0) train_data /= std test_data -= mean test_data /= std # Building our network (p.93) # In general, the less training data you have, the worse overfitting will be. # Using a small network is one way to mitigate overfitting. from keras import models from keras import layers def build_model(): model = models.Sequential() model.add(layers.Dense(64, activation='relu', input_shape=(train_data.shape[1], ))) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(1)) # No activation function required for the output layer model.compile(optimizer='rmsprop', loss='mse', metrics=['mae']) return model # Validating our approach using k-fold cross-validation (p.94) import numpy as np k = 4 num_val_samples = len(train_data) // k all_scores = [] for i in range(k): print('processing fold #', i) # prepare the validation data: data from partition # k val_data = train_data[i * num_val_samples: (i + 1) * num_val_samples] val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples] # prepare the training data: data from all other partitions partial_train_data = np.concatenate( [train_data[: i * num_val_samples], train_data[(i + 1) * num_val_samples:]], axis=0 ) partial_train_targets = np.concatenate( [train_targets[: i * num_val_samples], train_targets[(i + 1) * num_val_samples:]], axis=0 ) # build the Keras model (already compiled) model = build_model() model.fit(partial_train_data, partial_train_targets, epochs=100, batch_size=1) # evaluate the model on the validation data val_mse, val_mae = model.evaluate(val_data, val_targets) all_scores.append(val_mae)
#! usr/bin/env python # -*- coding: utf-8 -*- from numpy import * import operator import matplotlib import matplotlib.pyplot as plt ''' r:读 rb: 读二进制文件 ''' def file2matrix(fileName): fr = open(fileName) arrayOLines = fr.readlines() #用 readlines() 一次读取所有内容并按行返回 list numerOfLines = len(arrayOLines) #行数 returnMat = zeros((numerOfLines,3)) #创建一个 numerOfLines行 ,3列的二维数组(就是一个矩阵),0 classLabelVector = [] index = 0 for line in arrayOLines: line = line.strip() # 去掉末尾的换行符, listFromLine = line.split('\t') #split() 切割 \t代表是一个tab键值,就是8位,具体空格的个数,跟你的数值有关系,比如你的字符串是abc,加个\t,则空格是5个,如果字符串是abcde,加\t,则空格是3个 returnMat[index,:] = listFromLine[0:3] #获取 0,1,2三个字符串元素 ,[index: ],表示到最大一个 classLabelVector.append(int(listFromLine[-1])) index += 1 return returnMat,classLabelVector datingDataMat, datingLabels = file2matrix("/Users/Encore/Desktop/Python3.0/Python/Machine_Learning/datingTestSet2.txt") print datingDataMat print datingLabels[0: 20] fig = plt.figure() ax = fig.add_subplot(111) #将画布分为1行1列,即一块大的,(349)表示将画布分3行4列共12块,9表示12块的第九块,即左下角那块 print type(ax) ax.scatter(datingDataMat[:,1], datingDataMat[:, 2]) plt.show()
#!/usr/bin/env python # -*- coding:utf-8 -*- #函数中的可变参数 #定义可变参数,在参数前面加一个* ,此时可以传入list 或者tupe def cale (*number): sum = 0 for n in number: sum += n*n return sum print cale(1,2) #传入的是一个元祖,省略了() # 2. 如果已经有一个list 或者tupe 需要作为参数传进去,则按照如下调用,且是非常常见 ,当然也可以还原为tupe形式 list1 = [1,2,3] print cale(*list1) # 3. 关键字参数: 自动组装0个或任意个参数名的参数,关键字参数在函数内部,自动组装为字典 def person(name, age, **kw): print "name:", name, "age:", age, "other", kw #解析上面方法: name, age, 为必选参数,kw为关键字参数(可任意多个字段),带** person("xiaoming",18) person("xiaoming",18,city = "guangzhou", sex = "man", work = "doctor") # 当然 也可以直接传一个字典,但要在前面加** dic1 = {"city" : "guangzhou", "sex": "man", "work": "doctor", "father": "army"} person("xiaowang", 27, **dic1) #参数组合:在函数参数中 可以同时使用 必选参数,默认参数,可变参数,关键字参数,但是在定义时,必须按照:必选参数,默认参数,可变参数,关键字参数 这个顺序来定义。 def func(a, b, c = 0, *args, **kw): print "a=", a, "b=", b, "c=", c, "args=", args, "kw=", kw func(1,2) func(1,2,3) func(1,2,3,"a","b") func(1,2,3,"a","b",cc="x") #最神奇的是你可以通过一个 tupe 和dict 调用这儿func list2 = (1,2,3,4,5) dict2 = {"x": "a", "y": "b"} func(*list2, **dict2) #* 第二章:递归 def fac(n): if n == 1: return 1 return n * fac(n-1) print fac(10) # 尾随递归 def fact(n): return fact_iter(n, 1) def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1,num * product) print fact(5)
def questao1(): return 5**2,9*5,15/12,12/15,15//12,12//15,5%2,9%5,15%12,12%15,6%6,0%7 def questao2(): return '5 da tarde' def questao3(): a=int(input('Digite a hora atual: ')) b=int(input('Digite daqui a quantas horas o alarme deverá tocar: ')) desp=(a+b)%24 if desp>24: desp=desp%24 return print('O alarme tocará às {}h'.format(desp)) def questao4(): a=int(input('Digite o dia inicial: ')) b=input('Digite o dia da semana: ') c=int(input('Digite quantos dias ficará de férias: ')) dias = ('Segunda','Terça','Quarta','Quinta','Sexta','Sábado','Domingo') ds=dias.index(b) #dr=(a+c)%30 dsr=c%7 dsf=ds+dsr while dsf>=7: dsf=dsf%7 return print('o retorno das férias será:',dias[dsf]) def questao5(): a='Só' b='trabalho' c='sem' d='diversão' e='faz' f='de' g='João' h='em' i='chato' return print(a,b,c,d,f,g,h,i) def questao6(): x=6 * (1 - 2) return print('6*(1-2) =',x) def questao7(): t=float(input('Digite a quantidade de anos: ')) A=10000*((1+(0.08/12))**(12*t)) return print('O valor final é: {:.2f}'.format(A)) def questao8(): r=float(input('Digite o raio do círculo: ')) a=3.14*(r**2) return print('A área do círculo de raio',r,'é:',a) def questao9(): a=float(input('Digite altura do retângulo: ')) b=float(input('Digite largura do retângulo: ')) return print('A área do retangulo é:',a*b) def questao10(): km=float(input('Digite a quilometragem percorrida: ')) l=float(input('Digite a quantidade de litros consumido: ')) c=km/l return print('O consumo de gasolina é de: {:.2f}Km/l'.format(c)) def questao11(): c=float(input('Digite a temperatura em ºC: ')) f=(1.8*c)+32 return print('{}ºC em Fahrenheit é: {:.2f}ºF'.format(c,f)) def questao12(): f=float(input('Digite a temperatura em ºF: ')) c=(f-32)/1.8 return print('{}ºF em Celsius é: {:.2f}ºC'.format(f,c))
# ---------- # Given a car in grid with initial state init. # Compute the car's optimal path to the position to the goal. # The costs are given for each motion. # # There are four motion directions: up, left, down, and right. # Increasing the index in this array corresponds to making a # a left turn, and decreasing the index corresponds to making a # right turn. forward = [[-1, 0], # go up [ 0, -1], # go left [ 1, 0], # go down [ 0, 1]] # go right forward_name = ['up', 'left', 'down', 'right'] # action has 3 values: right turn, no turn, left turn action = [-1, 0, 1] action_name = ['R', '#', 'L'] # EXAMPLE INPUTS: # grid format: # 0 = navigable space # 1 = unnavigable space grid = [[1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 1, 1], [1, 1, 1, 0, 1, 1]] init = [4, 3, 0] # given in the form [row, col, direction] # direction = 0: up # 1: left # 2: down # 3: right goal = [2, 0] # given in the form [row, col] cost = [2, 1, 20] # cost has 3 values, corresponding to making # a right turn, no turn, and a left turn # EXAMPLE OUTPUT: # calling optimum_policy2D with the given parameters should return # [[' ', ' ', ' ', 'R', '#', 'R'], # [' ', ' ', ' ', '#', ' ', '#'], # ['*', '#', '#', '#', '#', 'R'], # [' ', ' ', ' ', '#', ' ', ' '], # [' ', ' ', ' ', '#', ' ', ' ']] # ---------- def optimum_policy2D(grid,init,goal,cost): value = [ [[float('inf') for col in range(len(grid[0]))] for row in range(len(grid))], [[float('inf') for col in range(len(grid[0]))] for row in range(len(grid))], [[float('inf') for col in range(len(grid[0]))] for row in range(len(grid))], [[float('inf') for col in range(len(grid[0]))] for row in range(len(grid))], ] policy = [[' ' for col in range(len(grid[0]))] for row in range(len(grid))] changed = True while changed: changed = False for r in range(len(grid)): for c in range(len(grid[0])): for i in range(len(forward)): if r == goal[0] and c == goal[1] and value[i][r][c] > 0: value[i][r][c] = 0 changed = True for k in range(len(action)): current_cost = value[i][r][c] o2 = (i + action[k]) % 4 y2 = r + forward[o2][0] x2 = c + forward[o2][1] if x2 >= 0 and x2 < len(grid[0]) and y2 >= 0 and y2 < len(grid) and grid[r][c] != 1: new_cost = cost[k] + value[o2][y2][x2] if new_cost < current_cost: value[i][r][c] = new_cost changed = True policy[goal[0]][goal[1]] = '*' nodes = [init] while nodes: node = nodes.pop() y = node[0] x = node[1] o = node[2] current_cost = value[o][y][x] mincost = float('inf') for k in range(len(action)): o2 = (o + action[k]) % 4 y2 = y + forward[o2][0] x2 = x + forward[o2][1] if x2 >= 0 and x2 < len(grid[0]) and y2 >= 0 and y2 < len(grid): next_cost = value[o2][y2][x2] if next_cost < current_cost: policy[y][x] = action_name[k] nodes.append([y2, x2, o2]) return policy if __name__ == '__main__': o = optimum_policy2D(grid, init, goal, cost) for r in o: print(r)
"""hackathon communitea functions""" from typing import List, Tuple, Dict, TextIO popup_msg = 'Incorrect username or password. Please try again, or sign up.' user_list = {} cups_of_types = {} English_breakfast = {} # def sign_up def welcome_page(username: str, password: str) -> None: """ Admit users with existing usernames and correct passwords. >>> welcome_page('guest-user', 'password') >>> welcome_page('user--', 'psw---') 'Incorrect username or password. Please try again, or sign up.' """ if user_list[username] == passcode: return int #use that int to enact the user homepage later else: return popup_msg def tea_log(tea_type: str) -> None: """ Keep track of how many cups of each type of tea a user has had. >>> tea_log('TWINING Chai') >>> tea_log('TWINING English breakfast') """ if tea_type in cups_of_types: cups_of_types[tea_type] += 1 else: cups_of_types[tea_type] = 1 def review_tea (tea_cate: dict, username: str, stars: int) -> None: """ Add a user's review to a dictionary that represents a category of tea. >>> English_breakfast {'user01': 3, 'user08': 4} >>> review_tea(English_breakfast, 'guest-user', 4) >>> English_breakfast {'user01': 3, 'user08': 4, 'guest-user': 4} """ tea_cate[username] = stars
#!/usr/bin/python3 Binary_Node = __import__("binary_tree_node").Binary_Node class Binary_Tree_Travel: """create a nice looking printing when travelling""" def __init__(self): self.root = None def inorder_array(self, node, lis=[]): if node.left_node is not None: self.inorder_array(node.left_node, lis) lis.append(node.number) if node.right_node is not None: self.inorder_array(node.right_node, lis) return lis def queue_levelorder(self, node, lis1=[], lis2=[]): if node.parent_node is None: lis1 += list([node]) if lis1 != []: lis2 += list([(lis1.pop(0)).number]) if node.left_node is not None: lis1 += list([node.left_node]) if node.right_node is not None: lis1 += list([node.right_node]) if lis1 != []: self.queue_levelorder(lis1[0], lis1, lis2) return (lis2) def print_heap(self, node): lis = self.queue_levelorder(node) i = 0; row = 1; col = 1; idx = 0; ct = 0 temp_max = 1; check = 1; max = lis[0]; min = lis[0] max_digit = 1; count = 0; j = 0 for el in lis: if max < el: max = el if min > el: min = el # compare max with min if max <= (min * -1): max = (min * -1) * 10; count += 1 # find the count of digit and max_digit will be printing while max_digit < max: max_digit *= 10 count += 1 max_digit /= 10 # calculate row and co that it will be printing i = 0 while i < len(lis): row += 1 i = (i * 2) + 1 row -= 1 i = (i - 1) / 2 col = i * 2 + 1 #print the dash / number depending on position # print("COUNT IS {}", format(count)) while row > 0: check = 1 ct = 1; j = 0 while ct <= col and idx < len(lis): if ct % (i + 1) == 0 and check == 1: print("[{}".format(lis[idx]), end='') temp_max = max_digit j = count while int(temp_max / (lis[idx] + 1)) != 0: temp_max /= 10 j -= 1 if lis[idx] < 0: j += 1 while j < count: print(" ", end='') j += 1 print("]", end='') idx += 1 check = 0 elif ct % (i + 1) == 0 and check == 0: j = 0 while j < count: print("-", end='') j += 1 check = 1 else: j = 0 while j < count + 1: print("-", end='') j += 1 ct += 1 print("") row -= 1 i = (i - 1) / 2 return lis def print_preorder(self, node): """print the tree follow pre_order method""" if node is None: return else: print(node.number) self.print_preorder(node.left_node) self.print_preorder(node.right_node) def print_inorder(self, node): """print the tree follow in_order method""" if node is None: return else: self.print_inorder(node.left_node) print(node.number) self.print_inorder(node.right_node) def print_postorder(self, node): """print the tree follow pre_order method""" if node is None: return else: self.print_postorder(node.left_node) self.print_postorder(node.self_node) print(node.number)
#!/usr/bin/python3 def complex_delete(a_dictionary, value): del_key = [] for k, v in a_dictionary.items(): if v == value: del_key += [k] for k in del_key: a_dictionary.pop(k) return a_dictionary
class Status: def __init__(self, size, stat_arr=[], stat_comb = []): self.stat_arr = stat_arr self.stat_comb = stat_comb self.size = size def return_comb(self): """create a combination of Queen location""" comb = [] for y in range(self.size): for x in range(self.size): if self.stat_arr[y][x] == -5: comb += [[y, x]] if len(comb) == self.size: #self.stat_comb += [comb] self.stat_comb += [str(comb)] def print_graphic(self, col): """print combination as shown on chess board uncomment line 15, 49 and comment out line 16, 48 to print """ lis = [] l = len(self.stat_comb) rows = l // col if l % col == 0 else l // col + 1 r = 0 for row in range(rows): r = row * col + col if row * col + col < l else l print("-" * ((self.size * 2 + 5) * col - 4)) for y in range(self.size): for i in range(row * col, r): lis = ["| " * self.stat_comb[i][y][1]] + ["|Q"] + ["| " * (self.size - self.stat_comb[i][y][1] - 1)] + ["|"] if i != col - 1: lis += [" "] print("".join(lis), end='') print("") print("-" * ((self.size * 2 + 5) * col - 4)) def back_status(self, queen): """the function will go back previous status and set that time queen position to y-direction value""" for y in reversed(range(self.size)): for x in reversed(range(self.size)): if self.stat_arr[y][x] >= queen.pos_y: self.stat_arr[y][x] = 0 if self.stat_arr[y][x] == -5: if y == 0 and x == self.size - 1: """when no more combination, the program will be exit""" print("\n".join(self.stat_comb)) #self.print_graphic(6) exit() else: self.stat_arr[y][x] = queen.pos_y queen.pos_y = y queen.pos_x = x queen.number -= 1 return
sample_dict = { "name": "Kelly", "age":25, "salary": 8000, "city": "New york" } keys_to_remove = ["name", "salary"] for key in keys_to_remove: if key in sample_dict: del sample_dict[key] print(sample_dict)
# username = input("Enter your username: ") # password = input("Enter your password: ") # plength= len(password) # password_block= plength*'*' # print(f'{username}, your password {password_block}, is {plength} charecters long') # school = {'Bobby','Tammy','Jammy','Sally','Danny'} # attendance_list = ['Jammy', 'Bobby', 'Danny', 'Sally'] # for name in school: # if name not in attendance_list: # print(name) some_list = ['a','b','c','b','d','m','n','n'] duplicates = list(set([i for i in some_list if some_list.count(i)>1 ])) print(duplicates)
# Ex 1 # li1 = [1,2,3,4,5] # li2 = [6,7,8,9] # for i in li2: # li1.append(i) # print(li1) # joint_ist = [*li1,*li2] # print (joint_ist) # Ex 2 # number = [] # number.append(input("Input the 1st number: ")) # number.append(input("Input the 2nd number: ")) # number.append(input("Input the 3rd number: ")) # print(f'The greatest number is: {max(number)}') ## Ex 3 # string ='abcdefghijklmnopqrstuvwxyz' # vowels = ['a','e','i','o','u'] # for i in string: # if i in vowels: # print('Vowel') # else: # print('Constanet') # # Ex 4 # name = input("Whats your name? ") # names = ['Samus', 'Cortana', 'V', 'Link', 'Mario', 'Cortana', 'Samus'] # if name in names: # print(names.index(name)) # else: # print('Name not in list.') # # Ex 5 # word_list=[] # count= 0 # while count<7: # word_list.append(input('Enter a word: ')) # count +=1 # letter = input("Enter a letter: ") # for word in word_list: # if letter in word: # print(f'Index of "{letter}" in "{word}" is {word.index(letter)}') # else: # print(f'Sorry "{letter}" is not in "{word}"') # # Ex 6 # import time # number_list=[] # for number in range(0,10000001): # number_list.append(number) # print(min(number_list)) # print(max(number_list)) # time_start = time.perf_counter() # addition = sum(number_list) # time_end = time.perf_counter() # print(addition) # print(time_end-time_start) # # Ex 7 # string = input("Enter a list of numbers sperated by a comma: ") # li = string.split(",") # tup = tuple(li) # print(li) # print(tup) # Ex 8 import random flag = True win = 0 loss = 0 while flag is True: user_num = input("Enter a number between 0-9 or q to quit:") comp_num = random.randint(0,9) if user_num =='q': flag = False elif int(user_num) == comp_num: win+=1 print('Winner!!') print(comp_num) else: loss+=1 print(comp_num) print('Looser') print(f'Wins: {win}') print(f'Losses: {loss}')
sen = input("Enter a sentance: ") letter = input("Enter a Letter: ") print(f'{letter} apperares {sen.count(letter)} times')
TICKET_PRICE = 10 SERVICE_CHARGE = 2 ticket_remaining = 100 def calc_price(numer_of_tickets): return (TICKET_PRICE * numer_of_tickets)+SERVICE_CHARGE while ticket_remaining >= 1: print ("There are {} tickets remaing".format(ticket_remaining)) name = input("What is your name?: ") ticket_amount = input("How many tickets would you like to purchse?: ") try: ticket_amount = int(ticket_amount) if ticket_amount > ticket_remaining: raise ValueError("There are only {} tickets remaining".format(ticket_remaining)) except ValueError as err: print("Invalid! Sorry not enough tickets. {}".format(err)) else: total = calc_price(ticket_amount) print("Thank you {}. Your are total for {} tickets will be ${}".format(name, ticket_amount, total)) proceed = input("Would you like purchase your tickets? (yes or no): ") if proceed.lower() == "yes": print("sold") ticket_remaining = ticket_remaining - ticket_amount else: print("Thank You {}, come again!".format(name)) print("Sorry All Sold Out")
class Node: def __init__(self): self.id = "" self.connected = [] self.x = 0 self.y = 0 self.coordinates = [self.x,self.y] class Edge: def __init__(self): self.connects = [] self.w = 0 self.direction = [] self.x = 0 self.y = 0 self.coordinates = [self.x,self.y] """ Make a game of the Dijkstra algorithm """ import pygame from pygame.locals import * def main(): pygame.init() screen = pygame.display.set_mode((250,250)) pygame.display.set_caption("Dijkstra Game") background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((250,250,250)) # Display some text font = pygame.font.Font(None, 36) text = font.render("Hello There", 1, (10, 10, 10)) textpos = text.get_rect() textpos.centerx = background.get_rect().centerx background.blit(text, textpos) # Blit everything to the screen screen.blit(background, (0, 0)) pygame.display.flip() # Event loop while 1: for event in pygame.event.get(): if event.type == QUIT: return screen.blit(background, (0, 0)) pygame.display.flip() if __name__ == '__main__': main()
import random choice = ["Rock","Paper","Scissors"] def computer_choice(): return random.choice(choice) def player_pick(): i=input() if int(i) < 4 and int(i) > 0: return choice[i-1] def main(): print(computer_choice()) if __name__ == '__main__': main()
camel_word = input() snake_word = "" for char in camel_word: if char.islower(): snake_word += char elif char.isupper(): snake_word += "_" + char.lower() print(snake_word)
x = float(input()) y = float(input()) if (x > 0) and (y > 0): print("I") elif (x < 0) and (y > 0): print("II") elif (x < 0) and (y < 0): print("III") else: print("IV")
cafe = [] cats = [] while True: user_input = input() if user_input == 'MEOW': break else: cat_cafe = user_input.split() cafe.append(cat_cafe[0]) cats.append(int(cat_cafe[1])) max_nb_of_cats = (cats.index(max(cats))) print(cafe[max_nb_of_cats])
def factorial(number): return number * factorial(number - 1) if number > 1 else 1 def fibo(posinfibo): if posinfibo > 2: return fibo(posinfibo - 1) + fibo(posinfibo - 2) else: return 1
import turtle window = turtle.Screen() window.setup(width=800, height=600) window.bgcolor('black') window.tracer(0) #Our Game Objects #Balls balls = int(input('Set difficulty:')) for i in range(0, balls): ball[] = turtle.Turtle() ball.color('green') ball.shape('circle') ball.penup() ball.speed(0) ball.dx = 0.2 ball.dy = 0.2 #The Game Loop while True: window.update() ball.sety(ball.ycor() + ball.dy) ball.setx(ball.xcor() + ball.dx) #Bouncing off if ball.ycor() > 270: ball.sety(270) ball.dy *= -1 if ball.xcor() > 350: ball.setx(350) ball.dx *= -1 if ball.ycor() < -270: ball.sety(-270) ball.dy *= -1 if ball.xcor() < -370: ball.setx(-370) ball.dx *= -1
import numpy as np def mult_matrix(m1, m2): ''' check if the matrix1 columns = matrix2 rows mult the matrices and return the result matrix print an error message if the matrix shapes are not valid for mult and return None error message should be "Error: Matrix shapes invalid for mult" ''' result = [] k = [] for i in range(len(m1)): # iterate through columns of Y for j in range(len(m2[0])): # iterate through rows of Y for k in range(len(m2)): result[i][j] += m1[i][k] * m2[k][j] for i in result: k.appen(i) return k def add_matrix(m1, m2): ''' check if the matrix shapes are similar add the matrices and return the result matrix print an error message if the matrix shapes are not valid for addition and return None error message should be "Error: Matrix shapes invalid for addition" ''' # for i in m1: # for j in m2: k = [i + j for x, y in zip(m1, m2) for i,j in zip(x, y)] if (len(m1[0]) == len(m2[0])): return [k[x:x+len(m1[1])] for x in range(0,len(k),len(m1[1]))] print('Error: Matrix shapes invalid for addition' ) return None def read_matrix(): ''' read the matrix dimensions from input create a list of lists and read the numbers into it in case there are not enough numbers given in the input print an error message and return None error message should be "Error: Invalid input for the matrix" ''' n = input().split(',') rows = int(n[0]) columns = int(n[1]) matrix = [] for row in range(rows): l = input().split(' ') if len(l) == rows: matrix.append([int(i) for i in l]) else: print("Error: Invalid input for the matrix") return None return matrix def main(): # read matrix 1 m1 = read_matrix() # add matrix 1 and matrix 2 if m1 is None: exit() # read matrix 2 m2 = read_matrix() if m2 is None: exit() print(add_matrix(m1, m2)) #print(mult_matrix(m1, m2)) # multiply matrix 1 and matrix 2 if __name__ == '__main__': main() # from numpy import * # x = int(input()) # y = reshape(x,(2,2)) # print(y)
''' @author:navin106 # Exercise: Assignment-2 # Write a Python function, sumofdigits, that takes in one number \ and returns the sum of digits of given number. # This function takes in one number and returns one number. ''' def sumofdigits(int_num): ''' n is positive Integer returns: a positive integer, the sum of digits of n. ''' if int_num > 0: return int_num%10 + sumofdigits(int_num//10) return 0 def main(): ''' calling function ''' numb_a = input() print(sumofdigits(int(numb_a))) if __name__ == "__main__": main()
#Newton Divided difference Formula: Python Coding from below diff1,diff2,diff3,diff4,diff5,x,y = [ ] , [ ] , [ ] , [ ] , [ ] , [ ] , [ ] v,w,k=0,0,0 result=0 n=int (input("How many pairs of x and y:\t")) print ("Enter the value of x:\n") for i in range(0,n): a=float(input()) x.append(a) print ("Enter the value of y:\n") for i in range(0,n): b=float(input()) y.append(b) print ("Enter the value of x: ") m=float(input()) for i in range(0,n-1): v=(y[i+1]-y[i]) w=(x[i+1]-x[i]) k= float (v/w) diff1.append(k) v,w,k=0,0,0 for i in range (0,n-2): v=(diff1[i+1]-diff1[i]) w=(x[i+2]-x[i]) k= float (v/w) diff2.append(k) v,w,k=0,0,0 for i in range (0,n-3): v=(diff2[i+1]-diff2[i]) w=(x[i+3]-x[i]) k= float (v/w) diff3.append(k) v,w,k=0,0,0 for i in range (0,n-4): v=(diff3[i+1]-diff3[i]) w=(x[i+4]-x[i]) k= float (v/w) diff4.append(k) v,w,k=0,0,0 for i in range (0,n-5): v=(diff4[i+1]-diff4[i]) w=(x[i+5]-x[i]) k= float (v/w) diff5.append(k) if(n==6): result=float (y[0]+(m-x[0])*diff1[0]+ (m-x[0])*(m-x[1])*diff2[0]+(m-x[0])*(m-x[1])*(m-x[2])*diff3[0]+(m-x[0])*(m-x[1]) *(m-x[2])*(m-x[3])*diff4[0]+ (m-x[0])*(m-x[1])*(mx[2])*(m-x[3])*(m-x[4])*diff5[0]) elif(n==5): result=float (y[0]+(m-x[0])*diff1[0]+(m-x[0])*(m-x[1])*diff2[0]+(m-x[0])*(m-x[1])*(m-x[2])*diff3[0]+(m-x[0]) *(m-x[1])*(m-x[2])*(m-x[3])*diff4[0]) elif(n==4): result=float (y[0]+(m-x[0])*diff1[0]+(m-x[0])*(m-x[1])*diff2[0]+(m-x[0])*(m-x[1])*(m-x[2])*diff3[0]) print ("the result is : ",result)
from math import exp,cos,sin,tan,log import parser print("Equation format will be x**a+b*x+9 where a is the power of x") print("b is the constant like 1,2...9 etc\n") print("When need to input exp or cos or sin use exp() or sin()") formula=str(input("Enter your whole equation:\n")) code = parser.expr(formula).compile() def f(x): return eval(code) def bisection(x1,low,up): f(x1) if(f(x1)*f(low)<0): l1=float((x1+low)/2) c=low else: l1=float((x1+up)/2) c=up if(x1==l1 or c==l1): print(l1) return bisection(l1,x1,c) for i in range(-10,20): f(i) f(i+1) if(f(i)*f(i+1)<0): n1=i n2=i+1 a=float((i+i+1)/2) bisection(a,n1,n2)
# 面向对象编程 # 属性:名字/身高/年龄。。 # 功能/动作:吃喝拉撒 # class Person(): # # 属性:成员变量 # name = "萧瑟" # high = 180 # # 功能:成员方法,self固定就行 # def chi(self): # print("吃大餐") # # 实例化类:p类的对象/把柄 # p = Person() # print(p.name) # print(p.high) # p.chi() class Cat(): name = "阿珍" high = "80" def run(self): print("喵喵要吃饭") a = Cat() print(a.name) print(a.high) a.run()
# 导入 selenium from selenium import webdriver import time # 打开谷歌浏览器: Chrome 的C大写的!! 浏览器的把柄 driver = webdriver.Chrome(executable_path='chromedriver.exe') driver.maximize_window() # 打开网址 driver.get("http://ljtest.net:9090/shopxo/") # 搜索 driver.find_element_by_id("search-input").send_keys("裙子") driver.find_element_by_id("ai-topsearch").click() # 固定等待 time.sleep(10) # 隐式等待,自动检测网页是否加载完成 driver.implicitly_wait(8) # 寻找对应的元素判断结果 e = driver.find_element_by_xpath("/html/body/div[4]/div/ul/li/div/p[2]/strong") assert e.text == '¥0.01-128.00' print("成功!")
import sys import math # https://www.codingame.com/ide/puzzle/dwarfs-standing-on-the-shoulders-of-giants influences = {} n = int(input()) # the number of relationships of influence for i in range(n): # x: a relationship of influence between two people (x influences y) x, y = [int(j) for j in input().split()] if x not in influences: influences[x] = [y] else: influences[x] += [y] def influence_paths(person): visited = [person] if person in influences: for influenced in influences[person]: visited += [influence_paths(influenced)] return visited def longest_path_len(paths): result = 1 branches = list(filter(lambda p : isinstance(p, list), paths)) if len(branches) > 0: selected = max(branches, key = lambda p : len(p)) result += longest_path_len(selected) return result output = max(longest_path_len(influence_paths(person)) for person in influences) print(str(output))
from home_work.classes.Figure import Figure import math class Triangle(Figure): name = 'Треугольник' angles = 3 def __init__(self, size_a, size_b, angle_a): # Figure.__init__(self) if size_a > 0 and size_b > 0 and (angle_a > 0 and angle_a < 180): self.size_a = size_a self.size_b = size_b self.angle_a = angle_a self.angle_r_a = math.radians(self.angle_a) else: raise ValueError('Значение сторон должно быть больше 0, угол между ними от 0 до 180') def perimeter(self): self.size_с = math.sqrt( (self.size_a ** 2) + (self.size_b ** 2) - 2 * self.size_a * self.size_b * math.cos(self.angle_r_a)) return self.size_a + self.size_b + self.size_с def area(self): return 1 / 2 * self.size_a * self.size_b * math.sin(self.angle_r_a) t = Triangle(6, 8, 25) print(t.area())
from random import randint from IPython.display import clear_output # create the blackjack class, which will hold all game methods and attributes class Blackjack(): def __init__(self): self.deck = [] self.suits = ("Spades", "Hearts", "Diamonds", "Clubs") self.values = (2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A") # method that creates a deck of 52 cards, each card should be a tuple with a value and suit def makeDeck(self): for suit in self.suits: for value in self.values: self.deck.append((value, suit)) # ex: (7, "Hearts") # method to pop a card from the deck using a random index value def pullCard(self): return self.deck.pop(randint(0, len(self.deck) - 1)) # create a class for the dealer and player objects class Player(): def __init__(self, name): self.name = name self.hand = [] # take in a tuple and append it to the hand def addCard(self, card): self.hand.append(card) # if not dealer's turn then only show one of his cards, otherwise show all def showHand(self, dealer_start = True): print("\n{}".format(self.name)) print("===========") for i in range (len(self.hand)): if self.name == "Dealer" and i == 0 and dealer_start: print("- of -") # hide first card else: card = self.hand[i] print("{} of {}".format(card[0], card[1])) print("Total = {}".format(self.calcHand(dealer_start))) # if not dealer's turn then only give back total of second card def calcHand(self, dealer_start = True): total = 0 aces = 0 card_values = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:10, "J":10, "Q":10, "K":10, "A":11} if self.name == "Dealer" and dealer_start: card = self.hand[1] return card_values[card[0]] for card in self.hand: if card[0] == "A": aces += 1 else: total += card_values[card[0]] for i in range(aces): if total + 11 > 21: total += 1 else: total += 11 return total game = Blackjack() game.makeDeck() name = input("What is your name?") clear_output() player = Player(name) dealer = Player("Dealer") # add two cards to the dealer and player hand for i in range(2): player.addCard(game.pullCard()) dealer.addCard(game.pullCard()) # show both hands using method player.showHand() dealer.showHand() player_bust = False # variable to keep track of player going over 21 while input("Would you like to stay or hit?").lower() != "stay": clear_output() # pull card and put into player's hand player.addCard(game.pullCard()) # show both hands using method player.showHand() dealer.showHand() # check if over 21 if player.calcHand() > 21: player_bust = True # player busted, keep track for later break # break out of the player's loop # handling the dealer's turn, ony run if player didn't bust dealer_bust = False if not player_bust: while dealer.calcHand(False) < 17: # pass False to calculate all cards # pull card and put into player's hand dealer.addCard(game.pullCard()) # check if over 21 if dealer.calcHand(False) > 21: # pass False to calculate all cards dealer_bust = True break # beak out of the dealer's loop clear_output() # show both hands using method player.showHand() dealer.showHand(False) # pass False to calculate and show all cards, even when there are 2 # calculate a winner if player_bust: print("\n\nYou busted, better luck next time!") elif dealer_bust: print("\n\nThe dealer busted, you win!") elif dealer.calcHand(False) > player.calcHand(): print("\n\nDealer has higher cards, you lose!") elif dealer.calcHand(False) < player.calcHand(): print("\n\nYou beat the dealer! Congrats, you win!") else: print("\n\nYou pushed, no one wins!")
from matplotlib import pyplot as plt from IPython.display import clear_output ratings, num_ratings = [1, 2, 3, 4, 5], [0, 0, 0, 0, 0] n = True while n: x = True while x: rating = input("What would you rate this movie (1-5)? ") if rating == '1': num_ratings[0] += 1 clear_output() x = False elif rating == '2': num_ratings[1] += 1 clear_output() x = False elif rating == '3': num_ratings[2] += 1 clear_output() x = False elif rating == '4': num_ratings[3] += 1 clear_output() x = False elif rating == '5': num_ratings[4] += 1 clear_output() x = False else: print("That is not a number or is not a number between 1 through 5!") y = True while y != False: ask_again = input("Is there another user that would like to review (y/n) ") if ask_again == 'y': clear_output() x = True y = False elif ask_again == 'n': clear_output() n = False y = False else: print("That is not an option.") plt.bar(ratings, num_ratings) plt.title("Movie Ratings", fontsize=24) plt.xlabel("Ratings", fontsize=16) plt.ylabel("# of Ratings", fontsize=16) plt.show()
from flask import Flask import json import random app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" class Questions(): """ """ def __init__(self): self.questions = None def get_questions(self, filename='questions.json'): qs = json.load(open(filename, 'r')) self.questions = qs return qs def ask_question(self, question=None): """ Ask a question to the user and collect the answer. If questions specified ask that, else ask a random unasked question :return: """ if not question: key = random.choice(tuple(self.questions.keys())) else: key = question print(key) q = self.questions[key] print(q) ans = input(q['Question']) return ans if __name__ == '__main__': ###Section 1 get input data from the user userQuestions = Questions() userQuestions.get_questions() print(userQuestions.questions) ans = userQuestions.ask_question() print(ans) ##Section 2, show questions to the user for them to choose from, retain selections. interviewQuestions = Questions() interviewQuestions.get_questions(filename='interview_questions.json') for k, v in interviewQuestions.questions.items(): print("The questions is: " + v['Question']) print("The answer is: " + str(v['Answer']) ) ##Section 3, output to the user a PDF to interview the person with.
def get_odd_factorials(func): def wrapper(*args,**kwargs): if args[0]%2==0: print("We give only odd-positive factorials") else: func(*args,**kwargs) return func(*args,**kwargs) return wrapper @get_odd_factorials def display(num): f=1 for x in range(1,num+1): f=f*x return f
""" Write a function that takes directory path, a file extension and an optional tokenizer. It will count lines in all files with that extension if there are no tokenizer. If a the tokenizer is not none, it will count tokens. For dir with two files from hw1.py: >>> universal_file_counter(test_dir, "txt") 6 >>> universal_file_counter(test_dir, "txt", str.split) 6 """ from pathlib import Path from typing import Optional, Callable from sys import path def universal_file_counter( dir_path: Path, file_extension: str, tokenizer: Optional[Callable] = None ) -> int: count = 0 for x in dir_path.iterdir(): if x.match(f"*.{file_extension}"): count += count_from_file(x, tokenizer) return count def count_from_file(file: str, tokenizer: Optional[Callable] = None) -> int: with open(file) as fi: local_count = 0 if tokenizer is None: for line in fi: local_count += 1 else: for line in fi: local_count += len(tokenizer(line)) return local_count if __name__ == "__main__": ...
""" Given a Tic-Tac-Toe 3x3 board (can be unfinished). Write a function that checks if the are some winners. If there is "x" winner, function should return "x wins!" If there is "o" winner, function should return "o wins!" If there is a draw, function should return "draw!" If board is unfinished, function should return "unfinished!" Example: [[-, -, o], [-, x, o], [x, o, x]] Return value should be "unfinished!" [[-, -, o], [-, o, o], [x, x, x]] Return value should be "x wins!" """ from typing import List def tic_tac_toe_checker(board: List[List]) -> str: n = len(board[0]) if ["x"] * n in board: return "x wins!" if ["o"] * n in board: return "o wins!" flat_board = [char for row in board for char in row] for i in range(n): if ( all(flat_board[j] == flat_board[i] for j in range(n + i, n * n, n)) and flat_board[i] != "-" ): # search in colomns return f"{flat_board[i]} wins!" if ( all(flat_board[j] == flat_board[0] for j in range(n + 1, n * n, n + 1)) and flat_board[0] != "-" ): # search in the main diagonal return f"{flat_board[0]} wins!" if ( all( flat_board[j] == flat_board[n - 1] for j in range(n - 1, n * (n - 1) + 1, n - 1) ) and flat_board[n - 1] != "-" ): # search in the side diagonal return f"{flat_board[n-1]} wins!" if "-" in flat_board: return "unfinished!" return "draw!" if __name__ == "__main__": ...
""" Homework 1: ============ We have a file that works as key-value storage, each like is represented as key and value separated by = symbol, example: name=kek last_name=top song=shadilay power=9001 Values can be strings or integer numbers. If a value can be treated both as a number and a string, it is treated as number. Write a wrapper class for this key value storage that works like this: storage = KeyValueStorage('path_to_file.txt') that has its keys and values accessible as collection items and as attributes. Example: storage['name'] # will be string 'kek' storage.song # will be 'shadilay' storage.power # will be integer 9001 In case of attribute clash existing built-in attributes take precedence. In case when value cannot be assigned to an attribute (for example when there's a line `1=something`) ValueError should be raised. File size is expected to be small, you are permitted to read it entirely into memory. """ from keyword import iskeyword from typing import Iterable from typing import Union, Tuple class KeyValueStorage: def __init__(self, path: str) -> None: with open(path) as input: self.items = {key: value for key, value in self.splited_line(input)} @staticmethod def splited_line(input: Iterable) -> Tuple[str, str]: for line in input: line = line.replace("\n", "").split("=") if not line[0].isidentifier() or iskeyword(line[0]): raise ValueError("Value cannot be assigned to an attribute.") yield line[0], line[1] def __getitem__(self, key: str) -> Union[int, str]: try: return int(self.items[key]) except: return self.items[key] def __getattr__(self, name: str) -> Union[int, str]: try: return int(self.items[name]) except: return self.items[name] if __name__ == "__main__": ...
""" Write a function that takes a number N as an input and returns N FizzBuzz numbers* Write a doctest for that function. Write a detailed instruction how to run doctests**. That how first steps for the instruction may look like: - Install Python 3.8 (https://www.python.org/downloads/) - Install pytest `pip install pytest` - Clone the repository <path your repository> - Checkout branch <your branch> - Open terminal - ... Definition of done: - function is created - function is properly formatted - function has doctests - instructions how to run doctest with the pytest are provided You will learn: - the most common test task for developers - how to write doctests - how to run doctests - how to write instructions * https://en.wikipedia.org/wiki/Fizz_buzz ** Энциклопедия профессора Фортрана page 14, 15, "Робот Фортран, чисть картошку!" """ from typing import List def fizzbuzz_1(n: int) -> List[str]: """ >>> fizzbuzz_1(5) ['1', '2', 'fizz', '4', 'buzz'] >>> fizzbuzz_1(16) ['1', '2', 'fizz', '4', 'buzz', 'fizz', '7', '8', 'fizz', 'buzz', '11', 'fizz', '13', '14', 'fizz buzz', '16'] >>> fizzbuzz_1(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 >>> fizzbuzz_1(11.6) Traceback (most recent call last): ... ValueError: n must be exact integer """ if type(n) != int: raise ValueError("n must be exact integer") if n <= 0: raise ValueError("n must be >= 0") buffer = [] for i in range(1, n + 1): if i % 15 == 0: buffer.append("fizz buzz") elif i % 3 == 0: buffer.append("fizz") elif i % 5 == 0: buffer.append("buzz") else: buffer.append(str(i)) return buffer def fizzbuzz_2(n: int) -> List[str]: """ >>> fizzbuzz_2(5) ['1', '2', 'fizz', '4', 'buzz'] >>> fizzbuzz_2(18) ['1', '2', 'fizz', '4', 'buzz', 'fizz', '7', '8', 'fizz', 'buzz', '11', 'fizz', '13', '14', 'fizz buzz', '16', '17', 'fizz'] >>> fizzbuzz_2(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 >>> fizzbuzz_2(11.6) Traceback (most recent call last): ... ValueError: n must be exact integer """ if type(n) != int: raise ValueError("n must be exact integer") if n <= 0: raise ValueError("n must be >= 0") buffer = [] for i in range(1, n + 1): buffer.append( "fizz" * int(i % 3 == 0) + " " * int(i % 15 == 0) + "buzz" * int(i % 5 == 0) + str(i) * (i % 3 != 0 and i % 5 != 0) ) return buffer if __name__ == "__main__": """ The instruction how to run doctest with the pytest: - Install Python 3.8 (https://www.python.org/downloads/) - Install pytest `pip install pytest` - Clone the repository <path your repository> - Checkout branch <your branch> - Open terminal - Write the following comand: pytest --doctest-modules """ import doctest doctest.testmod()
import pandas as pd import numpy as np import nltk import re from spacy.lang.fr.stop_words import STOP_WORDS as fr_stop from nltk.stem.snowball import FrenchStemmer # using stemming of words stemmer = FrenchStemmer() # spliting a string using a regular expression tokenizer = nltk.RegexpTokenizer(r'\w+') # lists of stop words to ignore stop_fr = nltk.corpus.stopwords.words('french') stop_spacy_fr = list(fr_stop) def parse_text(text): """ Parse text to make it ready for further NLP analysis: lower case, remove digits, some characters, stop words... """ text = [re.sub("\d+", "", word) for word in text] text = [re.sub(r'[\(\[\)\]\{\}\.\/]+', '', word) for word in text] text = [word.lower() for word in text] text = tokenizer.tokenize(str(text)) text = [word for word in text if not word in stop_fr] text = [word for word in text if not word in stop_spacy_fr] return text
class SavingsAccount: def __init__(self, annual_inter_rate, saving_balance): self.annual_inter_rate=annual_inter_rate self.saving_balance=saving_balance def MonthlyInterest(self): self.monthly_interest=(self.annual_inter_rate*self.saving_balance*0.01)/(12) self.saving_balance+=self.monthly_interest print("Monthly interest: ", self.monthly_interest) print("Saving balance: ",self.saving_balance) def modifyInterestRate(self,rate): self.annual_inter_rate=rate r=int(input("Enter the rate: ")) p1=int(input("Enter the principal amount of saver 1: ")) p2=int(input("Enter the principal amount of saver 2: ")) saver1=SavingsAccount(r,p1) saver2=SavingsAccount(r,p2) saver1.MonthlyInterest() saver2.MonthlyInterest() saver1.modifyInterestRate(7) saver2.modifyInterestRate(7) saver1.MonthlyInterest() saver2.MonthlyInterest()
#Automating the analysis of a paragraph. #Import a text file filled with a paragraph of your choosing. #Assess the passage for each of the following: #Approximate word count #Approximate sentence count #Approximate letter count (per word) #Average sentence length (in words) import re import os numlines = 0 numwords = 0 numchars = 0 avg_numwords = [] numletters_list = [] lineslist =[] filepath = os.path.join('.', 'paragraph_2.txt') with open("paragraph_2.txt", "r") as text_file: #Count of sentences lineslist = re.split("[?<=.!?] +", str(text_file)) numlines = len(lineslist) for line in text_file: #Count of words wordslist = line.split() numwords += len(wordslist) #Count of letters per word for words in wordslist: numletters = len(words) numletters_list.append(numletters) avg_numwords = sum(numletters_list)/(numwords) #Average Sentence length avg_line_len = (numwords)/(numlines) #Printing all the values print("Paragraph Analysis") print("-----------------") print("Approximate Word Count: " + str(numwords)) print("Approximate Sentence Count:" + str(numlines)) print("Average Letter Count:" + str(avg_numwords)) print("Average Sentence Length:" + str(avg_line_len))
n=int(input("Enter any number :")); cube=0; temp=n; while(n>0): no=n%10 cube=cube+(no**3) n=n//10 if(temp==cube): print("No is armstrong") else: print("No is not armstrong")
x=int(input("Enter the number of element of list: ")) l1=[] def input_fun(): for i in range(0,x): if(i==0): num=int(input('Enter 1st element: ')) l1.append(num) elif(i==1): num=int(input('Enter 2nd element: ')) l1.append(num) elif(i==2): num=int(input('Enter 3rd element: ')) l1.append(num) else: num=int(input('Enter {}th element: '.format(i+1))) l1.append(num) def swap(a,b): l1[j],l1[j+1]=l1[j+1],l1[j] input_fun() for i in range(0,x-1): for j in range(0,x-1): if (l1[j]>l1[j+1]): swap(l1[j],l1[j+1]) print(l1)
""" NEED: Input parsing (command and identifier) Map support World floors/sectors Basic NPC conversations WANT: Map random generation """ from random import randint def start(): print('Insert exposition here.') while True: name = input('\nWhat is your name: ') if input('Your name is '+name+' correct? (y/n)').lower()[0] == 'y': player_data['name'] = name break while True: race = input('\nWhat race are you? (human, mantis or rockperson) ').lower()[0] if race == 'h': player_data['race'] = 'human' break elif race == 'm': player_data['race'] = 'mantis' break elif race == 'r': player_data['race'] = 'rockperson' break else: print('That is not a valid selection.') def input_parse(user_input): global current_targets, raw_input raw_input = user_input current_targets = '' test_command = user_input.lower().split()[0] if 'help' in raw_input: help() return None try: valid_functions[valid_command(test_command)]() except: pass current_targets = valid_target(user_input.lower().split()[1:]) if current_targets: if command_on_target(test_command,current_targets): valid_functions[test_command](current_targets) else: print('You can not do that.') checkup() def command_on_target(command,target): if command in all_targets[target]: return True else: print('You can not '+command+' on the '+target+'.') return False def valid_target(test_targets): global current_targets for word in test_targets: if word in all_targets: return word def valid_command(test_command): for command in valid_commands: for counter in range(len(valid_commands[command])): if test_command == valid_commands[command][counter]: return command print('Sorry I do not understand what '+test_command+' is, please try again.') def checkup(): if player_data['ship_health'] <= 0: raise ZeroDivisionError if player_data['fuel'] <= 0: raise IsADirectoryError def fire_weapon_check(): if input('Fire a laser shot or a rocket? ').lower()[0] == 'l': fire_laser(combat_unit) elif input('Fire a laser shot or a rocket? ').lower()[0] == 'r': if player_data['rockets'] >= 1: fire_rocket(combat_unit) else: print('No rockets remaining.') else: fire_weapon_check() def fire_laser(target): laser_base_dmg = 9 laser_dmg = laser_base_dmg + randint(-2,2) target['health'] -= laser_dmg print('%s hit for %d damage.'%(target,laser_dmg)) def fire_rocket(target): rocket_base_dmg = 18 rocket_dmg = rocket_base_dmg + randint(-5,5) player_data['rockets'] -= 1 if randint(0,1) == 0: target['health'] -= rocket_dmg print('%s hit for %d damage.'%(target,rocket_dmg)) else: print('The rocket missed...') def combat_start(unit): global combat_unit combat_unit = unit combat_unit_health = unit['health'] player_data['in_combat'] = True def beacon_warp(beacon): if player_data['beacon'] == '11'and beacon == 'exit': sector_exit() return None if player_data['in_combat'] == True: print('You can not warp out of combat') return None try: int(beacon) except ValueError: print('This is not a valid beacon to warp to.') if beacon in sec1_warps[str(player_data['beacon'])]: player_data['beacon'] = beacon player_data['fuel'] -= 1 else: print('You can not warp to that location.') def beacon_warp_info(): cur_beacon = player_data['beacon'] print('You are at beacon '+cur_beacon) print('From here you can warp to beacon(s) ',sec1_warps[cur_beacon]) def sector_exit(waffle): print('You exit the sector. Ending the game for now.') #Endgame text for now def talk(target): print(talk_targets[target]) def repair(amount): while True: if amount is None: amount = input('How much damage would you like to repair (current health: %d'%(player_data['ship_health'])) else: break try: amount = int(amount) except ValueError: print('Please give a valid value. ') if amount > player_data['credits']: print('You cannot afford that, you only have %d credits.'%(player_data['credits'])) else: print('You have fixed %d damage.'%(amount)) player_data['credits']-=amount player_data['ship_health'] += amount def status_check(): print('Ship Health: ',player_data['ship_health']) print('Credits: ',player_data['credits']) print('Fuel: ',player_data['fuel']) print('Missiles: ',player_data['rockets']) def help(): print('Available commands are: ') for fun in valid_functions: print(fun) all_targets = { 'id': None, 'davey': ('talk'), 'rebel': ('shoot'), 'mechanic': ('talk','repair'), 'shopkeeper': ('talk'), 'cruiser': ('talk','shoot'), 'exit': ('exit','gate','warp'), 'wrecked ship': ('wrecked','ship','wreck'), '1': ('warp'), '2': ('warp'), '3': ('warp'), '4': ('warp'), '5': ('warp'), '6': ('warp'), '7': ('warp'), '8': ('warp'), '9': ('warp'), '10': ('warp'), '11': ('warp','sector') } valid_functions = { 'shoot': fire_weapon_check, 'warp': beacon_warp, 'talk': talk, 'help': help, 'status': status_check, 'repair': repair, 'sector': sector_exit } valid_commands = { 'shoot': ('shoot', 'fire', 'gun','attack'), 'warp': ('warp','jump'), 'talk': ('talk','speak','chat'), 'help': ('help'), 'status': ('status','ship'), 'repair': ('repair','fix'), 'sector': ('exit','sector') } player_data = { 'name': 'Default', 'race': '', 'rockets': 10, 'ship_health': 100, 'credits': 30, 'fuel': 10, 'inventory': ['id'], 'beacon': '1', 'sector': 1, 'in_combat': False } talk_targets = { 'davey': "Gee boss, good luck on your next delivery; I'm sure you'll do just great!", 'mechanic': "'Pleasure to meet ya! The names Jim, whats yours?'\nYou introduce yourself to Jim\n'Well %s do yer need me to work some wonders on that rust bucket there?'"%(player_data['name']), 'shopkeeper': 'Hello dear and welcome to my humble shop, sadly I have a shortage of supply right now, this bloody war is taking its toll.\n' 'Your ship looks quite a state! You should bring it over to beacon 9, best mechanic in the galaxy.', 'cruiser': 'Stop talking and show us your id, or we will open fire.\nUpon realising that you id was lost during your prior meeting with the federation you begin to panic.\nSensing the tension in your voice you hear the captain yell "Enough of this, kill the rebel scum" shortly followed up by a missile that narrowly misses the ship.' } sec1_data = { 'rebel_scout_defeated': False, 'boss_defeated': False } sec1_targets = { '1': None, '2': 'davey', '3': None, '4': None, '5': None, '6': 'rebel', '7': 'wrecked ship', '8': 'shopkeeper', '9': 'mechanic', '10': 'cruiser', '11': None } sec1_warps = { '1': ('2'), '2': ('1','3','4'), '3': ('2','4'), '4': ('2','3','6'), '5': ('6','7'), '6': ('4','5','8'), '7': ('5'), '8': ('6','9','10'), '9': ('8'), '10': ('8','11'), '11': ('10','sector') } sec1_shop = { 'fuel': 10, 'missile': 8 } rebel_scout = { 'health': 30, 'base_dmg': 7, 'var': 2 } fed_cruiser = { 'health': 50, 'base_dmg': 12, 'var':4 }
""" Linked list questions (pdf page 106-107, book page 94-95) solutions (pdf page 220, book page 208) """ class Node: def __init__(self, data=None, next_node=None): self.data = data self.next_node = next_node def print_list(head): node = head while node is not None: print(node.data) node = node.next_node def remove_next_node(node): if node is None or node.next_node is None: return node_to_remove = node.next_node node.next_node = node_to_remove.next_node del node_to_remove def remove_duplicates(head): """2.1.1""" if head is None or head.next_node is None: return prev = head node = head.next_node numbers = {prev.data} while node is not None: print(numbers) if node.data in numbers: remove_next_node(prev) node = prev.next_node else: numbers.add(node.data) prev = node node = node.next_node def remove_duplicates_no_buffer(head): """2.1.2""" if head is None or head.next_node is None: return prev = head node = head.next_node while node is not None: it = head was_deleted = False while node is not it: if it.data == node.data: remove_next_node(prev) node = prev.next_node was_deleted = True break else: it = it.next_node if not was_deleted: prev = node node = node.next_node # # k = Node(3) # j = Node(3, k) # i = Node(3, j) # h = Node(3, i) # # remove_duplicates_no_buffer(h) # print_list(h) # ----------------------------------------------------------------------------- def get_kth_last_node(k, head): """2.2""" if head is None or k < 0: return None p_first = head p_last = head for i in range(k): if p_last.next_node is None: return None p_last = p_last.next_node while p_last.next_node is not None: p_first = p_first.next_node p_last = p_last.next_node return p_first # # c = Node(3) # b = Node(2, c) # a = Node(1, b) # # res = get_kth_last_node(2, a) # print(f'correct example, {res.data}') # # res = get_kth_last_node(2, None) # print(f'list is nil, {res}') # # res = get_kth_last_node(0, a) # print(f'K is zero, {res.data}') # # res = get_kth_last_node(-2, a) # print(f'K is negative, {res}') # # res = get_kth_last_node(7, a) # print(f'K is bigger than the list, {res}') # ----------------------------------------------------------------------------- def delete_middle_node(node): """2.3""" if node is None or node.next_node is None: return to_be_deleted = node.next_node node.data = to_be_deleted.data node.next_node = to_be_deleted.next_node del to_be_deleted # k = Node(4) # j = Node(3, k) # i = Node(2, j) # h = Node(1, i) # # delete_middle_node(i) # print_list(h) # ----------------------------------------------------------------------------- def partition(head, x): """2.4""" l_head = Node() r_head = Node() last_left = None n = head while n is not None: if n.data < x: nn = n.next_node n.next_node = l_head.next_node l_head.next_node = n if last_left is None: last_left = n n = nn else: nn = n.next_node n.next_node = r_head.next_node r_head.next_node = n n = nn print_list(l_head) print_list(r_head) print("--") if last_left is None: return r_head.next_node else: last_left.next_node = r_head.next_node return l_head.next_node # # g = Node(1) # f = Node(2, g) # e = Node(10, f) # d = Node(5, e) # c = Node(8, d) # b = Node(5, c) # a = Node(3, b) # # res = partition(a, 5) # print_list(res) # ----------------------------------------------------------------------------- def sum_lists_reversed(lst1, lst2): """2.5.1""" p1 = lst1 p2 = lst2 res_head = None res_tail = None t = 0 while p1 is not None or p2 is not None or t != 0: val1 = p1.data if p1 is not None else 0 val2 = p2.data if p2 is not None else 0 digit_sum = val1 + val2 + t t = digit_sum // 10 n_node = Node(digit_sum % 10) if res_head is None: res_head = n_node res_tail = n_node else: res_tail.next_node = n_node res_tail = n_node if p1 is not None: p1 = p1.next_node if p2 is not None: p2 = p2.next_node return res_head def get_number(lst): n = lst number = 0 while n is not None: number = number * 10 + n.data n = n.next_node return number def sum_lists(lst1, lst2): num1 = get_number(lst1) num2 = get_number(lst2) total_sum = num1 + num2 head = None while total_sum > 0: residue = total_sum % 10 digit = Node(residue) if head is None: head = digit else: digit.next_node = head head = digit total_sum = total_sum // 10 return head # f = Node(5) # e = Node(9, f) # d = Node(2, e) # c = Node(7) # b = Node(1, c) # a = Node(6, b) # # res = sum_lists(a, d) # print_list(res) # ----------------------------------------------------------------------------- def get_tail_and_size(head): last_node = head size = 1 while last_node.next_node is not None: last_node = last_node.next_node size = size + 1 return last_node, size def intersection(lst1, lst2): """2.7""" if lst1 is None or lst2 is None: return None last_node1, size1 = get_tail_and_size(lst1) last_node2, size2 = get_tail_and_size(lst2) if last_node1 is not last_node2: return None shorter = lst1 if size1 < size2 else lst2 longer = lst2 if size1 < size2 else lst1 chop = abs(size1 - size2) for i in range(chop): longer = longer.next_node while shorter is not longer: shorter = shorter.next_node longer = longer.next_node return longer # # f = Node(6) # e = Node(5, f) # d = Node(4, e) # c = Node(3, d) # b = Node(2, c) # a = Node(1, b) # x = Node(3, d) # # res = intersection(a, x) # print_list(res) # ----------------------------------------------------------------------------- def loop_detection(head): """2.8""" if head is None: return None node = head nodes = set() while True: print(node.data) if node in nodes: return node else: nodes.add(node) node = node.next_node f = Node(6) e = Node(5, f) d = Node(4, e) c = Node(3, d) b = Node(2, c) a = Node(1, b) f.next_node = c res = loop_detection(a) print(res) # x = 'hippo' # print(x.index('p')) # lst = [6, 2, 5, 9] # print(lst) # lst.append(10) # print(lst + [3, 4]) # print(lst) # lst.extend([3, 4]) # print(lst) # del lst[1] # print(lst) # lst.remove(5) # print(lst) # t = 2, # print(t) # print(t[0]) # tp = (1, 2, 3) # print(tp) # def double(y): # y.append(6) # return y # # # x = [5] # double(x) # print(x) # # li = x # # li = [0, 1] # print(x) # print(li) # x = [1] # y = [1] # # print(x == y) # print(hex(id(x))) # print(hex(id(y)))
from scipy import optimize # linspace의 데이터 추출 시각화 import matplotlib.pyplot as plt import math import numpy as np def border() : print() print("=================================================") print() def sigma(K, N, value): return sum(value[n] for n in range(K, N)) def positive_number(x) : return x if x > 0 else None def incentive_X_delay_graph(Contract_item = []) : graph_color = ['c', 'b', 'g', 'r', 'm', 'y', 'k'] for i in range(len(Contract_item)) : x = list(filter(positive_number, Contract_item[i].Delay)) y = list(filter(positive_number, Contract_item[i].Incentive)) label = "r=" + str(Contract_item[i].Gamma) + ",r'=" + str(Contract_item[i].Gamma_Prime) plt.plot(x,y, graph_color[i], label = label) plt.axis([0, 6, 0, 3.5]) plt.xlabel("Latency") plt.ylabel("Incentive$") plt.title("Relationships between delay and incentive") plt.grid(True) plt.legend() # plt.savefig("contract1.png", dpi=350) plt.show() def HubTpye_X_HubUtility_graph(Hub_type={}, N = 0, st=0, dt=0) : graph_color = ['c', 'b', 'g', 'r', 'm', 'y', 'k'] for i in Hub_type : if i < st : continue elif i > dt : break x = list(Hub_type.keys()) y = Hub_type[i] label = "type=" + str(i) color = graph_color.pop(0) plt.scatter(x,y, s = 40, c = color, alpha=0.5) plt.plot(x,y, color, label = label) plt.axis([10, N, -3, 6]) plt.xlabel("Type Hub node") plt.ylabel("Utility Hub node") plt.title("Relationships between Type and Utility (Hub Node)") plt.grid(True) plt.legend() # plt.savefig("contract2.png", dpi=350) plt.show() class Contract_item : def __init__(self, name): self.name = name self.Incentive = [0] self.Client_U = 0 # total client Utility self.Client_U_I = [0] self.Hub_U = [0] self.Hub_type_U = {} self.Delay = [0] self.Delay_Inverse = [0] self.Omega = [0] # delay addition function self.Theta = [] self.P = [] self.Gamma = 0 # Incentive wegiht parameter for client self.Minus = -1 self.N = 0 # total Theta number self.Gamma_Prime = 0 # unit resource cost for hub nodes def set_Theta_number(self, n): self.N = n self.Theta = [i for i in range(n+1)] self.P = [1/n for _ in range(n+1)] self.print_N() self.print_Theta() self.print_P() def set_Gamma(self, gamma): self.Gamma = gamma self.print_Gamma() def set_Gamma_Prime(self, gamma_prime): self.Gamma_Prime = gamma_prime self.print_Gamma_Prime() def print_N(self): print("{}'s N value : {}".format(self.name, self.N)) def print_Theta(self): print("{}'s Theta value : {}".format(self.name, self.Theta)) def print_P(self): print("{}'s P value : {}".format(self.name, self.P)) def print_Gamma(self): print("{}'s Gamma value : {}".format(self.name, self.Gamma)) def print_Gamma_Prime(self): print("{}'s Gamma_Prime value : {}".format(self.name, self.Gamma_Prime)) def state_print(self, name, value): for i in range(len(value)): print("{}'s {} index {} : {}".format(self.name, i, name, value[i])) def set_client_utility_i(self, i): def optimizeQ(x): current_P = self.P[i] V_theta_q = self.Theta[i] * math.log(1 + x) P_sigma = sigma(i + 1, self.N + 1, self.P) if i != self.N: Lambda = self.Theta[i] * math.log(1 + x) - self.Theta[i + 1] * math.log(1 + x) else: Lambda = 0 return (self.Minus * ((current_P / self.Gamma_Prime * V_theta_q) + (Lambda / self.Gamma_Prime * P_sigma) - (current_P * self.Gamma * x))) return optimizeQ def set_omega(self): for k in range(1, self.N+1): if k == 1: self.Omega.append(0) else: self.Omega.append(self.Theta[k] * (math.log(1 + self.Incentive[k]) - math.log(1 + self.Incentive[k - 1]))) def set_delay(self, i): delay = (self.Theta[1] * math.log(1 + self.Incentive[1]) + sigma(1, i + 1, self.Omega)) / self.Gamma_Prime self.Delay_Inverse.append(delay) if delay != 0: delay = 1 / delay return (delay) def set_client_Utility(self): return sum(self.P[i] * (self.Delay_Inverse[i] - self.Gamma * self.Incentive[i]) for i in range(1, self.N + 1)) def set_hub_Utility(self): for i in range (1, self.N+1) : self.Hub_U.append(self.Theta[i] * math.log(1 + self.Incentive[i]) - self.Gamma_Prime * self.Delay_Inverse[i]) def set_hub_type_Utility(self): for i in range (1, self.N+1) : self.Hub_type_U[self.Theta[i]] = [] for j in range (1, self.N+1) : self.Hub_type_U[self.Theta[i]].append(self.Theta[i] * math.log(1 + self.Incentive[j]) - self.Gamma_Prime * self.Delay_Inverse[j]) def execute(self,x0,bnds): # 1_ for for i in range(1, self.N+1) : temp = self.set_client_utility_i(i) result = optimize.minimize(temp, x0, method="TNC", bounds=bnds, options={'maxiter': 1000}) self.Client_U_I.append(result.fun) self.Incentive.append(result.x) self.state_print("client utility", self.Client_U_I) border() self.state_print("incentive", self.Incentive) border() self.set_omega() self.state_print("Omega", self.Omega) border() #2_ for for i in range(1, self.N+1) : self.Delay.append(self.set_delay(i)) self.state_print("Delay", self.Delay) border() self.set_hub_Utility() self.state_print("Hub Utility", self.Hub_U) border() self.set_hub_type_Utility() # border() print("**=====================================================") print() self.Client_U = self.set_client_Utility() print("Client_U : {}".format(self.Client_U)) print() print("**=====================================================") contract_item1 = Contract_item("item1") contract_item2 = Contract_item("item2") contract_item3 = Contract_item("item3") contract_item1.set_Theta_number(20) contract_item2.set_Theta_number(20) contract_item3.set_Theta_number(20) border() contract_item1.set_Gamma(1) contract_item1.set_Gamma_Prime(5) contract_item2.set_Gamma(1.5) contract_item2.set_Gamma_Prime(5) contract_item3.set_Gamma(1) contract_item3.set_Gamma_Prime(4.6) border() x0 = [0.1] # init bnds = [(0.0,40.0)] # bound contract_item1.execute(x0, bnds) contract_item2.execute(x0, bnds) contract_item3.execute(x0, bnds) incentive_X_delay_graph([contract_item1,contract_item2, contract_item3]) HubTpye_X_HubUtility_graph(contract_item3.Hub_type_U,N = contract_item3.N, st = 14, dt = 19)
import re def find_max_ap(students_line): pattern = r'AP{1,}' return re.findall(pattern, students_line) if __name__ == '__main__': t = int(input()) for _ in range(t): n = int(input()) students_line = input() res = find_max_ap(students_line) if len(res) != 0: print(len(max(res, key=len)) - 1) else: print(0)
def calc(array): ref = set(array) for i in range(len(array)): for j in range(i + 1, len(array)): if abs(array[i] - array[j]) not in ref: ref.add(abs(array[i] - array[j])) return list(ref) def is_nice(array): while len(array) <= 300: x = calc(array) if array == x: return ['YES', len(array), array] array = x return ['NO'] if __name__ == '__main__': t = int(input()) li = [] for _ in range(t): n = input() ar = list(map(int, input().split())) li.append(ar) for arr in li: ans = is_nice(array=arr) if ans[0] == 'YES': print('YES') print(ans[1]) print(' '.join(str(p) for p in ans[2])) else: print('NO')
import re if __name__ == '__main__': n = int(input()) arr = [] count = 0 targ = False for _ in range(n): x = input() if count == 0: pattern = r'OO' res = re.search(pattern, x) if res: x = x.replace('OO', '++', 1) count = 1 targ = True arr.append(x) else: arr.append(x) else: arr.append(x) if targ: print('YES') for i in arr: print(i) else: print('NO')
def check_three_strings(x, y, z): for i in range(len(x)): if x[i] == y[i]: if x[i] != z[i]: return 'NO' elif x[i] == z[i] or y[i] == z[i]: continue else: return 'NO' return 'YES' if __name__ == '__main__': t = int(input()) for _ in range(t): a = input() b = input() c = input() print(check_three_strings(a, b, c))
def solve(tab, hand): for i in hand: if i[0] == tab[0] or i[1] == tab[1]: return 'YES' return 'NO' if __name__ == '__main__': card_on_table = input() card_on_hand = input().split() ans = solve(card_on_table, card_on_hand) print(ans)
import math def isvalid(s): # Solution of Quadratic Equation k = (-1 + math.sqrt(1 + 8 * s)) / 2 # Condition to check if the # solution is a integer if math.ceil(k) == math.floor(k): return int(k) else: return -1 if __name__ == '__main__': n = int(input()) t = input() i = 0 k = 0 ans = list(range(1, isvalid(n)+1)) end = False s = '' while not end: s += t[i] i += ans[k] k += 1 if k == isvalid(n): end = True print(s)
def binary_search_insertion(item, arr): # handling border cases print(f'key: {item}, arr: {arr}') if arr[0] > item: new_arr = [item] new_arr.extend(arr) return new_arr elif arr[-1] < item: arr.append(item) return arr start = 0 end = len(arr) - 1 while start <= end: mid = (start + end) // 2 if item > arr[mid]: start = mid + 1 elif item < arr[mid]: end = mid - 1 else: new_arr = arr[:mid] + [item] + arr[mid:] return new_arr new_arr = arr[:start] + [item] + arr[start:] return new_arr res = binary_search_insertion(5, [2, 4, 4, 6, 7, 9]) print(res)
if __name__ == '__main__': # there are n candies and you must distribute them to two sisters alice and betty # alice will get a (a > 0) and betty will get b (b > 0) # a > b and a + b = n t = int(input()) for _ in range(t): n = int(input()) if n % 2 == 0: print(n // 2 - 1) else: print(n // 2)
if __name__ == '__main__': t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) if set(a).intersection(set(b)): print('YES') print(1, list(set(a).intersection(set(b)))[0]) else: print('NO')
def solve(array): x = sorted(array) max1 = x[-1] max2 = x[-2] finalist = [max(array[0], array[1]), max(array[2], array[3])] if max1 in finalist and max2 in finalist: print('YES') else: print('NO') if __name__ == '__main__': t = int(input()) for _ in range(t): matches = list(map(int, input().split())) solve(matches)
import numpy as np import matplotlib.pyplot as plt def generateOrthognalArray (m , n): arr = np.empty([m,n]) arr[:,0] = np.ones(m , np.int) for i in range(0,m-1): item = i * (1/(m - 1)) for j in range(1 , n): arr[i , j] = pow(item , j-1) return arr arr1 = generateOrthognalArray(3 , 3) print(arr1) print('Conditioning number : ' + str(np.linalg.cond(arr1)))
import random from objects.game_objects import Card from objects.player_objects import Player, Action, Hint class Rando(Player): def __init__(self, id): super().__init__(id) def _strategy(self, players, game): """This strategy selects an action and action description completely at random. It's choices are bound by the current state of the game (e.g., it will not try to provide a hint if there are no more available hints). This method serves as a template for how a strategy is constructed. """ available_actions = ['play', 'discard'] if game.hints > 0: available_actions.append('hint') action = random.choice(available_actions) if action in ['play', 'discard']: # select one card to play or discard at random description = random.choice(self.hand) elif action in ['hint']: # give hint to another randomly selected player target_player_id = random.choice([player.id for player in players if player.id != self.id]) # select a random card from their hand and randomly decide to give a hint about that card's suit or value selected_card = random.choice(players[target_player_id].hand) hint_type = 'value' \ if not game.rainbow_as_sixth and selected_card.suit() == 'Rainbow' \ else random.choice(['suit', 'value']) hint_value = getattr(selected_card, hint_type)() # assemble the choices into the action's description description = Hint(target_player_id, hint_type, hint_value) return Action(self.id, action, description)
# Import connection pool tools from psycopg2 from psycopg2 import pool # Create a class to create a connection to the database class Database: # Create connection_pool property in class __connection_pool = None @staticmethod # Initialize connection with keyword arguments passed in, set pool range between 1 and 12 connections def init_conn(**kwargs): Database.__connection_pool = pool.SimpleConnectionPool(1, 12, **kwargs) # kwargs(keyword args) = named parameters in app.py # Method: To get a connection from pool @staticmethod def get_connection(): return Database.__connection_pool.getconn() # Method: Returns the connection to the pool when finished @staticmethod def return_connection(connection): Database.__connection_pool.putconn(connection) # Method: Closes open connections @staticmethod def close_all_connections(): Database.__connection_pool.closeall() # Create a class to open a cursor to manipulate the database. Use with statement(init, enter, exit) class ConnectionPool: def __init__(self): # Create connection property self.connection = None # Create cursor property self.cursor = None def __enter__(self): # Return a valid new connection from the pool self.connection = Database.get_connection() # Get cursor from connection self.cursor = self.connection.cursor() # return active connection with cursor return self.cursor # Close cursor Commit data and return connection to the pool def __exit__(self, exc_type, exc_val, exc_tb): # Rollback connection if error occurs if exc_val is not None: self.connection.rollback() else: self.cursor.close() # Close cursor self.connection.commit() # Commit data # Return connection to the pool Database.return_connection(self.connection)
#!/usr/bin/env python import SimpleHTTPServer import SocketServer import cgi import sys PORT = 8080 # Simple server to respond to both POST and GET requests. POST requests will # just respond as normal GETs. class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) def do_POST(self): SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) Handler = ServerHandler # Allows use to restart server immediately after restarting it. SocketServer.ThreadingTCPServer.allow_reuse_address = True httpd = SocketServer.TCPServer(("", PORT), Handler) print ("Serving at: http://%s:%s" % ("localhost", PORT)) httpd.serve_forever()
"""This module contains common operation connected with datetime""" from datetime import datetime def datetime_from_string(date_string): """ Returns datetime from string formatted like: 2021-01-01 :param date_string: formatted string :return: datetime corresponding to date_string """ return datetime.strptime(date_string, '%Y-%m-%d')
meal_cost = 12 tip_percent = 20 tax_percent = 8 tip=meal_cost*tip_percent/100 tax=meal_cost*tax_percent/100 x=meal_cost+tip+tax y=5 print("The total meal cost is {a} {b} dollars.".format(a=round(x),b=(y)))
import re def checkFasta(fastas): status = True lenList = set() for i in fastas: lenList.add(len(i[1])) if len(lenList) == 1: return True else: return False def minSequenceLength(fastas): minLen = 10000 for i in fastas: if minLen > len(i[1]): minLen = len(i[1]) return minLen def minSequenceLengthWithNormalAA(fastas): minLen = 10000 for i in fastas: if minLen > len(re.sub('-', '', i[1])): minLen = len(re.sub('-', '', i[1])) return minLen
from random import randint #criando função para criar ficha: def criarficha(nomedaficha): ficha = open(f"{nomedaficha}.txt", "w+") while True: classe = input("qual a classe do seu personagem?(Guerreiro, assasino ou mago)").upper() if classe != "MAGO" and classe != "GUERREIRO" and classe != "ASSASSINO": print("Selecione uma classe válida") else: break ficha.write(f"NOME: {nomedaficha}\nCLASSE: {classe}\nMANA:\n{randint(1, 20)}\nVIDA:\n{randint(1, 20)}\nCARISMA:\n{randint(1, 4)}\nARMA:\n{randint(1, 5)} (1 - espada 2 - adagas 3 - arco 4 - flecha 5 - cajado)\nFOME:\n{randint(1,4)}") ficha.close() print("ficha criada com sucesso!") #criando função para mostrar a ficha def mostrarficha(nomedaficha): ficha = open(f"{nomedaficha}.txt", "r") ficha2 = ficha.read() ficha.close() return ficha2 #função para modificar a ficha def modificarficha(nomedaficha, modificado): while True: ficha = open(f"{nomedaficha}.txt", "r") moom = ficha.readlines() sos = moom.index(f"{modificado}:\n") novo = input(f"digite o novo valor de {modificado.lower()}: ") if modificado == "MANA" and int(novo) <= 20: pass elif modificado == "FOME" and int(novo) <= 4: pass elif modificado == "VIDA" and int(novo) <= 20: pass else: print("Use um valor até 20 para vida e mana e 4 para fome.") continue del moom[sos + 1] moom.insert(sos + 1, novo + "\n") ficha = open(f"{nomedaficha}.txt", "w") moom2 = "".join(moom) ficha.write(moom2) ficha.close() break #função para copiar para um txt def copiandparaumnovotxt(nomezin, nomezo): ficha = open(f"{nomezin}.txt", "r") sos = ficha.read() ficha2 = open(f"{nomezo}.txt", "w+") ficha2.write(sos) ficha.close() ficha2.close() #criando um def que verifica se a fome/vida/mana estão em 0 def verificando(nome): ficha = open(f"{nome}.txt", "r") ficha2 = ficha.readlines() ficha.close() if int(ficha2[5]) <= 0: print("=-"*30, "\n") print("sua vida está em 0") elif int(ficha2[3]) <= 0: print("=-" * 30, "\n") print("EMTER21ALMERT!!1!sua mana está em 0") elif int(ficha2[11]) <= 0: print("=-" * 30, "\n") print("EMTER21ALMERT!!1!sua fome está em 0") while True: try: #perguntando se ele quer entrar em uma ficha ou criar uma sus = int(input("Você deseja criar uma nova ficha ou importar uma ficha já criada?(1 - criar ficha/2 - entrar em uma existente)")) nome = input("qual o nome do seu personagem?") if sus == 1: criarficha(nome) elif sus == 2: #fazendo um sistema para selecionar o que a pessoa quer mudar. while True: print(f"sua ficha está assim:\n{mostrarficha(nome)}") verificando(nome) print("=-"*30) pergunta = int(input("Você gostaria de: Mudar a vida (1) // Mudar a mana (2) // Mudar a fome (3) // Salvar a ficha em um txt (4) // Jogar dado (5) // Sair (6) --->")) if pergunta == 1: modificarficha(nome, "VIDA") elif pergunta == 2: modificarficha(nome, "MANA") elif pergunta == 3: modificarficha(nome, "FOME") elif pergunta == 4: copiandparaumnovotxt(nome, input("digite o nome do arquivo novo")) elif pergunta == 5: t = int(input("quantos lados tem o dado?")) t2 = int(input("quantos dados você ques jogar?")) for _ in range(0, t2): print(f"O dado deu: {randint(1, t)}") elif pergunta == 6: exit() else: print(" digite um número válido") continue except FileNotFoundError: print("Esse personagem não existe, tente novemente ou crie um!") except ValueError: print("Use um número.")
# I need this playground area to replace a dictionary key value on a small # scale from collections import defaultdict # ASSIGN A NEW VALUE TO AN EXISTING KEY TO CHANGE THE VALUE # Use the format dict[key] = value to assign a new value to an existing key. a_dictionary = {"a": 1, "b": 2} a_dictionary["b"] = 3 # USE dict.update() TO CHANGE MULTIPLE VALUES IN A DICTIONARY # Call dict.update(other) using a collection of key: value pairs as other # to update the values of the dictionary. b_dictionary = {"a": 1, "b": 2} b_dictionary.update({"a": 3, "b": 4}) # However, in budget.py it's a list of a dictionary # * A `deposit` method that accepts an amount and description. If no description # is given, it should default to an empty string. The method should append an # object to the ledger list in the form of # `{"amount": amount, "description": description}`. ledger = [ {"amount": 1, "description": 'aaa'}, {"amount": 22, "description": 'bbb'}, {"amount": 333, "description": 4} ] print(ledger)
#!/usr/bin/env python3 import os def str_list_to_int_list(input): for i, value in enumerate(input, start=0): input[i] = int(value) return input def get_content(path): with open(path, 'r') as data: return data.read() def get_deserialized_content(path): return get_content(path).split(',') def run(intcode=[0]): i = 0 opcode = intcode[i] while opcode != 99: one = intcode[intcode[i+1]] two = intcode[intcode[i+2]] result_index = intcode[i+3] if opcode == 1: result = one + two elif opcode == 2: result = one * two else: raise Exception("invalid opcode {}".format(opcode)) intcode[result_index] = result i = i + 4 opcode = intcode[i] return intcode def get_noun_verb_to_equal_output(init_intcode, target_output=19690720, noun_max=100, verb_max=100): output = 0 for noun in range(noun_max): for verb in range(verb_max): intcode = init_intcode.copy() intcode[1] = noun intcode[2] = verb try: output = run(intcode)[0] except: continue if output == target_output: return (100 * noun) + verb raise Exception('could not find target optcode') def main(input_path='input'): pass init_intcode = str_list_to_int_list(get_deserialized_content(input_path)) print('part one: {}'.format(run(init_intcode.copy())[0])) print('part two: {}'.format(get_noun_verb_to_equal_output(init_intcode.copy(), 19690720))) if __name__ == '__main__': main()
asd = input("Enter your 12 bit EAN barcode number: ") tin = [int(i) for i in asd] odd = 0 even = 0 for k in range(1,12,2): odd += tin[k] for j in range(0,12,2): even += tin[j] checksum = odd*3 + even checkdigit = checksum % 10 if checkdigit != 0: checkdigit = 10 - checkdigit print(asd+str(checkdigit))
# coding:utf-8 ''' 【101】对称二叉树 给定一个二叉树,检查它是否是镜像对称的。 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 1 / \ 2 2 / \ / \ 3 4 4 3 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: 1 / \ 2 2 \ \ 3 3 进阶: 你可以运用递归和迭代两种方法解决这个问题吗? ''' class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class CompeleteTree(object): def __init__(self, tree_list): if not tree_list: self.root = None else: self.root = TreeNode(tree_list[0]) queue = list() queue.append(self.root) index = 0 index1 = 1 while index1 < len(tree_list): root = queue[index] root.left = TreeNode(tree_list[index1]) index1 += 1 queue.append(root.left) root.right = TreeNode(tree_list[index1]) index1 += 1 queue.append(root.right) index += 1 class Solution(object): ''' 如果同时满足下面的条件,两个树互为镜像: 1.它们的两个根结点具有相同的值 2.每个树的右子树都与另一个树的左子树镜像对称 ''' def isSymmtricSubTree(self, left, right): flag = False if left is None and right is None: flag = True elif left and right: if left.val == right.val: flag_1 = self.isSymmtricSubTree(left.left, right.right) flag_2 = self.isSymmtricSubTree(left.right, right.left) if flag_1 and flag_2: flag = True return flag def isSymmetric(self, root): if not root: return True return self.isSymmtricSubTree(root.left, root.right) if __name__ == '__main__': solution = Solution() tree_list = [1, 2, 2, 3, 4, 4, 3] tree = CompeleteTree(tree_list) print solution.isSymmetric(tree.root) tree_list = [1, 2, 2, None, 3, None, 3] tree = CompeleteTree(tree_list) print solution.isSymmetric(tree.root)
# coding:utf-8 ''' 96. 不同的二叉搜索树 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? 示例: 输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 ''' class Solution(object): def __init__(self): self.dp = {} self.dp[0] = 0 self.dp[1] = 1 self.dp[2] = 2 self.dp[3] = 5 def buildBST(self, l1): n = len(l1) if n in self.dp: return self.dp[n] cnt = 0 for i in range(n): left_cnt = 1 if i < n -1: left = l1[i+1:] left_cnt = self.buildBST(left) right_cnt = 1 if i > 1: right = l1[:i] right_cnt = self.buildBST(right) cnt += (left_cnt * right_cnt) self.dp[n] = cnt return cnt def numTrees1(self, num): l1 = [i for i in range(1, num+1)] self.buildBST(l1) return self.dp[num] def numTrees(self, n): dp = list() dp.append(1) dp.append(1) for i in range(2, n+1): dp.append(0) for j in range(1, i+1): dp[i] += (dp[j-1] * dp[i-j]) return dp[n] if __name__ == '__main__': solution = Solution() num = 6 print solution.numTrees(num)
# coding:utf-8 ''' 【229. 求众数 II】 给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。 说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。 示例 1: 输入: [3,2,3] 输出: [3] 示例 2: 输入: [1,1,1,3,3,2,2,2] 输出: [1,2] ''' class Solution(object): ''' 摩尔投票法 组一个team 若投票到team中的一员 进行下一轮,否则同时抵消;最终team中为最大的几个人 ''' def majoritElement(self, nums): nums_set = set(nums) if len(nums) < 3 or len(nums_set) < 2: return list(nums_set) #投票过程 cond1 = nums_set.pop() count1 = 0 cond2 = nums_set.pop() count2 = 0 for i in nums: if i == cond1: count1 += 1 elif i == cond2: count2 += 1 else: if count1 <= 0: cond1 = i count1 = 1 if count2 <= 0: cond2 = i count2 = 1 else: count1 -= 1 count2 -= 1 #审核过程 cnt1 = 0 cnt2 = 0 for i in nums: if i == cond1: cnt1 += 1 if i == cond2: cnt2 += 1 res = set() if cnt1 * 3 > len(nums): res.add(cond1) if cnt2 * 3 > len(nums): res.add(cond2) return list(res) if __name__ == '__main__': solution = Solution() print solution.majoritElement([1,1,1,2,3,4,5,6])
# coding:utf-8 class Solution(object): def minArray(self, numbers): low = 0 high = len(numbers) -1 while low < high: mid = low + (high-low)/2 if numbers[mid] < numbers[high]: high= mid elif numbers[mid] >numbers[high]: low = mid + 1 else: high -= 1 return numbers[low] if __name__ == '__main__': solution = Solution() numbers = [3,4,5,1,2] numbers = [2,2,2,2,2,1] #numbers = [1, 3, 5] #numbers = [3, 1, 2] numbers = [3, 1, 1, 1, 1] print solution.minArray(numbers)
# coding:utf-8 class Solution(object): def searchInsert(self, nums, target): if not nums: return 0 low = 0 high = len(nums) - 1 while low <= high: mid = low + (high-low)/2 if nums[mid] == target: return mid elif nums[mid] < target: low = mid + 1 else: high = mid - 1 return low if __name__ == '__main__': solution = Solution() nums = [1,3,5,6] target = 7 print solution.searchInsert(nums, target)
# coding:utf-8 ''' 【53. 最大子序和】 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 进阶: 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 ''' class Solution(object): def maxSubArray(self, nums): dp = list() dp.append(nums[0]) maxSum = dp[0] for i in range(1, len(nums)): if dp[i-1] < 0: dp.append(nums[i]) else: dp.append(dp[i-1] + nums[i]) if dp[i] > maxSum: maxSum = dp[i] return maxSum if __name__ == '__main__': solution = Solution() print solution.maxSubArray([-2,1,-3,4,-1,2,1,-5,4])
# coding:utf-8 class Solution(object): def reverse(self, s): s = s.strip() s = list(s) low = 0 high = len(s) -1 while low < high: tmp = s[low] s[low] = s[high] s[high] = tmp low += 1 high -= 1 return ''.join(s) def reverseWords(self, s): s = self.reverse(s) res = '' low = 0 high = 0 while high < len(s): if s[high] == ' ': tmp = self.reverse(s[low:high+1]) if tmp: res = res + tmp + ' ' low = high+1 high += 1 res += self.reverse(s[low:high+1]) return res if __name__ == '__main__': solution = Solution() print solution.reverseWords('the sky is blue') print solution.reverseWords(' hello world! ') print solution.reverseWords('a good example')
# coding:utf-8 ''' 【560. 和为K的子数组】 给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。 示例 1 : 输入:nums = [1,1,1], k = 2 输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。 说明 : 数组的长度为 [1, 20,000]。 数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。 ''' class Solution(object): ''' 前缀和 ''' def subarraySum(self, nums, k): cnt = 0 presums = {0: 1} sumpre = 0 for i in nums: sumpre += i if (sumpre - k) in presums: cnt += presums[sumpre - k] presums.setdefault(sumpre, 0) presums[sumpre] += 1 return cnt if __name__ == '__main__': solution = Solution() nums = [1, 1, 1] print solution.subarraySum(nums, 2)
# coding:utf-8 class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def maxDepth(self, root): if not root: return 0 left = self.maxDepth(root.left) right = self.maxDepth(root.right) return max(left, right) + 1 if __name__ == '__main__': solution = Solution() root = TreeNode(3) root.left = TreeNode(9) root.right = TreeNode(20) root.left.left = TreeNode(15) root.left.right = TreeNode(7) print solution.maxDepth(root)
# coding:utf-8 ''' 【1025. 除数博弈】 爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。 最初,黑板上有一个数字 N 。在每个玩家的回合,玩家需要执行以下操作: 选出任一 x,满足 0 < x < N 且 N % x == 0 。 用 N - x 替换黑板上的数字 N 。 如果玩家无法执行这些操作,就会输掉游戏。 只有在爱丽丝在游戏中取得胜利时才返回 True,否则返回 false。假设两个玩家都以最佳状态参与游戏。 示例 1: 输入:2 输出:true 解释:爱丽丝选择 1,鲍勃无法进行操作。 示例 2: 输入:3 输出:false 解释:爱丽丝选择 1,鲍勃也选择 1,然后爱丽丝无法进行操作。 提示: 1 <= N <= 1000 ''' class Solution(object): def divisorGame(self, N): return N%2 == 0
# coding:utf-8 ''' 【657. 机器人能否返回原点】 在二维平面上,有一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。 移动顺序由字符串表示。字符 move[i] 表示其第 i 次移动。机器人的有效动作有 R(右),L(左),U(上)和 D(下)。如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。 注意:机器人“面朝”的方向无关紧要。 “R” 将始终使机器人向右移动一次,“L” 将始终向左移动等。此外,假设每次移动机器人的移动幅度相同。 示例 1: 输入: "UD" 输出: true 解释:机器人向上移动一次,然后向下移动一次。所有动作都具有相同的幅度,因此它最终回到它开始的原点。因此,我们返回 true。 示例 2: 输入: "LL" 输出: false 解释:机器人向左移动两次。它最终位于原点的左侧,距原点有两次 “移动” 的距离。我们返回 false,因为它在移动结束时没有返回原点。 ''' class Solution(object): def judgeCircle(self, moves): row = 0 col = 0 for i in moves: if i == 'U': row -= 1 elif i == 'D': row += 1 elif i == 'R': col += 1 elif i == 'L': col -= 1 return (row == 0 and col == 0) if __name__ == '__main__': solution = Solution() moves = "UD" print solution.judgeCircle(moves)
# coding:utf-8 ''' 【437. 路径总和 III】 给定一个二叉树,它的每个结点都存放着一个整数值。 找出路径和等于给定数值的路径总数。 路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。 二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。 示例: root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 返回 3。和等于 8 的路径有: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11 ''' class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def count(self, root, sum): if not root: return 0 cnt = 1 if root.val == sum else 0 cnt_left = self.count(root.left, sum-root.val) cnt_right = self.count(root.right, sum-root.val) return cnt + cnt_left + cnt_right def pathSum(self, root, sum): if not root: return 0 cnt = self.count(root, sum) left_cnt = self.pathSum(root.left, sum) right_cnt = self.pathSum(root.right, sum) return cnt +left_cnt +right_cnt if __name__ == '__main__': solution = Solution() root = TreeNode(10) root.left = TreeNode(5) root.right = TreeNode(-3) root.left.left = TreeNode(3) root.left.right = TreeNode(2) root.left.left.left = TreeNode(3) root.left.left.right = TreeNode(-2) root.left.right.left = TreeNode(1) root.right.right = TreeNode(11) print solution.pathSum(root, 8)
# -*- coding:utf-8 -*- # author cherie # jascal@163.com # jascal.net # Merge k Sorted Lists class Solution: def mergeKLists(self, lists): if len(lists) == 0: return None if len(lists) == 1: return lists[0] mid = len(lists) // 2 l1 = self.mergeKLists(lists[:mid]) l2 = self.mergeKLists(lists[mid:]) # merge Two Lists nl = ListNode(0) c = nl while l1 and l2: if l1.val <= l2.val: c.next = l1 l1 = l1.next else: c.next = l2 l2 = l2.next c = c.next c.next = l1 or l2 return nl.next
#coding:utf-8 import PIL.Image as Image import os import sys def compressMutiImage(dirPath): rename(dirPath) fileList = os.listdir(dirPath) for f in fileList: if(".png" in f): if os.path.isfile(f): sImg=Image.open(f) w,h=sImg.size dImg=sImg.resize((w/2,h/2),Image.ANTIALIAS) dImg.save(f) print("succeed"+f) else: print(f+" is not file") def rename(dirPath): fileList = os.listdir(dirPath) for i, f in enumerate(fileList): print(f) if(".png" in f): os.rename(f, str(i)+".png") if __name__=='__main__': compressMutiImage(sys.argv[1])
#This is primegame. this application gives the max difference between 2 primenumbers in a given range of numbers def prime(n): if n<=1: return False for i in range(2,n): if n%i==0: return False return True k=int(input("no.of iterations")) while k>0: l,m = [int(x) for x in input("enter numbers: ").split(" ")] fp=0 lp=0 for i in range(l,m+1): if prime(i): fp=i break for i in range(m,l-1,-1): if prime(i): lp=i break if fp!=lp: print(lp-fp) elif fp==lp and fp!=0: print(0) elif fp==0: print(-1) k-=1
def get_songs(data: dict) -> dict: """ Returns a dictionary of song id: playbacks from data given.""" songs = dict() for item in data["items"]: name = item["track"]["id"] if name in songs: songs.update({name: songs[name]+1}) else: songs[name] = 1 return songs def average_playcount(songs : dict) -> float: """ Returns the average number of playbacks. """ sum = 0 number_of_playcounts = len(songs) for playback in songs.values(): sum += playback average = sum / number_of_playcounts return average def above_average_songs(average: float, songs: dict)-> [str]: """ Returns a list of song ids with playbacks greater than average playbacks.""" songs = sorted(songs.items(), key = lambda kv:(kv[1], kv[0]), reverse = True) top_songs = [] if average == 1: print("You've only played each song once.") return songs.keys() for song in songs: name = song[0] plays = song[1] if plays > average: top_songs.append(name) return top_songs
from starwars import list_of_swapi, detail_profile if __name__ == '__main__': choice = int(input("enter option")) while choice != 6: if choice == 1: choice1 = int(input("enter choice\n1.Starwars people list\n2.Starwars planets list\n3.Starwars films list\n" "4.Starwars species list\n5.Starwars vehicles list\n6.Starwars starships list\n")) if choice1 == 1: list2 = list(list_of_swapi(site="https://swapi.co/api/people/?page=", name="name")) for i in list2: print(i) elif choice1 == 2: list2 = list(list_of_swapi(site="https://swapi.co/api/planets/?page=", name="name")) for i in list2: print(i) elif choice1 == 3: list2 = list(list_of_swapi(site="https://swapi.co/api/films/?page=", name="title")) for i in list2: print(i) elif choice1 == 4: list2 = list(list_of_swapi(site="https://swapi.co/api/species/?page=", name="name")) for i in list2: print(i) elif choice1 == 5: list2 = list(list_of_swapi(site="https://swapi.co/api/vehicles/?page=", name="name")) for i in list2: print(i) elif choice1 == 6: list2 = list(list_of_swapi(site="https://swapi.co/api/starships/?page=", name="name")) for i in list2: print(i) else: print("enter a valid option") elif choice == 2: name_person = "name" string = input("enter name of the person to show details") site = "https://swapi.co/api/people/?page=" dict1 = dict(detail_profile(site, string, name_person)) for key, value in dict1.items(): print(key, value) elif choice == 4: name_person = "name" string = input("enter name of the personpassword" "" " to show details") site = "https://swapi.co/api/people/?page=" dict1 = dict(detail_profile(site, string, name_person)) for key, value in dict1.items(): print(key, value)
#examAnewMark.py import random showAgain = True while showAgain == True: count = 0 totalSum =0 score = 0 for x in range(1,1001): randomNumber= random.randint(1,9) if randomNumber%2 == 0: score = 100 else: score = 60 totalSum += score count += 1 print('There were',count,'students, with an average of',round(totalSum/count,2)) showAgain = input('Simulate again?(y/n)') if showAgain.lower() == 'y': showAgain = True else: showAgain = False print('Thanks for simulating!')
def cipher(): #this encodes just one single letter #store the alphabet as a string alphabet ='abcdefghijklmnopqrstuvwxyz' #get the letter from the user as a string original = input("What is the letter in to encode: ") #get the amount of shift from user as a number shift = eval(input("What is the shift value:")) #the new position of the letter will be the position plus shift number = alphabet.find(original) + shift #print out the new letter with the new position from the alphabet print('Encoded letter is:', alphabet[number]) def cipher2(): #this encodes phrases, but space is part of the encoding alphabet ='abcdefghijklmnopqrstuvwxyz ' original = input("What is the phrase to encode: ") original = original.lower() shift = eval(input("What is the shift value:")) phrase = list(original) numberized = [[x,alphabet.find(x)+shift] for x in phrase] encoded = [x[1] for x in numberized] converted = [[x,alphabet[x]] for x in encoded] convert1= [x[1] for x in converted] print('Original:',original,'\n', 'phrase:',phrase,"\n", 'numberized:',numberized,'\n', 'encoded:',encoded,'\n', 'converted:',converted,'\n', 'convert1:',convert1,'\n', 'Encoded phrase is:',"".join(convert1)) def cipher3(): #this encodes just one single word alternate method #best conversion so far as it deals with the space alphabet ='abcdefghijklmnopqrstuvwxyz' original = input("What is the phrase to encode: ") original = original.lower() shift = eval(input("What is the shift value:")) shift = shift%26 alphabet1=alphabet[:shift] alphabet2=alphabet[shift:] alphabet3=alphabet2+alphabet1+" !?<>@#$%^&*()+_-=[]{}\|`~.," alphabet = alphabet+" !?<>@#$%^&*()+_-=[]{}\|`~.," phrase = list(original) numberized =[alphabet.find(x) for x in phrase] encoded = [alphabet3[x] for x in numberized] print('Original:',original,'\n', 'phrase:',phrase,"\n", 'numberized:',numberized,'\n', 'encoded:', encoded,'\n', 'Encoded phrase:',"".join(encoded)) print('Encoded phrase:',"".join(encoded)) def cipher4(): #this encodes phrase using dictionaries instead of strings and lists alpha2num = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5, 'g':6,'h':7,'i':8,'j':9,'k':10,'l':11, 'm':12,'n':13,'o':14,'p':15,'q':16, 'r':17,'s':18,'t':19,'u':20,'v':21, 'w':22,'x':23,'y':24,'z':25,' ':26} num2alpha = {0:'a',1:'b',2:'c',3:'d',4:'e',5:'f', 6:'g',7:'h',8:'i',9:'j',10:'k',11:'l', 12:'m',13:'n',14:'o',15:'p',16:'q', 17:'r',18:'s',19:'t',20:'u',21:'v', 22:'w',23:'x',24:'y',25:'z',26:' '} original = input("Enter your phrase to be encoded: ") original = original.lower() shift = eval(input("What is the shift value:")) phraseList = list(original) number = [alpha2num[x] for x in phraseList] number1 = [(x+shift)%27 for x in number] encoded = [num2alpha[x] for x in number1] print('original:',original,'\n', 'shift:',shift,'\n', 'phraseList:',phraseList,'\n', 'number:',number,'\n', 'number1:',number1,'\n', 'encoded:',encoded,'\n', 'Encoded phrase:',"".join(encoded)) cipher3()
# CS110Exam_XXX_C_Block.py # XXX, XXX (Jan, 2016) ''' Pseudocode: import the random momdule game = True setup game loop while game = True print welcome message ask user to input name set variables compWins = 0 userWins = 0 loops for roll while userWins does not equal 5 and while compWins does not equal 5 compRoll = random number between 2-12 userRoll = random number between 2-12 if userRoll does not equal compRoll if userRoll is greater than compRoll add 1 to userWins tell the user they win that roll elif userRoll is less than compRoll add 1 to compWins tell the user that the computer won that roll tell the user that it is a tie and to roll again if compWins = 5 tell the user that the computer won if userWins = 5 tell the user that they won asks user to input if they want to play again or not game = False game over message''' import random #imports random module game = True #used to stop game #--------------Welcome Message--------------------- print('Welcome to the Dice Roller game!\nIn this game you will be facing off against a fierce computer name Mr.Computer.\nThe player with the highest sum win!\nMay the odds be in your favor!') #-----------------Game Loop------------------------ while game == True: userName = input('Please enter your name:') compWins = 0 userWins = 0 #-----------------Dice Roll Loop------------------- while userWins != 5 and compWins != 5: rollKey = input('Press enter to roll:') #starts the roll compRoll = random.randint(2,12) #random numbers for the dice rolls userRoll = random.randint(2,12) if userRoll > compRoll: #if the computers roll is bigger at 1 to wins and tells user who won userWins = userWins +1 print((userName),'won this roll') elif userRoll < compRoll: #if the users roll is bigger at 1 to wins and tells user who won compWins = compWins + 1 print('Mr.Computer won this roll') elif userRoll == compRoll: #if the rolls are equal, reroll print('It was a tie, try again!') #-----------------Game Winning Loop---------------- if userWins == 5: #if the user wins 5 rolls they win the game and tells user they won print((userName),'won the game!') elif compWins == 5: #if the computer wins 5 rolls they win the game and tells user that the computer won print('Mr.Computer won the game!') #-----------------Restart-------------------------- playagain = input('Play Again? Type yes or no:') #prompts user to input if they want to play again if playagain != 'yes': #if answer isn't yes, game stops game = False #-----------------Game Over------------------------ print('Thank you',(userName),'for playing the dice game, hope to see you soon!') #game over message
from random import randrange def dieRoll(numDice): x=[] for i in range(numDice): d=randrange(1,7) x.append(d) #print(x) return x def scoring(play,comp): if play>comp: print(namePlayer+' wins with '+str(playRoll),'George only rolled '+str(compRoll)) elif play<comp: print('George wins with '+str(compRoll), 'you only rolled '+str(playRoll)) else: print('TIE... oh no.') print(str(playRoll),str(compRoll)) print(namePlayer+': '+str(playScore)+'\nGeorge: '+str(compScore)) return print('Welcome to Dice Roller!\n'+ 'You will roll two dice against the computer.\n'+ 'The player with the highest sum wins the round.\n'+ 'The computer\'s name is George.\n') namePlayer=input('Please enter your name:') keepGoing = True compScore=0 playScore=0 while keepGoing == True: compRoll = sum(dieRoll(2)) playRoll = sum(dieRoll(2)) if playRoll > compRoll: playScore+=1 scoring(1,0) elif playRoll < compRoll: compScore+=1 scoring(0,1) else: scoring(0,0) pass if compScore>4 or playScore>4: if compScore>4: print('Computer Won!') compScore=0 playScore=0 else: print('You Won!') compScore=0 playScore=0 x=input('Play again? (y/n):') if x == 'y': keepGoing = True else: keepGoing = False if keepGoing==True: x=input('Press Enter Key for next roll\n') print('Ok, thanks for playing.')
# CS110Exam_Colwell_C_Block.py # Colwell, Andrew (Jan, 2016) ''' Pseudocode: import Random set initial variables loop until game ends get random number loop until player stops get user guess add one to guess counter compare with random number == print number of guesses, condition to restart game > random number print guess too high < random number print guess too low ''' import random lowScore = 10000 playGame = True guessAgain = True guessCount = 0 while playGame == True: guess = input('Guess a number between 0 and 9999.') randNumber = random.randint(0,9999) while guessAgain == True: guessCount += 1 guess = eval(guess) if guess == randNumber: guessAgain = False print('You got the number! Only took',guessCount,'tries.') if guessCount < lowScore: print('You have a new lowScore') else: print('Low score is',lowScore,'guesses.') elif guess > randNumber: print('Your guess is high.') guess = input('Guess a number between 0 and 9999.') else: print('Your guess is low.') guess = input('Guess a number between 0 and 9999.') guess = input('Guess a number between 0 and 9999 or "n" to quit.') if guess == 'n': playGame = False randNumber = random.randint(0,9999)
#A5_3 Read three points from a text file #Then draw the triangle with graphics.py from graphics import * from time import sleep #file=open(r'A5_3.txt','r') file=open(r'U:\trianglePoints.txt','r') L1=[] data=file.readline() while data !='': s=data.find('\n') if s>=0: #If there is an \n, data=data[:s] #strip off the escape code l=data.split(',') #split the data into nested lists L1.append(l) #build L1 as the list with numbers as strings data=file.readline() print('Preparing to print a triangle. Hold on to your hats!') print(L1) sleep(3) win=GraphWin('Draw a triangle',300,300) p1=Point(int(L1[0][0]),int(L1[0][1])) #Make points integers from strings p2=Point(int(L1[1][0]),int(L1[1][1])) p3=Point(int(L1[2][0]),int(L1[2][1])) triangle=Polygon(p1,p2,p3) triangle.setFill('green') triangle.draw(win) file.close() print('All done! Hold your applause for later.')
#!/usr/bin/python3 # coding: utf-8 import sys def tag_sort(): """ This mapper sort top 10 tags for each locality name in descending order Input data format: place_url_1 \t {tag_n = count} ... Output data format: place_url_1 \t {tag_top_1 = count} ... {tag_top_10 = count} ... """ top_10_tags = [] for line in sys.stdin: items = line.strip().split('\t') # chekc if the data in the right format if len(items) != 2: continue place_url, tags = items[0].strip(), items[1].strip() split_Tags = tags.split(',') # split tags and ready for sort for tag in split_Tags[0:-1]: split_tag = tag.strip().split(' = ') tag_name, count = split_tag[0].strip(), split_tag[1].strip() top_10_tags.append((tag_name, int(count))) # sort the tag in descending order and find the top 10 reversed_top_10_tags = sorted(top_10_tags, key = lambda x : x[1])[-10:] top_10_list = '' for tag_names, tag_count in reversed(reversed_top_10_tags): top_10 = tag_names + '=' + str(tag_count) top_10_list += top_10 + ', ' print(place_url + '\t' + top_10_list) top_10_tags = [] if __name__ == '__main__': tag_sort()
# -*- coding: UTF-8 -*- x = 33 y = 4 print(x % y) print(x // y) x = 2 y = 3 print(x ** y)
# POINTERS PI = 3.14 print('pi', PI) PI = 3 print('changed pi', PI) first_number = 1 second_number = first_number + 1 print(first_number) print(second_number) first_letter = 'h' second_letter = first_letter # 'h' second_letter = 'hola' print(first_letter) print(second_letter) numbers = [1, 2] more_numbers = numbers third_numbers = more_numbers more_and_more_numbers = third_numbers more_numbers.append(3) print(numbers) print(more_numbers) print(third_numbers) print(more_and_more_numbers) more_and_more_numbers.pop() print(numbers) print(more_numbers) print(third_numbers) print(more_and_more_numbers) carlos = {'name': 'Carlos', 'company': 'Envera'} laura = carlos laura['name'] = 'Laura' print(carlos) print(laura) carlos['surname'] = 'Alvez' print(carlos) print(laura) # COPIES FIRST_LIST = [1, 2, 3] second_list = FIRST_LIST[:] second_list.pop() print(FIRST_LIST) print(second_list) carlos = {'name': 'Carlos', 'company': 'Envera', 'age': 10} laura = dict() #copy laura['company'] = carlos['company'] laura['age'] = carlos['age'] laura['name'] = carlos['name'] #change laura['name'] = 'Laura' print(carlos) print(laura) carlos['surname'] = 'Alvez' print(carlos) print(laura)
"""Demonstration of the Workflow Design Pattern. As the name suggests, this pattern wants to represent workflows. It is basically an extension of the 'Command Pattern' meant for more complex, long-running commands consisting of multiple sub-commands. Workflows also provide multiple ways of evaluation, usually local and remote. A workflow would be a common, pre-defined set of tasks frequently used in a pipeline, for example: - prepare a delivery to the client - publish geometry with a subsequent turntable rendering - ingest data from vendors, including data cleanup and transformation The Workflow builds a Graph and initializes it with user provided settings as well as data taken from other sources (database, filesystem). """ import getpass from flowpipe import Graph, Node class Workflow(object): """Abstract base class defining a workflow, based on a flowpipe graph. The Workflow holds a graph and provides two ways to evaluate the graph, locally and remotely. """ def __init__(self): self.graph = Graph() def evaluate_locally(self): """Evaluate the graph locally.""" self.graph.evaluate() def evaluate_remotely(self): """See examples/vfx_render_farm_conversion.py on how to implement a conversion from flowpipe graphs to your render farm. """ pass class PublishWorkflow(Workflow): """Publish a model and add a turntable render of it to the database.""" def __init__(self, source_file): super(PublishWorkflow, self).__init__() publish = Publish(graph=self.graph) message = SendMessage(graph=self.graph) turntable = CreateTurntable(graph=self.graph) update_database = UpdateDatabase(graph=self.graph) publish.outputs["published_file"].connect( turntable.inputs["alembic_cache"] ) publish.outputs["published_file"].connect( message.inputs["values"]["path"] ) turntable.outputs["turntable"].connect( update_database.inputs["images"] ) # Initialize the graph from user input publish.inputs["source_file"].value = source_file # Initialize the graph through pipeline logic # These things can also be done in the nodes themselves of course, # it's a design choice and depends on the case message.inputs["template"].value = ( "Hello,\n\n" "The following file has been published: {path}\n\n" "Thank you,\n\n" "{sender}" ) message.inputs["values"]["sender"].value = getpass.getuser() message.inputs["values"]["recipients"].value = [ "john@mail.com", "jane@mail.com", ] turntable.inputs["render_template"].value = "template.ma" update_database.inputs["asset"].value = source_file.split(".")[0] update_database.inputs["status"].value = "published" # ----------------------------------------------------------------------------- # # The Nodes used in the Graph # # ----------------------------------------------------------------------------- @Node(outputs=["published_file"]) def Publish(source_file): """Publish the given source file.""" return {"published_file": "/published/file.abc"} @Node(outputs=["return_status"]) def SendMessage(template, values, recipients): """Send message to given recipients.""" print("--------------------------------------") print(template.format(**values)) print("--------------------------------------") return {"return_status": 0} @Node(outputs=["turntable"]) def CreateTurntable(alembic_cache, render_template): """Load the given cache into the given template file and render.""" return {"turntable": "/turntable/turntable.%04d.jpg"} @Node(outputs=["asset"]) def UpdateDatabase(asset, images, status): """Update the database entries of the given asset with the given data.""" return {"asset": asset} if __name__ == "__main__": workflow = PublishWorkflow("model.ma") print(workflow.graph) workflow.evaluate_locally()
# -*- coding: utf-8 -*- """ Created on Sat Jan 20 12:12:37 2018 @author: Admin """ import unittest from calculator import Calculator class CalculatorTest(unittest.TestCase): def setUp(self): self.calc = Calculator() def testPrintDecimalNumbers(self): self.calc.setInput(1) self.calc.setInput(.23) self.calc.setInput(45) self.assertEqual("1.2345", self.calc.number) def testShowInputError(self): self.calc.setInput('df') self.assertEqual("Incorrect Input, please try again !", "Incorrect Input, please try again !") self.calc.setInput('*123') self.assertEqual("Incorrect Input, please try again !", "Incorrect Input, please try again !") def testShowInputOrderError(self): self.calc.setInput('+') self.assertEqual("Incorrect Input, please enter a number first, then enter your calc function !", "Incorrect Input, please enter a number first, then enter your calc function !") def testEndProgram(self): self.calc.setInput('e') self.assertEqual("Goodbye!", "Goodbye!") self.calc.setInput('E') self.assertEqual("Goodbye!", "Goodbye!") #testing the calculation operator def testAdd(self): self.assertEqual(4, self.calc.operators2Num["+"](2, 2)) self.assertEqual(5, self.calc.operators2Num["+"](2, 3)) self.assertEqual(-1, self.calc.operators2Num["+"](2, -3)) self.assertEqual(0, self.calc.operators2Num["+"](2, -2)) self.assertEqual(2, self.calc.operators2Num["+"](2, 0)) self.assertEqual(-5, self.calc.operators2Num["+"](-2, -3)) def testSubtract(self): self.assertEqual(0, self.calc.operators2Num["-"](2, 2)) self.assertEqual(-1, self.calc.operators2Num["-"](2, 3)) self.assertEqual(5, self.calc.operators2Num["-"](2, -3)) self.assertEqual(4, self.calc.operators2Num["-"](2, -2)) self.assertEqual(2, self.calc.operators2Num["-"](2, 0)) self.assertEqual(1, self.calc.operators2Num["-"](-2, -3)) def testDivide(self): self.assertEqual(1, self.calc.operators2Num["/"](2, 2)) self.assertEqual(-1, self.calc.operators2Num["/"](2, -2)) self.assertEqual(0, self.calc.operators2Num["/"](2, 0)) self.assertEqual(-2, self.calc.operators2Num["/"](2, -1)) self.assertEqual(2, self.calc.operators2Num["/"](2, 1)) self.assertEqual(2, self.calc.operators2Num["/"](3, 1.5)) self.assertEqual(.5, self.calc.operators2Num["/"](2., 4)) self.assertEqual(-.5, self.calc.operators2Num["/"](2., -4)) def testMultiply(self): self.assertEqual(4, self.calc.operators2Num["*"](2, 2)) self.assertEqual(6, self.calc.operators2Num["*"](2, 3)) self.assertEqual(-6, self.calc.operators2Num["*"](2, -3)) self.assertEqual(-4, self.calc.operators2Num["*"](2, -2)) self.assertEqual(0, self.calc.operators2Num["*"](2, 0)) self.assertEqual(6, self.calc.operators2Num["*"](-2, -3)) self.assertEqual(2, self.calc.operators2Num["*"](2, 1)) self.assertEqual(3, self.calc.operators2Num["*"](2, 1.5)) def testRemainder(self): self.assertEqual(0, self.calc.operators2Num["%"](2, 2)) self.assertEqual(2, self.calc.operators2Num["%"](2, 4)) self.assertEqual(-2, self.calc.operators2Num["%"](2, -4)) self.assertEqual(0, self.calc.operators2Num["%"](2, -2)) self.assertEqual(0, self.calc.operators2Num["%"](2, -2)) self.assertEqual(0, self.calc.operators2Num["%"](2, 0)) self.assertEqual(0, self.calc.operators2Num["%"](2, 1)) self.assertEqual(-2, self.calc.operators2Num["%"](-2, -4)) def testSquared(self): self.assertEqual(4, self.calc.operators1Num["x^2"](2)) self.assertEqual(25, self.calc.operators1Num["x^2"](5)) self.assertEqual(9, self.calc.operators1Num["x^2"](-3)) self.assertEqual(2.25, self.calc.operators1Num["x^2"](1.5)) self.assertEqual(0, self.calc.operators1Num["x^2"](0)) def testSquareRoot(self): self.assertEqual(3, self.calc.operators1Num["sqR"](9)) self.assertEqual(0, self.calc.operators1Num["sqR"](-9)) self.assertEqual(.3, self.calc.operators1Num["sqR"](.09)) self.assertEqual(0, self.calc.operators1Num["sqR"](0)) self.assertEqual(2.5, self.calc.operators1Num["sqR"](6.25)) def testCubed(self): self.assertEqual(8, self.calc.operators1Num["cube"](2)) self.assertEqual(27, self.calc.operators1Num["cube"](3)) self.assertEqual(-8, self.calc.operators1Num["cube"](-2)) self.assertEqual(0, self.calc.operators1Num["cube"]( 0)) self.assertAlmostEqual(29.791, self.calc.operators1Num["cube"](3.1), delta=0.001) def testCubedRoot(self): self.assertEqual(2, self.calc.operators1Num["cubeR"](8)) self.assertEqual(3, self.calc.operators1Num["cubeR"](27)) self.assertEqual(2, self.calc.operators1Num["cubeR"](-8)) self.assertEqual(0, self.calc.operators1Num["cubeR"](0)) def testAbsoluteValues(self): self.assertEqual(2, self.calc.operators1Num["abs"](2)) self.assertEqual(1.5, self.calc.operators1Num["abs"](-1.5)) self.assertEqual(0, self.calc.operators1Num["abs"](0)) def testShouldPrintUserInput(self): self.calc.setInput(1) self.calc.setInput(1) self.calc.setInput(1) self.assertEqual(111.0, float(self.calc.number)) def testShouldAddUserInput(self): self.calc.setInput(1) self.calc.setInput(1) self.calc.setInput(1) self.calc.setInput("+") self.calc.setInput(7) self.assertEqual(118.0, self.calc.getCalculator2NumResult("+")) def testShouldSubtractUserInput(self): self.calc.setInput(1) self.calc.setInput(1) self.calc.setInput(1) self.calc.setInput("-") self.calc.setInput(7) self.assertEqual(104.0, self.calc.getCalculator2NumResult("-")) def testShouldDivideUserInput(self): self.calc.setInput(1) self.calc.setInput("/") self.calc.setInput(2) self.assertEqual(0.5, self.calc.getCalculator2NumResult("/")) self.calc.setInput(1) self.calc.setInput("/") self.calc.setInput(0) self.assertEqual(0, self.calc.getCalculator2NumResult("/")) self.calc.setInput(1) self.calc.setInput("/") self.calc.setInput(-1) self.assertEqual(-1, self.calc.getCalculator2NumResult("/")) def testShouldMultiplyUserInput(self): self.calc.setInput(1) self.calc.setInput("*") self.calc.setInput(2) self.assertEqual(2, self.calc.getCalculator2NumResult("*")) self.calc.setInput(10) self.calc.setInput("*") self.calc.setInput(-10) self.assertEqual(-100, self.calc.getCalculator2NumResult("*")) self.calc.setInput(-1.5) self.calc.setInput("*") self.calc.setInput(-1.5) self.assertEqual(2.25, self.calc.getCalculator2NumResult("*")) def testShouldRemainderUserInput(self): self.calc.setInput(10) self.calc.setInput("%") self.calc.setInput(2) self.assertEqual(0, self.calc.getCalculator2NumResult("%")) self.calc.setInput(10) self.calc.setInput("%") self.calc.setInput(-10) self.assertEqual(0, self.calc.getCalculator2NumResult("%")) self.calc.setInput(-1.5) self.calc.setInput("%") self.calc.setInput(-1.5) self.assertEqual(0, self.calc.getCalculator2NumResult("%")) def testShouldSquareUserInput(self): self.calc.setInput(10) self.calc.setInput("x^2") self.assertEqual(100, self.calc.getCalculator1NumResult("x^2")) self.calc.setInput(-10) self.calc.setInput("x^2") self.assertEqual(100, self.calc.getCalculator1NumResult("x^2")) self.calc.setInput(-1.5) self.calc.setInput("x^2") self.assertEqual(2.25, self.calc.getCalculator1NumResult("x^2")) def testShouldSquareRootUserInput(self): self.calc.setInput(25) self.calc.setInput("sqR") self.assertEqual(5, self.calc.getCalculator1NumResult("sqR")) self.calc.setInput(2116) self.calc.setInput("sqR") self.assertEqual(46, self.calc.getCalculator1NumResult("sqR")) self.calc.setInput(-2116) self.calc.setInput("sqR") self.assertEqual(0, self.calc.getCalculator1NumResult("sqR")) def testShouldCubeUserInput(self): self.calc.setInput(10) self.calc.setInput("cube") self.assertEqual(1000, self.calc.getCalculator1NumResult("cube")) self.calc.setInput(-10) self.calc.setInput("cube") self.assertEqual(-1000, self.calc.getCalculator1NumResult("cube")) self.calc.setInput(-1.5) self.calc.setInput("cube") self.assertEqual(-3.375, self.calc.getCalculator1NumResult("cube")) def testShouldCubeRootUserInput(self): self.calc.setInput(1000) self.calc.setInput("cubeR") self.assertAlmostEqual(10, self.calc.getCalculator1NumResult("cubeR"), delta = .001) self.calc.setInput(-1000) self.calc.setInput("cubeR") self.assertAlmostEqual(10, self.calc.getCalculator1NumResult("cubeR"), delta = .001) self.calc.setInput(125) self.calc.setInput("cubeR") self.assertEqual(5, self.calc.getCalculator1NumResult("cubeR")) def testShouldAbsoluteUserInput(self): self.calc.setInput(-10) self.calc.setInput("abs") self.assertEqual(10, self.calc.getCalculator1NumResult("abs")) self.calc.setInput(-1.5) self.calc.setInput("abs") self.assertEqual(1.5, self.calc.getCalculator1NumResult("abs")) unittest.main()
#! /usr/bin/python row = "+-----" def row1(): for i in range(4): print(row,end="") print("+") def col1(): for i in range(4): for i in range(4): print("| ",end=" ") print("|") for i in range(4): row1() col1() row1()
#!/usr/bin/env python # coding: utf-8 # In[ ]: # Definition for a binary tree node. class TreeNode(object): def __init__(self,x): self.val = x self.left = None self.right = None self.parent = None """ :type val: int :type left: TreeNode or None :type right: TreeNode or None """ class Solution(object): def insert(self, root, val): """ :type root: TreeNode :type val: int :rtype: TreeNode(inserted node) """ if root = None: root = val elif self.left > self.right: self.left = val else self.right = val def delete(self, root, target): """ :type root: TreeNode :type target: int :rtype: TreeNode(the root of new completed binary search tree) (cannot search()) """ def search(self, root, target): """ :type root: TreeNode :type target: int :rtype: TreeNode(searched node) """ def modify(self, root, target, new_val): """ :type root: TreeNode :type target: int :type new_val: int :rtype:TreeNode(the root of new completed binary search tree) (cannot search()) """ # In[ ]:
""" Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1, 2, 2, 3, 4, 4, 3] is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 output: true But the following [1, 2, 2, null, 3, null, 3] is not: 1 / \ 2 2 \ \ 3 3 output: false """ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # Recursive # def isSymmetric(self, root: TreeNode) -> bool: # if not root: # return True # # def isMirror(node1, node2): # if not node1 or not node2: # return node1 == node2 # if node1.val != node2.val: # return False # return isMirror(node1.left, node2.right) and isMirror(node1.right, node2.left) # # return isMirror(root.left, root.right) # Stack def isSymmetric(self, root: TreeNode) -> bool: if root is None: return True stack = [(root, root)] while stack: node1, node2 = stack.pop() if node1 is None and node2 is None: pass elif node1 is None or node2 is None: return False elif node1.val != node2.val: return False else: stack.append((node1.left, node2.right)) stack.append((node1.right, node2.left)) return True