text
stringlengths
37
1.41M
import asyncio import time def fetch(url): """Make the request and return the results """ pass def worker(name, queue, results): """ A function to take the unmake requests from a queue and perform the work then add results to the results list.""" pass async def distribute_work(url, requests, concurrency, results): """ Divide up the work into batches and collect the final results """ queue = asyncio.Queue() for _ in range(requests): queue.put_nowait(url) tasks = [] for i in range(concurrency): task = asyncio.create_task(worker(f"worker-{i+1}", queue, results)) tasks.append(task) started_at = time.monotonic() await queue.join() total_time = time.monotonic() - started_at for task in tasks: task.cancel() print("---") print( f"{concurrency} workers took {total_time:.2f} seconds to complete {len(results)} requests" ) def assault(url, requests, concurrency): """ Entrypoint to making requests """ results = [] asyncio.run(distribute_work(url, requests, concurrency, results)) print(results) pass
# -*- coding: utf-8 -*- def twoNumber(): number1= raw_input("请输入第一个数字:") number2= raw_input("请输入第二个数字:") if number1>number2: print number1,"大于",number2 elif number2>number1: print number2,"大于",number1 else: print number1,"等于",number2 def threeNumber(): l = [] for i in range(3): x = int(raw_input("请输入数字:")) l.append(x) l.sort() print l[2],"大于",l[1],"大于",l[0] type=int(raw_input("2个数字比较大小请输入2,三个数字比较大小请输入3。")) if type == 2: twoNumber() elif type ==3: threeNumber() else: print "输入比较大小类型错误!"
sum1 = 0 for i in range(1, 101): sum1 = sum1 + i*i print('sum1', sum1) sum2 = 0 for j in range(1, 101): sum2 = sum2 + j print('sum2', sum2) sum3 = 0 sum3 = sum2 * sum2 print('sum3', sum3) diff = 0 diff = sum3 - sum1 print('difference', diff)
from datetime import datetime def get_collatz_sequence(num): collatz_sequence = [num] while num != 1: if num % 2 == 0: num = num//2 else: num = 3 * num + 1 collatz_sequence.append(num) return collatz_sequence num_seq_length_map = {} def get_collatz_sequence_length(number): num = number sequence_length = 0 while num != 1: print(num_seq_length_map) if num in num_seq_length_map: sequence_length += num_seq_length_map[num] break if num % 2 == 0: num = num//2 else: num = 3 * num + 1 sequence_length += 1 num_seq_length_map[num] = sequence_length num_seq_length_map[number] = sequence_length return sequence_length def main(): max_l = 0 num = 1 for i in range(1, 10): l = get_collatz_sequence_length(i) if l > max_l: max_l = l num = i print(num_seq_length_map) print() print(num, max_l) if __name__ == '__main__': # print(datetime.now()) main() # print(get_collatz_sequence_length(50)) # print(get_collatz_sequence_length(70)) # print(datetime.now())
from collections import defaultdict class Graph: def __init__(self, graph): self.graph = graph self. ROW = len(graph) # Використання BFS як алгоритму пошуку def searching_algo_BFS(self, s, t, parent): visited = [False] * (self.ROW) queue = [] queue.append(s) visited[s] = True while queue: u = queue.pop(0) for ind, val in enumerate(self.graph[u]): if visited[ind] == False and val > 0: queue.append(ind) visited[ind] = True parent[ind] = u return True if visited[t] else False # Застосування алгоритму def ford_fulkerson(self, source, sink): parent = [-1] * (self.ROW) max_flow = 0 while self.searching_algo_BFS(source, sink, parent): path_flow = float("Inf") s = sink while(s != source): path_flow = min(path_flow, self.graph[parent[s]][s]) s = parent[s] # додавання потоків шляху max_flow += path_flow # Оновлення залишкових значень ребер v = sink while(v != source): u = parent[v] self.graph[u][v] -= path_flow self.graph[v][u] += path_flow v = parent[v] return max_flow graph1 = [[0, 20, 20, 40, 0, 0, 0, 0], [0, 0, 10, 0, 10, 0, 0, 0], [0, 0, 0, 20, 20, 0, 0, 0], [0, 0, 0, 0, 0, 20, 20, 0], [0, 0, 0, 0, 0, 0, 0, 30], [0, 0, 10, 0, 20, 0, 0, 20], [0, 0, 0, 0, 0, 10, 0, 20], [0, 0, 0, 0, 0, 0, 0, 0]] f = open('l4-2.txt', 'rt') graph = [] i = 0 for line in f: lines = line.split(' ') lst = [] for ln in lines: ln = ln.rstrip() if ln != '': num = int(ln) lst = lst + [num] graph = graph + [lst] print("Вхідні дані = ", graph) f.close() g = Graph(graph) source = 0 sink = 3 print("Максимальний потік: %d " % g.ford_fulkerson(source, sink))
#test_爬取来自www.doutula.com的表情包 from urllib import request from urllib import parse import urllib import re import sys import os import time page=1 x=0 totolnum=0 sys.stdin.encoding def filename(keyword): path=os.path.abspath('.') newpath=path+'\\img\\'+keyword if(os.path.exists(newpath)==False): os.makedirs(path+'\\img\\'+keyword) return newpath def link(keyword,pagenum): qkeyword=urllib.parse.quote(keyword) page="&page="+str(pagenum) search='search?type=photo&more=1&keyword=' url="http://www.doutula.com/" link=url+search+qkeyword+page req=request.Request(link) req.add_header('user-agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36') text=request.urlopen(req).read() text=text.decode('utf-8') return text def content(keyword,pagenum): text=link(keyword,pagenum) pattern1='data-original="(http|https):(/|\w|\.)+(gif|jpg|png)"' match=re.finditer(pattern1,text) return match keyword=input("请输入想要爬取的表情包的名字 ") page=int(input("请输入爬取页数 ")) newpath=filename(keyword) if os.path.exists('match.txt')==True: os.remove('match.txt') for pagei in range(1,page+1): match=content(keyword,pagei) f=open('match.txt','a+') f.write('\n') for i in match: f.write(i.group()) f.write('\n') totolnum+=1 f.close() f=open('match.txt','r+') str=f.read() pattern2='(http|https):(/|\w|\.)+(gif|jpg|png)' src=re.finditer(pattern2,str) for i in src: urllib.request.urlretrieve(i.group(),newpath+'\\'+'%s.jpg' %(x+1)) x+=1 print('正在爬取%d/%d' %(x,totolnum)) time.sleep(0.8) f.close() if totolnum==0: print('对不起,找不到关于%s的表情包,请重新输入' %keyword) else: print('爬取完成,爬取%d个文件\n保存在%s' %(totolnum,newpath))
#list_of_numbers = [0, 1, 2, 3, "blue", 5] #for loops #for elem in list_of_numbers: # print(elem) #for loops #for elem in list_of_numbers: # if type(elem) == str: # continue # print(elem) #range loop #for i in range(5, 20, 3): # print(i) #for i in range(5): # print(i) #i = 0 #while i<10: #print(i) #i = i + 1 #i += 1 #i = 0 #while True #i += 1 #print(i) #if i>10: #break #=========iteration labs from slides================ #Q1 #for i in range(5): # print(i) #i = 0 #while i<8: #print(i) #i = i + 1 #i += 1 #Q2 #x = 0 #while(x < 100): # x+=2 # print(x) #Q3 """input(int("enter number")) if N%2 == 0: print("weird") elif N >= 2 && N <= 5: print("not weird") elif N >= 6 && N <= 20: print("weird") else: print("not weird")""" #++++++++++++++++++++++++ #If n is odd, print Weird #If n is even and in the inclusive range of 2 to 5, print Not Weird #If n is even and in the inclusive range of 6 to 20, print Weird #If n is even and greater than 20, print Not Weird #import sys N = int(input("enter number: ")) if N % 2 != 0: print("Weird") else: if N >= 2 and N <= 5: print ("Not Weird") elif N >= 6 and N <= 20: print ("Weird") elif N > 20: print ("Not Weird") #++++++++++++++++++++++++++++++++++++++++
import random def jogo_advinha(): print("*****************************") print("Bem vindo ao jogo de adivinha") print("*****************************") tentativas = 0 numero_usuario = 0 numero_aleatorio = 0 #while((tentativas < 3) & (numeroUsuario != 10) ): for tentativas in range(1, 4): numero_aleatorio = random.randrange(0, 100) numero_usuario = input("Digite seu numero entre 1 e 100: ") print("Numero do usuario = ", numero_usuario) try: numero_usuario = int(numero_usuario) if(numero_usuario < 0 or numero_usuario > 100): raise Exception("Numero fora do padrao") if(numero_usuario == numero_aleatorio): print("Voce Acertou") break else: if(numero_usuario > numero_aleatorio): print("Voce Errou, chutou um numero maior") if(numero_usuario < numero_aleatorio): print("Voce Errou, chutou um numero menor") except Exception as Err: print("Ops...", Err) def somar(a, b): return a + b; if (__name__ == "__main__"): jogo_advinha()
import tkinter as tk root = tk.Tk() root.title('A simple entry') root.geometry('300x100+50+50') lb = tk.Label(root, text='Enter:') lb.pack(side='left', padx=10) e = tk.StringVar() # 创建StringVar字符串变量 ety = tk.Entry(root, width=30, textvariable=e) ety.pack(side='left', padx=10) e.set('This is an entry!') root.mainloop()
import numpy as np import matplotlib.pyplot as plt def apply_linear_regression(data): X_train=data[:,0][:80] Y_train=data[:,1][:80] alpha=0.001 theta=np.array([1,1]) iterations=100 X_1=X_train for i in range(iterations): theta_0=theta[0]- alpha * (1/len(Y_train)) * np.sum([np.dot(X_train[i],theta)- Y_train[i] for i in range(len(Y_train))]) theta_1=theta[1] - alpha * (1/len(Y_train)) * np.sum([np.dot(X_1[i],np.dot(X_train[i],theta)-Y_train[i])for i in range(len(Y_train))]) theta= np.array([theta_0,theta_1]) return theta def mse(data,prediction): line=prediction[1]*data[:,0] + prediction[0] true_y=data[:,1] square_error=[] for i in range(len(line)): square_error.append((line[i]-true_y[i])**2) return sum(square_error)/len(line) data=np.load("linRegData.npy") l=apply_linear_regression(data) MSE=mse(data,l) print(MSE) X_test=data[:,0][80:100] Y_test=data[:,1][80:100] line=l[1]*X_test + l[0] line2=l[1]*data[:,0] + l[0] # Plot outputs plt.figure(1) plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.subplot('231') plt.scatter(data[:,0],data[:,1], color='black') plt.title("plot_of_data") plt.subplot('232') plt.scatter(data[:,0],data[:,1], color='black') plt.plot(data[:,0],line2, color='blue') plt.title("regression_line_fullData") plt.subplot('233') plt.scatter(X_test, Y_test, color='black') plt.plot(X_test, line, color='blue') plt.title("regressionline_testData") plt.show()
#!/usr/bin/env python ''' Split Input: string and and character to split on Output: create list with the string split based on character submitted ''' def split(string, char=None): create_list = [] start,stop = 0,0 if char==None: char = '' for i, letter in enumerate(string): if letter == char: stop = i create_list.append(string[start:stop]) start = i+1 if i == (len(string)-1): create_list.append(string[start:len(string)]) return create_list if __name__ == '__main__': # Test section print split('s p l i t', ' ') # how to run it with no split value?
#!/usr/bin/env python ''' Turn Matrix Input: 3x3 matrix of integers Output: Rotate the matrix by 90 degrees and return rotated matrix Example: 1 2 3 4 5 6 7 8 9 Switch to: 7 4 1 8 5 2 9 6 3 ''' #Set data structure as a list of coordinates def flip_matrix(mat): mid = int(len(matrix/6)) for i, coord in enumerate(matrix): if i == 0: pass # if x is 1 then it just flips x & y elif mid == coord[0]: coord[0], coord[1] = coord[1], coord[0] # if x is less than 1 then x becomes y and y becomes 2 elif mid > coord[1]: coord[0] = coord[1] coord[1] = mid + 1 # if x is greater than 1 then x becomes y and y becomes 1 elif mid < coord[0]: coord[0] = coord[1] coord[1] = mid - 1 #Improved approach is new[x,y] = old [y,2-x] """ Input: Given an NxN matrix Output: Rotate the matrix by 90 degrees and return rotated matrix. Example: input: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] output: [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]] Note: claudiay contributed additional example and test """ # Short without zip def rotate(matrix): return [[j[i] for j in matrix][::-1] for i in range(len(matrix))] # Python trick answer, returns an array with tuples def rotate_with_zip(matrix): return zip(*matrix[::-1]) # A expanded version to explain each step def rotate_explain(matrix): n = len(matrix) new_matrix = [] for i in range(n): new_row = [] for row in matrix: new_row.append(row[i]) new_matrix.append(new_row[::-1]) # Reverse new_row before appending. return new_matrix # Rotate the matrix in place, without creating another matrix # Ideal for situations processing a large matrix with limited space def rotate_in_place(matrix): n = len(matrix) for i in range(n/2): for j in range(n/2 + n%2): swap = matrix[i][j] for k in range(4): swap, matrix[j][n-i-1] = matrix[j][n-i-1], swap i, j = j, n - i - 1 return matrix if __name__ == '__main__': # Test section matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] odd_matrix = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]] #Test section print rotate(matrix) print rotate_with_zip(matrix) print rotate_explain(matrix) print rotate_in_place(matrix) print rotate(odd_matrix) print rotate_with_zip(odd_matrix) print rotate_explain(odd_matrix) print rotate_in_place(odd_matrix)
list = [5,3,7,5,1,2,5,6] target = 10 def add(list, target): #make a dictionary of nums in the list #to make the lookup faster num_dict = {} for i, num in enumerate(list): if num not in num_dict: num_dict[num] = [i] else: num_dict[num].append(i) # now go through each number in the list for i, num in enumerate(list): diff = target - num #this is for, for example, #if you're looking for 10 #and you get a 5 in the list #you need another 5 if diff == num: if len(num_dict[num]) > 1: return True #look for the difference in the dict. #if it's there then you've got #your sum if diff in num_dict: return True return False # putting the list in a dictionary first # passes through the list once, giving it # a time of n, then going through the # the list again is another n which makes # 2n. Since integers don't matter much # it's n time. l1 = [5,4,7,2,1,8,3] l2 = [8,1,2,7,5,3] # missing number = 4 def missing(l1, l2): l1.sort() l2.sort() if len(l1) > len(l2): longest = l1 second = l2 else: longest = l2 second = l1 for i, num in enumerate(longest): if i == len(longest)-1: return longest[i] elif num != second[i]: return num # This is bad n time because the sort algorithm takes # some amount of time (i don't know because it's set # by the programming language, then n again to go through # the list again.) # The best way to do it is add both lists up # and subtract them # sum(l1) = 30 # sum(l2) = 26 # difference is 4 :)
#!/usr/bin/env python """ Sentence Sort Input: sentence Output: sort a sentence by length of words Example: Input: "This is a fun interview" Output: "a is fun this interview" Original problem/solution submission from jofusa """ def pythonic_approach(sentence): """ This utilize's python's first class functions and the optional paramater to sort arrays """ return ' '.join(sorted(sentence.split(), key = len))
#!/usr/bin/env python ''' Depth First Search (DFS) Input: tree of names and search for existance of one name Output: true or false if the name is found ''' class Node(): def __init__(self, val): self.val = val self.left = None self.right = None def add(value): pass # handle adding nodes # Recursive solution - O(n) def dfs(self, person): if not self.val: return False else: if self.val == person: return True else: if self.left: return self.left.dfs(person) if self.right: return self.right.dfs(person) if __name__ == '__main__': # Build out the tree. n = Node('Lola') n2 = Node('Ann') n3 = Node('Rose') n4 = Node('Janice') n5 = Node('Harriet') n6 = Node('Louis') n7 = Node('Gertrude') n.left = n2 n.right = n3 n.right.left = n4 n.right.right = n5 n.left.left = n6 n.left.right = n7 # Test section implementations = [n.dfs] person_search = 'Louis' person_search2 = 'George' result = True result2 = False for impl in implementations: print "trying %s" % impl print " f(%s) == %s: %s" % (person_search, person_search, impl(person_search) == result) print " f(%s) == %s: %s" % (person_search2, person_search2, impl(person_search2) == result2)
class Vehicle: #vehicle class def _init_(self, number, make, model, year, vin, value, dealer): self.number = number self.make = make self.model = model self.year = year self.vin = vin self.value = value self.dealer = dealer m = [] #instances are stored here def Choosevehicle(action): global num num = 0 while True: num = raw_input("Which vehicle number would you like to %s? \nType 'menu' to return to the main menu. " %action) if num.isdigit() == False: if num == 'menu': menu() else: print "Invalid input" elif num.isdigit() == True: if int(num) <= len(m): return int(num) False break else: print "Invalid Input" def Displaydirec(): for i in m: #print entire directory print "Vehicle: # %d" %i.number print "Make: ", i.make print "Model: ",i.model print "Year: %d" %i.year print "VIN: ", i.vin print "Value: $%.2f" %i.value print "Dealer: %s\n" %i.dealer def Display(i): #display one vehicle print "Vehicle: # %d" %i.number print "Make: ", i.make print "Model: ",i.model print "Year: %s" %i.year print "VIN: ", i.vin print "Value: $%.2f" %i.value print "Dealer: %s\n" %i.dealer def addVehicle(): #add vehicle to inventory new = Vehicle() new.number = len(m)+1 print "This is vehicle number %d in the inventory" %new.number new.make = raw_input("What is the make of the vehicle? ") new.model = raw_input("What is the model of the vehicle? ") new.year = input("What is the year of the vehicle? ") new.vin = int(input("What is the VIN of the vehicle? ")) new.value = float(input("What is the value of the vehicle? ")) new.dealer = raw_input("Which dealership is the vehicle located at? ") m.append(new) print "A %d %s %s has been added to the directory." %(new.year, new.make, new.model) def Updatevehicle(): if len(m) == 0: print "No vehicles in directory. Please add a vehicle first." menu() num = Choosevehicle("update") Display(m[int(num)-1]) #print [Display(i) for i in m if i.number == num] #show you the vehicle you selected while True: cat = (raw_input("Which category would you like to update?\n'Menu' to return to the main menu. ")).lower() if cat == 'menu': menu() elif cat == 'make': print "The current make is ", m[(num)-1].make m[(num)-1].make = raw_input("What is the new value? ") elif cat == 'model': print "The current model is ", m[(num)-1].model m[(num)-1].model = raw_input("What is the new value? ") elif cat == 'year': print "The current year is ", m[(num)-1].year m[(num)-1].year = raw_input("What is the new value? ") elif cat == 'vin': print "The current vin is ", m[(num)-1].vin m[(num)-1].vin = raw_input("What is the new value? ") elif cat == 'value': print "The current value is ", m[(num)-1].value m[(num)-1].value = float(raw_input("What is the new value? ")) elif cat == 'dealer': print "The current dealer is ", m[(num)-1].dealer m[(num)-1].dealer = raw_input("What is the new value? ") else: print "Please enter a valid category or type 'menu' to return to the main menu." #print "The current %s value is %d." %(cat, m[(num)-1].cat) #How to input class instance variable? print "Success. The new directory item is:" Display(m[(num)-1]) menu() def Deletevehicle(): x = Choosevehicle("delete") Display(m[(x - 1)]) y = raw_input("Are you sure you want to delete vehicle #%s? " %m[(x-1)].number) if y == 'y' or 'yes': del m[(x-1)] def menu(): #main menu while True: print " Main Menu\n" print "1. Display Inventory\n" print "2. Add to Inventory\n" print "3. Update a Vehicle\n" print "4. Delete from Inventory\n" print "5. Sort Inventory by VIN\n" print "6. Search inventory by Model\n" print "7. Read inventory from file\n" print "8. Write inventory to file and exit\n" choice = raw_input("Type the number of what you would like to do. ") if choice == '1': if len(m) == 0: print "Error. No vehicles in directory." #Error checking menu() Displaydirec() back = raw_input("Type 'menu' to return to the main menu ") if back == "menu": menu() else: back = raw_input("invalid input") elif choice == '2': addVehicle() menu() elif choice == '3': Displaydirec() Updatevehicle() elif choice == '4': Displaydirec() Deletevehicle() elif choice == '8': with open('VehicleInventory.txt', 'w') as open_file: for i in m: open_file.write("Vehicle #:") open_file.write(str(i.var)) open_file.write("\n") open_file.write("Make: ") open_file.write(str(i.make)) open_file.write("\n") open_file.write("Model: ") open_file.write(str(i.model)) open_file.write("\n") open_file.write("Year: ") open_file.write(str(i.year)) open_file.write("\n") open_file.write("Value: ") open_file.write(str(i.value)) open_file.write("\n") open_file.write("Dealer: ") open_file.write(str(i.dealer)) open_file.write("\n") open_file.write("\n") else: print "Invalid choice." continue menu()
#Resource: https://www.youtube.com/watch?v=EItlUEPCIzM #Resource: https://towardsdatascience.com/k-means-clustering-for-beginners-ea2256154109 #Resource: https://stackoverflow.com/questions/42169892/is-there-a-way-to-limit-the-amount-of-while-loops-or-input-loops #Some hints on how to start, as well as guidance on things which may trip you up, have been added to this file. #You will have to add more code that just the hints provided here for the full implementation. #You will also have to import relevant libraries for graph plotting and maths functions. import matplotlib.pyplot as plt import numpy as np import csv from sklearn.metrics import pairwise_distances_argmin from collections import Counter, defaultdict #Allow user to set amount of clusters and iterations num_of_clusters = int(input("Enter desired number of clusters: ")) iterations = int(input("Enter desired number of iterations: ")) # Define a function that reads data in from the csv files # HINT: http://docs.python.org/2/library/csv.html. # HINT2: Remember that CSV files are comma separated, so you should use a "," as a delimiter. # HINT3: Ensure you are reading the csv file in the correct mode. def read_csv(): x = [] y = [] countries = [] x_label = "" y_label = "" with open('dataBoth.csv') as csvfile: reader = csv.reader(csvfile, delimiter=',') lines = 0 for row in reader: if lines >= 1: print(', '.join(row)) x.append(float(row[1])) y.append(float(row[2])) countries.append(row[0]) lines += 1 else: x_label = row[1] y_label = row[2] print(', '.join(row)) lines += 1 return x, y, x_label, y_label, countries x, y, x_label, y_label, countries = read_csv() #Call np.vstack() method which is used to stack the sequence of input arrays vertically to make a single array #In other words we combine x and y into a 2D list of pairs #Plot and display scatter plot X = np.vstack((x, y)).T plt.xlabel(x_label) plt.ylabel(y_label) plt.scatter(x, y, color='green') plt.show() # Implement the k-means algorithm, using appropriate looping for the number of iterations # --- find the closest centroid to each point and assign the point to that centroid's cluster # --- calculate the new mean of all points in that cluster # --- visualise (optional, but useful to see the changes) #---- repeat def find_clusters(X, n_clusters, rseed=2): #Create randomly choose clusters rng = np.random.RandomState(rseed) i = rng.permutation(X.shape[0])[:n_clusters] centers = X[i] count = 0 #While loop to try and find convergence #Note count variable is set to 0 and increases by one with every iteration of this loop #The loop continues until count == iterations as chosen by user #Assign labels based on closest center #Use pairwise_distances_argmin method to calculate the squared distance between each point and the # centroid to which it belongs based on example from resource at top of sheet and as per compulsary task 2 # instructions #Find new centers from means of points print("\nConverging centres:") while count < iterations: count += 1 labels = pairwise_distances_argmin(X, centers) new_centers = np.array([X[labels == i].mean(0) for i in range(n_clusters)]) if np.all(centers == new_centers): centers = new_centers #Print out this sum once on each iteration, and you can watch the objective function converge # as per compulsary task 2 instrucions print(centers) print() return centers, labels #Revisualize scatter plot to see the changes centers, labels = find_clusters(X, num_of_clusters) plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='viridis') plt.title('K-Means clustering of countries by birth rate vs life expectancy') plt.xlabel(x_label) plt.ylabel(y_label) plt.show() # Print out the results for questions #1.) The number of countries belonging to each cluster #2.) The list of countries belonging to each cluster #3.) The mean Life Expectancy and Birth Rate for each cluster print("\nNumber of countries in each cluster:") print(Counter(labels)) clusters_indices = defaultdict(list) for index, c in enumerate(labels): clusters_indices[c].append(index) x = 0 while x < num_of_clusters: print("\nCluster " + str(x + 1)) print("----------") for i in clusters_indices[x]: print(countries[i]) print("----------") print("Mean birth rate:") print(centers[x][0]) print("Mean life expectancy:") print(centers[x][1]) x+=1
import pygame as pg from data.constants import * from gui.widgets.animated_widget import AnimatedWidget class TextWidget(AnimatedWidget): """Widget that stores text on multiple lines. """ def __init__(self, x, y, font, font_size, color, align=0, width_limit=9001, max_alpha=255): super().__init__() pg.font.init() self.font_name = font self.font = pg.font.Font(font, font_size) self.x = x self.y = y self.h = 0 self.w = 0 self.color = color self.align = align self.width_limit = width_limit self.lines = [] # list of text surfaces with their coords self.text = None self.max_alpha = max_alpha def set_font_size(self, font_size): pg.font.init() self.font = pg.font.Font(self.font_name, font_size) def replace_with(self, text_widget): self.lines = text_widget.lines def clear(self): self.lines = [] def set_text(self, text=''): """Receives a string as input and makes a list of text surfaces with their coords. """ self.text = text self.lines = [] letter_height = self.font.size('A')[1] current_string = '' for i, word in enumerate(text.split() + ['@$']): new_word = (' ' if i else '') + word line_width = self.font.size(current_string + new_word)[0] if word == '@$' or (line_width > self.width_limit and current_string != ''): # make new surface with line of text and append it with its coords to the list of surfaces line = self.font.render(current_string.replace('~', ' '), True, self.color) if self.align == 0: x = 0 elif self.align == 1: x = -line.get_width() / 2 else: x = -line.get_width() y = len(self.lines) * letter_height self.lines.append([line, x, y]) current_string = word else: current_string += new_word self.h = letter_height * len(self.lines) self.w = max(line.get_width() for line, _, _ in self.lines) def set_max_alpha(self, max_alpha): self.max_alpha = max_alpha def set_alpha(self, alpha): """Sets alpha-value for all text surfaces. """ for surface, _, _ in self.lines: surface.set_alpha(alpha) def move(self, dx, dy): self.x += dx self.y += dy def move_to(self, x, y): self.x = x self.y = y def update(self, dt, animation_state=WAIT, time_elapsed=0.0): if animation_state == WAIT: self.set_alpha(self.max_alpha) if animation_state == OPEN: self.set_alpha(round(self.max_alpha * time_elapsed)) elif animation_state == CLOSE: self.set_alpha(round(self.max_alpha * (1 - time_elapsed))) def draw(self, screen, dx=0, dy=0, animation_state=WAIT): for surface, x, y in self.lines: screen.blit(surface, (round(self.x + x - dx), round(self.y + y - dy))) __all__ = ["TextWidget"]
import sys from math import floor, sqrt p = int(sys.stdin.read()) #A214526 #https://math.stackexchange.com/questions/163080/on-a-two-dimensional-grid-is-there-a-formula-i-can-use-to-spiral-coordinates-in def coords(n): # n steps m = floor(sqrt(n)) k = (m-1)/2 if m%2 !=0 else m/2 if n >= m*(m+1) else m/2-1 if 2*k*(2*k+1) < n and n <= (2*k+1)**2: return (n-4*k**2-3*k, k) if (2*k+1)**2 < n and n <= 2*(k+1)*(2*k+1): return (k+1, 4*k**2+5*k+1-n) if 2*(k+1)*(2*k+1) < n and n <= 4*(k+1)**2: return (4*k**2+7*k+3-n, -k-1) if 4*(k+1)**2 < n and n <= 2*(k+1)*(2*k+3): return (-k-1, n-4*k**2-9*k-5) raise Exception() def dist(a,b): return abs(a[0]-b[0]) + abs(a[1]-b[1]) print dist((0,0),coords(p-1))
import sys def triangleinequality(t): s1, s2, s3 = t t1, t2, t3 = (False, False, False) if (s1 + s2 > s3): t1 = True if (s2 + s3 > s1): t2 = True if (s1 + s3 > s2): t3 = True return t1 and t2 and t3 count = 0 while(True): t = zip(*[map(int,sys.stdin.readline().split()),map(int,sys.stdin.readline().split()),map(int,sys.stdin.readline().split())]) if len(t) == 0: break for i in t: if triangleinequality(i): count += 1 print count
def add(x=0,y=0): #Default parameter is someting that if a user does not insert the second value #it will not show the error return print(x+y) a = int(input("Enter a value for addition : ")) b = int(input("Enter second value for addition :")) add(a)
x = ["Farhan","Shaikh","Faheem"] for i in x: if(i == "Shaikh"): continue print(i)
def average(marks = int(input("Enter the marks of the Student : "))): if (marks >= 90): print("You have been passed with A grade") elif (marks >= 65 and marks <= 89): print("You have been passed With B grade") elif (marks >= 45 and marks <= 64): print("You have been passed with C grade") elif (marks >= 35 and marks <= 44): print("You have been Passed with D grade") else: print("Sorry you failed") average() print("hie")
height=input("Enter your height in foot : ") inch=input("Enter your height in inchs : ") weight=input("Enter your weight in kg's : ") meter_of_foot = float(height)/3.281 meter_of_inch = float(inch)/39.37 meter = meter_of_foot + meter_of_inch result = float(weight)/(float(meter)*float(meter)) print("From given input's your BMI should Be : ", result) if(result <= 18.5): print("You are Under Weight. ") if(result > 18.5 and result <= 25 ): print("You are Normal Weight. ") if (result > 25 and result <= 30): print("You are Over Weight. ") if (result > 30 and result <= 35): print("You are Obese. ") if (result > 35): print("You are Clinically Obese.")
import numpy as np x = np.arange(0,20) print(x) #Will print 0 to 19 print(x[8]) #Will print the value which is on the 8 position (8) print(x[1]) #Will print the value which is on the 1 position (1) print(x[:10]) #Will print the numbers which are before 10 print(x[10:]) #Will print the numbers which are after 9 print(x[2:5]) #Will print the numbers from 2 to 4 (5 will not be printed) print(x[-20:-1])#Will print the number from 0 to 18 y = x.copy()#All the Element of x will be copied into y y[-20:-1] = 80 #All the Element will be changed to 80 print(y)
Balance = 999 Pin = 1234 def Check(): Check = int(input("Welcome to CodingBook ATM Please Enter your pin : ")) #Checks for the pin if Check == Pin: options() else: print(" Invalid Pin Please try again ") #Dosent ask for another try. exit() def options(): print(" Choose an option ") #Ask's for options to the user print("--------------------------------------------------------------------------") option = int(input("1 : Check Balance\n2 : Deposite Funds\n3 : Withdrawl Funds\n4 : Change Pin\n")) print("--------------------------------------------------------------------------") if option == 1: Check_Balance() if option == 2: Deposite_funds() if option == 3: Withdrawl_Funds() if option == 4: Change_pin() def Check_Balance(): print("--------------------------------------------------------------------------") global Balance #Global variable print("Your Total Balance is : $",Balance) #prints balance print("--------------------------------------------------------------------------") decide = input("If want to go back to Mainmenu Press : Y \nIf you want to Exit Press :N\n") #Ask after every transaction whther to quit or not print("--------------------------------------------------------------------------") if (decide == 'y' or decide == 'Y'): options() elif (decide == 'n' or decide == 'N'): exit(" Thanks Please visit us again ") print("--------------------------------------------------------------------------") def Withdrawl_Funds(): print("--------------------------------------------------------------------------") withdrawl = int(input("How much Amout you want to Withdrawl : ")) #Ask's user amount to be withdrawl print("--------------------------------------------------------------------------") global Balance #Global variable if withdrawl > Balance: #If the Withdrawl amount is greater than current Balance print("You Dont have Sufficient Funds to Withdrawl \nYour Balance is :",Balance) print("--------------------------------------------------------------------------") elif withdrawl <= 0: #If user Enters zero or a minus value print("You Either Entered Zero or a Minus value\nPlease retry") print("--------------------------------------------------------------------------") elif withdrawl > 0: Balance = Balance - withdrawl #Actual withdrawl process print(withdrawl,"Amount Deducted","Your new Balance is:",Balance) print("--------------------------------------------------------------------------") #print("--------------------------------------------------------------------------") decide = input("If want to go back to Mainmenu Press : Y \nIf you want to Exit Press : N\n") #Ask after every transaction whther to quit or not print("--------------------------------------------------------------------------") if (decide == 'y' or decide == 'Y'): options() elif (decide == 'n' or decide == 'N'): exit("Thanks Please visit us again") print("--------------------------------------------------------------------------") def Deposite_funds(): global Balance Deposite = int(input("Enter the amount You want to deposite :")) print("--------------------------------------------------------------------------") if Deposite < 0: #check if amount is less than zero print("You Either Entered a Zero value or a Minus value.\n Exited") exit() elif Deposite > 0: #Allows only if amount is greater than zero Balance = Balance + Deposite print("You Sucessfully Deposited :",Deposite,":Amount in your account your current Balance is:",Balance) decide = input("If want to go back to Mainmenu Press : Y \nIf you want to Exit Press : N\n") #Ask after every transaction whther to quit or not print("--------------------------------------------------------------------------") if (decide == 'y' or decide == 'Y'): options() elif (decide == 'n' or decide == 'N'): exit("Thanks Please visit us again") print("--------------------------------------------------------------------------") def Change_pin(): global Pin Check_Pin = int(input("Enter your Current Pin : ")) if Check_Pin == Pin: #Checks for current Pin New_Pin = int(input("Enter Your New Pin : ")) #Ask's to enter New Pin Pin = New_Pin #Assings new Pin to current Pin print("Password Changed Succesfully:") else: print("Sorry your request cannot be performed:") #if user enter's wrong pin decide = input("If want to go back to Mainmenu Press : Y \nIf you want to Exit Press : N\n") #Ask after every transaction whther to quit or not print("--------------------------------------------------------------------------") if (decide == 'y' or decide == 'Y'): options() elif (decide == 'n' or decide == 'N'): exit("Thanks Please visit us again") print("--------------------------------------------------------------------------") Check()
# Given a string, find the length of the longest substring without repeating characters. # Examples: # Given "abcabcbb", the answer is "abc", which the length is 3. # Given "bbbbb", the answer is "b", with the length of 1. # Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ ans = str(s[0]) lenAns = (len(ans)) for x in range(0,len(s)): substr = s[x] index = ord(s[x]) for y in range(x+1,len(s)): if self.compareArray(substr, s[y]) == True: print(str(x)+' , '+str(y)) substr = substr+s[y] print(substr) if len(substr)>lenAns: print('UPDATE') ans = substr lenAns = len(substr) else: break print('FINAL ANSWER: '+ans) def compareArray(self, s, c): for x in range(0,len(s)): if ord(s[x]) == ord(c): return False return True obj = Solution() s = 'pwwkew' obj.lengthOfLongestSubstring(s)
# Given an integer, write a function to determine if it is a power of three. # Example 1: # Input: 27 # Output: true # Example 2: # Input: 0 # Output: false # Example 3: # Input: 9 # Output: true # Example 4: # Input: 45 # Output: false # Follow up: # Could you do it without using any loop / recursion? def isPowerOfThree(num): count = 1 while True: if count == num: return True elif count > num: break else: count *= 3 return False print(isPowerOfThree(27)) print(isPowerOfThree(0)) print(isPowerOfThree(9)) print(isPowerOfThree(45))
from selenium import webdriver #driver is a variable name whch holds the session of the url driver = webdriver.Chrome(executable_path='D:\Python\chromedriver_win32\chromedriver.exe') #maximum default time to wait for elements to load: driver.implicitly_wait(10) driver.get("https://translate.google.com/") #current url will show the current url print("current URL: ", driver.current_url) #title returns the tab title as shown in chrome print("title: ",driver.title) if driver.title=="Google Translate": print("tab is correct") else: print("incorrect tab") #get the page source print("---SOURCE---\n",driver.page_source) print("---END SOURCE---") #LOCATORS: finding elements in the html page #Locator type ID: unique name of the element my_list=driver.find_elements_by_id("source") print("ID element list:\n",my_list[0]) #XPath - this is a custom locator, we will use it when we have no data on the element, we only a specified element with which we can't locate. #xpath=//tagname[@attribute='value'], example: my_element=driver.find_element_by_xpath("/html/body[@class='displaying-homepage']/div[@class='frame']/div[@class='page tlid-homepage homepage translate-text']/div[@class='homepage-content-wrap']/div[@class='tlid-source-target main-header']/div[@class='source-target-row']/div[@class='tlid-input input']/div[@class='source-wrap']/div[@class='input-full-height-wrapper tlid-input-full-height-wrapper']/div[@class='source-input']/div[@id='input-wrap']/textarea[@id='source']") print("xpath element:\n",my_element) #CONTROLLERS button_element=driver.find_element_by_id("source") button_element.send_keys("hello") import time time.sleep(5) button_element.clear() print("button displayed: ",button_element.is_displayed()) my_element_language=driver.find_element_by_xpath("/html/body[@class='displaying-homepage with-lang-list']/div[@class='frame']/div[@class='page tlid-homepage homepage translate-text']/div[@class='homepage-content-wrap']/div[@class='tlid-source-target main-header']/div[@class='source-target-row']/div[@class='tlid-input input']/div[@class='tlid-language-bar ls-wrap']/div[@class='sl-wrap']/div[@class='sl-more tlid-open-source-language-list']") my_element_language.click() my_element_language=driver.find_element_by_xpath("/html/body[@class='displaying-homepage with-lang-list']/div[@class='frame']/div[@class='page tlid-language-picker-page language-picker-page']/div[@class='language-picker-wrapper']/div[@class='outer-wrap']/div[@class='language-list'][1]/div[@class='language_list_languages language_list_sl_list tw-ll-top'][1]/div[@class='language-list-unfiltered-langs-sl_list']/div[@class='language_list_section'][2]/div[@class='language_list_item_wrapper language_list_item_wrapper-hu']/div[@class='language_list_item language_list_item_language_name']") my_element_language.click() #driver quit closes all tabs related to the session #driver.quit()
# Question A # first = 7 # second = 44.3 # print (first + second) # print (first * second) # print (second / first) # # x = 1 # y = 2 # if x > y: # print ("BIG") # if x < y: # print("SMALL") # # # season = 1 # if season == 1: # print ("summer") # elif season == 2: # print ("winter") # elif season == 3: # print("fall") # elif season == 4: # print("spring") a = 8 b = "123" print (a + int(b))
#Problem statement: Supervised learning algorithm is applied by Simple Linear Regression model #where the dataframe is divided into traing and test data frame and plot a graph for it #libraries are imported import numpy as np import pandas as pd import matplotlib.pyplot as plt #data file is read dataset=pd.read_excel('data.xlsx') #data is splitted as independent and dependent variables X=dataset.iloc[:, :-1].values Y=dataset.iloc[:,1].values # dividing the complete dataset into training and test dataaset from sklearn.model_selection._split import train_test_split X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=1/3,random_state=0) #implement our classifier based on simple linear regression from sklearn.linear_model import LinearRegression simplelinearRegression=LinearRegression() simplelinearRegression.fit(X_train,Y_train) Y_predict=simplelinearRegression.predict(X_test) #Y_predict_ll=simplelinearRegression.predict([[14]]) #u=simplelinearRegression.coef_ #u=simplelinearRegression.intercept_ #implement the graph plt.xlabel('Years of experience') plt.ylabel('Salary(BDT)') plt.scatter(X_train,Y_train,color='red',marker='+') plt.plot(X_train,simplelinearRegression.predict(X_train)) plt.show()
<<<<<<< HEAD def makes10(a, b): ======= def makes10(a, b): >>>>>>> ec863b8dfbbeba8f5506e1f29976ea8308fddd9e return(a==10 or b==10 or a+b==10)
<<<<<<< HEAD def front_back(str): if len(str) <= 1: return str mid = str[1:len(str)-1] return str[len(str)-1] + mid + str[0] ======= def front_back(str): if len(str) <= 1: return str mid = str[1:len(str)-1] return str[len(str)-1] + mid + str[0] >>>>>>> ec863b8dfbbeba8f5506e1f29976ea8308fddd9e #замена первого и последнего символа местами
# GRADED FUNCTION: is_overlapping def is_overlapping(segment_time, previous_segments): """ Checks if the time of a segment overlaps with the times of existing segments. Arguments: segment_time -- a tuple of (segment_start, segment_end) for the new segment previous_segments -- a list of tuples of (segment_start, segment_end) for the existing segments Returns: True if the time segment overlaps with any of the existing segments, False otherwise """ segment_start, segment_end = segment_time ### START CODE HERE ### (≈ 4 lines) # Step 1: Initialize overlap as a "False" flag. (≈ 1 line) overlap = False # Step 2: loop over the previous_segments start and end times. # Compare start/end times and set the flag to True if there is an overlap (≈ 3 lines) for previous_start, previous_end in previous_segments: if segment_start <= previous_end and segment_end >= previous_start: overlap = True ### END CODE HERE ### return overlap
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('\nHello! Let\'s explore some US bikeshare data!') # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs city=input("Would you like to see data for Chicago, New York City, or Washington?\n") while city.lower() not in ["chicago", "new york city", "washington"]: city=input("\nOoops, invalid option. Would you like to see data for Chicago, New York City or Washington?\n") # get user input for filter options filtertype=input("Would you like to filter the data by month, day, or not at all? Choose only one option:\n") while filtertype.lower() not in ["month", "day", "not at all"]: filtertype=input("\nOoops, invalid option. Would you like to filter the data by month, day, or not at all? Choose only one option:\n") if filtertype=="month": # get user input for month (all, january, february, ... , june) month=input("Please enter a month (January, February, ... or June):\n") while month.lower() not in ["january", 'february', 'march', 'april', 'may', 'june']: month=input("\nOoops, invalid option. Please enter a month (January, February, ... or June):\n") day="all" elif filtertype=="day": # get user input for day of week (all, monday, tuesday, ... sunday) day=input("Please enter a day of week (Monday, Tuesday, ... or Sunday):\n") while day.lower() not in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']: day=input("\nOoops, invalid option. Please enter a day of week (Monday, Tuesday, ... or Sunday):\n") month="all" else: day="all" month="all" print('-'*40) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ # load data file into a dataframe df = pd.read_csv(CITY_DATA[city.lower()]) # convert the Start Time column to datetime df['Start Time'] = pd.to_datetime(df['Start Time']) # extract month, day of week and hour from Start Time to create new columns df['month'] = df['Start Time'].dt.month df['day_of_week'] = df['Start Time'].dt.day_name() df['hour'] = df['Start Time'].dt.hour # filter by month if applicable if month != 'all': # use the index of the months list to get the corresponding int months = ['january', 'february', 'march', 'april', 'may', 'june'] month = months.index(month.lower()) + 1 # filter by month to create the new dataframe df = df[df['month'] == month] # filter by day of week if applicable if day != 'all': # filter by day of week to create the new dataframe df = df[df['day_of_week'] == day.title()] return df def time_stats(df): """Displays statistics on the most frequent times of travel. Args: df - Pandas DataFrame containing city data filtered by month and day """ print('\nCalculating the most frequent times of travel...\n') start_time = time.time() # display the most common month popular_month = df['month'].mode()[0] months = ['january', 'february', 'march', 'april', 'may', 'june'] popular_month = months[popular_month-1].title() # display the most common day of week popular_day = df['day_of_week'].mode()[0] # display the most common start hour popular_hour = df['hour'].mode()[0] print("The most commom month of travel is {}." "\nThe most commom day of travel is {}." "\nThe most commom starting hour is {}h.".format(popular_month, popular_day, popular_hour)) print("\nThis took %s seconds." % round(time.time() - start_time,1)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating the most popular stations and trip...\n') start_time = time.time() # display most commonly used start station popular_start = df['Start Station'].mode()[0] # display most commonly used end station popular_end = df['End Station'].mode()[0] # display most frequent combination of start station and end station trip df['Trip Points'] = df['Start Station'] + " to " + df['End Station'] popular_trip = df['Trip Points'].mode()[0] print("The most commonly used start station was {}." "\nThe most commonly used end station was {}." "\nThe most commonly combination of start and end station was from {}.".format(popular_start, popular_end, popular_trip)) print("\nThis took %s seconds." % round(time.time() - start_time,1)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration. Args: df - Pandas DataFrame containing city data filtered by month and day """ print('\nCalculating trip duration...\n') start_time = time.time() # display total travel time total_travel= df['Trip Duration'].sum() # display mean travel time mean_travel= df['Trip Duration'].mean() print("The total travel time was {} seconds." "\nThe mean travel time was {} seconds.".format(round(total_travel), round(mean_travel))) print("\nThis took %s seconds." % round(time.time() - start_time,1)) print('-'*40) def user_stats(df, city): """Displays statistics on bikeshare users. Args: df - Pandas DataFrame containing city data filtered by month and day (str) city - name of the city to analyze """ print('\nCalculating user stats...\n') start_time = time.time() # Display counts of user types user_types = df['User Type'].value_counts() for i in user_types: print("The number of {}s users is {}.".format(user_types.index[i], user_types[i])) if city.lower() != "washington": # Display counts of gender gender = df['Gender'].value_counts() for i in gender: print("The number of {} users' is {}.".format(gender.index[i], gender[i])) # Display earliest, most recent, and most common year of birth earliest_yob=int(df['Birth Year'].min()) recent_yob=int(df['Birth Year'].max()) commom_yob=int(df['Birth Year'].mode()) print("\nThe earliest year of birth is {}." "\nThe most recent year of birth is {}." "\nThe most common year of birth is {}.".format(earliest_yob, recent_yob, commom_yob)) print("\nThis took %s seconds." % round(time.time() - start_time,1)) print('-'*40) def raw_data(df): """ Asks user if they want to see the raw dataset. Args: df - Pandas DataFrame containing city data filtered by month and day """ # get user input to check if they want to see the raw data rawdata=input("Would you like to see raw data? Enter yes or no.\n") while rawdata.lower() not in ["yes", "no"]: rawdata=input("\nOoops, invalid option. Would you like to see raw data? Enter yes or no.\n") if rawdata=="yes": seq=list(range(0, len(df.index)+1, 5)) for i in range(len(seq)-1): print(df[seq[i]:seq[i+1]]) morerows=input("Would you like to see 5 more rows? Enter yes or no.\n") while morerows.lower() not in ["yes", "no"]: morerows=input("\nOoops, invalid option. Would you like to see 5 more rows? Enter yes or no.\n") if morerows!="yes": break def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df, city) raw_data(df) restart = input('\nWould you like to restart? Enter yes or no.\n') while restart.lower() not in ["yes", "no"]: restart=input('\nOoops, invalid option. Would you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
import unittest from Programm.Sword import Sword class TestSwordMethods(unittest.TestCase): def test_name(self): s = Sword() self.assertEqual(s.name, "Меч") self.assertNotEqual(s.name, "Лук") self.assertEqual(s.damage, 10) def test_attack(self): s = Sword() self.assertEqual(s.damage, 10) s.attack() self.assertNotEqual(s.damage, 10) s.attack() self.assertEqual(s.damage, 8) def test_damage_setter(self): s = Sword()("Меч") self.assertEqual(s.damage, 10) s.damage = 20.0 self.assertEqual(s.damage, 20) def test_le_1(self): s1 = Sword("Меч 1", 20) s2 = Sword("Меч 2", 15) self.assertFalse(s1.__le__(s2)) for i in range(1, 50): s1.attack() self.assertTrue(s1.__le__(s2)) def test_le_2(self): s1 = Sword("Меч 1", 10) s2 = Sword("Меч 2", 20) self.assertTrue(s1.__le__(s2)) for i in range(1, 50): s2.attack() self.assertFalse(s1.__le__(s2)) if __name__ == '__main__': unittest.main()
import re pat = '^[456]\d{3}-?\d{4}-?\d{4}-?\d{4}$' c = r'(.)\1{3,}' t = int(input()) for _ in range(t): s = input() if re.search(pat, s) and not re.search(c,s.replace('-','')): print('Valid') else: print('Invalid')
#Function to convert sparse matrix into orignal matrix def orignal_mat(sparse_mat): row = sparse_mat[0][0] column = sparse_mat[0][1] #Initializing original matrix. orig_mat = [[0 for i in range(column)]for j in range(row)] #filling the orignal matrix with non zero terms from sparse matrix for i in range(1,len(sparse_mat)): orig_mat[sparse_mat[i][0]][sparse_mat[i][1]] = sparse_mat[i][2] #Displaying orignal matrix for i in orig_mat: print(i) #Main function sparse_mat =[[5 ,6, 6], [0, 4, 9], [1, 1, 8], [2, 0, 4], [2, 3, 2], [3, 5, 5], [4, 2, 2]] orignal_mat(sparse_mat)
""" Alogorithm to delete the middle node of the Linked_List 1). Declare 3 pointers slow_temp,temp,prev_temp. 2). Traverse the Linked List. 3). Move temp by two and slow_temp by one and while traversing track of previous of slow_temp storing it in prev_temp. 4). When temp reaches end of the Linked List, slow_temp reaches middle of the Linked List. 5). Delete the middle node. """ #Class Node to create a Node class Node: def __init__(self,data): self.data = data self.next = None #Class Linked_List to link different nodes all together class Linked_List: def __init__(self): self.head = None #Add the node to the linked list def insert(self,data): new_node = Node(data) if self.head == None: self.head = new_node else: new_node.next = self.head self.head = new_node #To delete middle node from the linked list def del_mid_node(self): temp = self.head slow_temp = self.head if temp == None: print("Linked list is empty") return elif temp.next == None: temp = None return else: while(temp != None and temp.next != None): prev_temp = slow_temp slow_temp = slow_temp.next temp = temp.next.next prev_temp.next = slow_temp.next #To display the element of the linked list def display(self): temp = self.head if temp == None: print("There is no node in linked list") return else: while(temp != None): print(temp.data,end=" ") temp = temp.next #Creating instance of the class Linked_List ll = Linked_List() ch = 0 while(ch != 4): print("""Enter 1 to insert a node at front in Linked_List Enter 2 to delete middle node in a linked list Enter 3 to print the linked List Enter 4 to to quit """) ch = int(input()) if ch == 1: print("Enter the data you want to insert in the linked list") a = int(input()) ll.insert(a) elif ch == 2: ll.del_mid_node() elif ch == 3: ll.display() elif ch == 4: print("We will quit") else: print("Wrong choice")
class Node: def __init__(self,value): self.left = None self.right = None self.value = value def insert(root,node): if root is None: root = node else: if root.value > node.value: if root.left is None: root.left = node else: insert(root.left,node) else: if root.value < node.value: if root.right is None: root.right = node else: insert(root.right , node) #function to do inorder tree traversal def inorder(root): if root: inorder(root.left) print(root.value) inorder(root.right) # Given a non-empty binary search tree, return the node # with minum value found in that tree. Note that the # entire tree does not need to be searched def minvalue(node): current = node if current.left != None: current = current.left return current # Given a binary search tree and a value, this function # delete the value and returns the new root def deletenode(root,value): if root == None: return root # If the value to be deleted is smaller than the root's # value then it lies in left subtree if root.value > value: root.left = deletenode(root.left,value) # If the value to be delete is greater than the root's value # then it lies in right subtree elif root.value < value: root.right = deletenode(root.right,value) # If value is same as root's value, then this is the node # to be deleted else: # Node with only one child or no child if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp # Node with two children: Get the inorder successor # (smallest in the right subtree) temp = minvalue(root.right) # Copy the inorder successor's content to this node root.value = temp.value # Delete the inorder successor root.right = deletenode(root.right,temp.value) return root # Driver program to test above functions """ Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 """ root = Node(50) #root = insert(root, Node(50)) insert(root, Node(30)) insert(root, Node(20)) insert(root, Node(40)) insert(root, Node(70)) insert(root, Node(60)) insert(root, Node(80)) print ("Inorder traversal of the given tree") inorder(root) print("\nDelete 20") root = deletenode(root, 20) print("Inorder traversal of the modified tree") inorder(root) print("\nDelete 30") root = deletenode(root, 30) print("Inorder traversal of the modified tree") inorder(root) print("\nDelete 50") root = deletenode(root, 50) print("Inorder traversal of the modified tree") inorder(root) """ Output:- Inorder traversal of the given tree 20 30 40 50 60 70 80 Delete 20 Inorder traversal of the modified tree 30 40 50 60 70 80 Delete 30 Inorder traversal of the modified tree 40 50 60 70 80 Delete 50 Inorder traversal of the modified tree 40 60 70 80 """
""" Algorithm:- To implement stack using one queue. 1. Create a class Queue. 2. Define methods enqueue, dequeue, is_empty and get_size inside the class Queue. 3. Create a class Stack with instance variable q initialized to an empty queue. 4. Pushing is done by enqueuing data to the queue. 5. To pop, the queue is dequeued and enqueued with the dequeued element n – 1 times where n is the size of the queue. This causes the the last element added to the queue to reach the rear of the queue. The queue is dequeued one more time to get the item to be returned. 6. The method is_empty returns True iff the queue is empty. """ class Queue: def __init__(self): self.queue = [] self.size = 0 def is_empty(self): return(self.queue == []) def enqueue(self,a): self.size += 1 self.queue.append(a) def dequeue(self): self.size -= 1 return(self.queue.pop(0)) def get_size(self): return self.size class Stack: def __init__(self): self.q = Queue() def is_empty(self): return self.q.is_empty() def push(self,a): self.q.enqueue(a) def pop(self): for j in range(self.q.get_size()-1): a = self.q.dequeue() self.q.enqueue(a) p = self.q.dequeue() print("The element which is being deleted is {}".format(p)) def display(self): for i in range(self.q.get_size()): print(self.q.queue[i],end = " ") s = Stack() ch = 0 while(ch != 4): print("""Enter 1 to push element in Stack Enter 2 to pop element from the Stack Enter 3 to display element of the stack Enter 4 to quit """) ch = int(input()) if ch == 1: m = int(input("Enter the element you want to enter in the stack")) s.push(m) elif ch == 2: s.pop() elif ch == 3: s.display() elif ch == 4: print("Hence we will quit") else: print("wrong choice")
class Node: def __init__(self,data): self.value = data self.left = None self.right = None class Tree: def __init__(self): self.head = None def insert(root ,node): if root is None: root = node else: if root.value > node.value: if root.left is None: root.left = node else: insert(root.left,node) else: if root.value < node.value: if root.right is None: root.right = node else: insert(root.right , node) def preorder(root): s = [] ans = [] s.append(root) while s!= []: val = s.pop() ans.append(val.value) if val.right!= None: s.append(val.right) if val.left != None: s.append(val.left) return ans r = Node(50) insert(r,Node(30)) insert(r,Node(20)) insert(r,Node(40)) insert(r,Node(70)) insert(r,Node(60)) insert(r,Node(80)) print(preorder(r)) """ Output [50,30,20,40,70,60,80] """
"""Algorithm 1. Scan the infix expression from left to right. 2. If the scanned character is an operand, output it. 3. Else, …..3.1 If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty or the stack contains a ‘(‘ ), push it. …..3.2 Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.) 4. If the scanned character is an ‘(‘, push it to the stack. 5. If the scanned character is an ‘)’, pop the stack and and output it until a ‘(‘ is encountered, and discard both the parenthesis. 6. Repeat steps 2-6 until infix expression is scanned. 7. Print the output 8. Pop and output from the stack until it is not empty.""" #OPERATORS is a set which contain all the operators OPERATORS = set(['+', '-', '*', '/', '(', ')']) #PRIORITY it contain the priority of the operators PRIORITY = {'+':1, '-':1, '*':2, '/':2} #Function defined for the infix to postfix conversion def infix_to_postfix(li): #String that will contain the postfix format off the expression output = "" stack = [] for i in li: if i not in OPERATORS: output += i elif i == "(": stack.append("(") elif i == ")": while(stack and stack[-1]!= "("): a = stack[-1] output += a stack.pop() else: while(stack and stack[-1] != "(" and PRIORITY[i] <= PRIORITY[stack[-1]]): output += stack.pop() stack.append(i) #For the remaing elements in stack while stack: output += stack.pop() print(output) #Driver code infix_to_postfix('1+(3+4*6+6*1)*2/3')
class Node: def __init__(self,value): self.left = None self.right = None self.value = value def insert(root, value): if root == None: return Node(value) elif value < root.value: root.left = insert(root.left , value) elif value > root.value: root.right = insert(root.right , value ) return root def inorder(root): if root: inorder(root.left) print(root.value ) inorder(root.right) def postorder(root): if root : postorder(root.left) postorder(root.right) print(root.value) def preorder(root): if root: print(root.value) preorder(root.left) preorder(root.right) root =None root = insert(root ,1) root = insert(root,2) root = insert(root,3) root =insert(root,4) root = insert(root,5) print ("Preorder traversal of binary tree is") preorder(root) print( "\nInorder traversal of binary tree is") inorder(root) print ("\nPostorder traversal of binary tree is") postorder(root)
""" Algorithm to implement Queue using Stack:- 1.Take 2 Stacks, stack1 and stack2. 2.stack1 will be used a back of the Queue and stack2 will be used as front of the Queue. 3.Push() operation will be done on stack1, and pop() operations will be done on stack2. 4.When pop() are called, check is stack2 is empty, if yes then move all the elements from stack1 and push them into stack2. """ #Class stack which consist of all the basic function of the stack class Stack: #To initialize a list named as stack def __init__(self): self.stack = [] #Ton append the element to list def push(self,a): self.stack.append(a) #To remove the topmost element from stack def pop(self): return(self.stack.pop()) #To get the size ot the list def get_size(self): return len(self.stack) #Class queue which is used to implement queue using stack class Queue: #To initialize two class Stack instance def __init__(self): self.s1 = Stack() self.s2 = Stack() #To get the size def get_size(self): return(self.get_size()) #To push the element ins stack s1 def enqueue(self,a): self.s1.push(a) def dequeue(self): if self.s1.stack == 0: print(" Stack is empty") else: for i in range(self.s1.get_size()): a = self.s1.stack.pop() self.s2.stack.append(a) res = self.s2.stack.pop() self.s1,self.s2 = self.s2,self.s1 self.s1.stack = self.s1.stack[::-1] print("The deleted element is {}".format(a)) #To display the element of stack. def display(self): print(self.s1.stack) #Main function q = Queue() ch = 0 while(ch != 4): print("""Enter 1 to push element in Stack Enter 2 to pop element from the Stack Enter 3 to display element of the stack Enter 4 to quit """) ch = int(input()) if ch == 1: m = int(input("Enter the element you want to enter in the stack")) q.enqueue(m) elif ch == 2: q.dequeue() elif ch == 3: q.display() elif ch == 4: print("Hence we will quit") else: print("wrong choice")
#Creating the function for merge_sort def merge_sort(a): # we will split the the list to left and right if there is more than one element in it. if(len(a)>1): mid = len(a)//2 #left half contain element from starting till one less than the middle element left = a[:mid] #Right half contain element from middle till the end. right = a[mid:] #recursive calling the merge_sort Function merge_sort(left) merge_sort(right) #Counter i for left list indexing #Counter j for right list indexing #counter k for the main list indexing that need to be sorted i,j,k = 0 ,0, 0 while(i<len(left) and j<len(right)): #Left element is smaller than the right element we will add it to the main list if(left[i] < right[i]): a[k] = left[i] k += 1 i += 1 else: #else if right element isn smaller or equal to the left element we will add it to the main list a[k] = right[j] k += 1 j += 1 while i<len(left): #Adding all the remaing element from right list to the main nlist a[k] = left[i] k += 1 i += 1 while j<len(right): #Adding all the remaing element from right list to the main list a[k] = right[j] k += 1 j +=1 nlist = [14,46,43,27,57,41,45,21,70] #calling the merge_sort function and passssing the list to it. merge_sort(nlist) #printing the sorted list. print(nlist)
""" Z function of string s ia and array z, where z[i] value is amount of numbers from ith position in string s which are the same with first z[i] characters of string s """ def z_function_naive(s): z = [0 for _ in range(len(s))] for i in range(1, len(s)): j = 0 k = i while k < len(s) and s[j] == s[k]: j += 1 k += 1 z[i] = j return z def z_function(s): l, r = 0, 0 z = [0 for _ in range(len(s))] for i in range(1, len(s)): if i <= r: z[i] = min(r - i + 1, z[i - l]) while i + z[i] < len(s) and s[z[i]] == s[z[i] + i]: z[i] += 1 if i + z[i] - 1 > r: l = i r = i + z[i] - 1 return z if __name__ == "__main__": s = "abacaba" print(z_function_naive(s)) print(z_function(s))
""" Given an array of numbers, segregate odd and even numbers Example: 3, 4, 1, 9, 5, 2 4, 2, 1, 3, 9, 5 """ def segregate(arr): tail = 0 for i in range(len(arr)): if arr[i] % 2 == 0: arr[tail], arr[i] = arr[i], arr[tail] tail += 1 arr[tail], arr[i] = arr[len(arr) - 1], arr[tail] return arr if __name__ == "__main__": arr = [3, 4, 1, 9, 5, 2] print(segregate(arr))
""" Given an 2d array with numbers - prices, you can move from (0, 0) to (n, m) only right or down, find path of maximum cost. """ def prepare_array(arr): for i in range(1, len(arr[0])): arr[0][i] += arr[0][i - 1] for j in range(1, len(arr)): arr[j][0] += arr[j - 1][0] def find_path(arr): prepare_array(arr) path = [] n = len(arr) m = len(arr[0]) x, y = n - 1, m - 1 for i in range(1, len(arr)): for j in range(1, len(arr[i])): if arr[i - 1][j] > arr[i][j - 1]: arr[i][j] += arr[i - 1][j] else: arr[i][j] += arr[i][j - 1] while x > 0 and y > 0: if arr[x - 1][y] > arr[x][y - 1]: path.append((x - 1, y)) x -= 1 else: path.append((x, y - 1)) y -= 1 while x > 0: path.append((x - 1, 0)) x -= 1 while y > 0: path.append((0, y - 1)) y -= 1 return arr[n - 1][m - 1], path[::-1] if __name__ == "__main__": arr = [ [2, 3, 1, 4, 6], [7, 10, 3, 6, 8], [4, 4, 5, 2, 1], [7, 6, 4, 3, 9] ] print(find_path(arr))
""" Check whether linked list has loop """ from python.linked_list import Node def has_loop(head): fast, slow = head.next, head while fast is not None and \ fast.next is not None \ and fast != slow: fast = fast.next.next slow = slow.next return slow == fast if __name__ == "__main__": node5 = Node(5) node4 = Node(4, node5) node3 = Node(3, node4) node2 = Node(2, node3) node1 = Node(1, node2) # node5.next = node3 print(has_loop(node1))
""" Implement Aho-Corasik algorithm """ class Node(object): def __init__(self, char, is_root=False): self.char = char self.suffix_link = None self.children = {} self.is_root = is_root def build_trie(text): root = Node(char='', is_root=True) parent = root for c in text: if c not in parent.children: node = Node(char=c) parent.children[c] = node if parent.is_root: node.suffix_link = parent p = parent cur = node while not p.is_root: if c not in p.suffix_link.children: new_node = Node(c) p.suffix_link.children[c] = new_node cur.suffix_link = p.suffix_link.children[c] cur = cur.suffix_link p = p.suffix_link cur.suffix_link = root parent = node return root def find_word(word, trie): cur_node = trie for c in word: if c not in cur_node.children: return False cur_node = cur_node.children[c] return True if __name__ == "__main__": text = "abcdedacbae" word1 = "dbc" word2 = "acb" word3 = "edc" word4 = "dacb" trie = build_trie(text) print(find_word(word1, trie)) print(find_word(word2, trie)) print(find_word(word3, trie)) print(find_word(word4, trie))
""" Check whether sting is rotation of another """ def is_rotation(s1, s2): s1s1 = s1 + s1 return s1s1.find(s2) != -1 if __name__ == "__main__": s1 = "waterbootle" s2 = "ootlewaterb" print(is_rotation(s1, s2))
""" Given a stack, sort it values using an additional stack only. Operations like push, pop, peel and is_empty permitted. """ class Stack(object): def __init__(self): self.stack = [] def push(self, value): self.stack.append(value) def pop(self): return self.stack.pop() def peek(self): if self.stack: return self.stack[-1] return None def is_empty(self): return len(self.stack) == 0 def sort(arr): stack1 = Stack() stack2 = Stack() for x in arr: stack1.push(x) while not stack1.is_empty(): while stack2.is_empty() or stack1.peek() >= stack2.peek(): stack2.push(stack1.pop()) if stack1.is_empty(): return stack2.stack # If stack is already sorted if stack1.is_empty(): while stack2.is_empty(): stack1.push(stack2.pop()) return stack1.stack tmp = stack1.pop() while not stack2.is_empty() and stack2.peek() >= tmp: stack1.push(stack2.pop()) stack1.push(tmp) while not stack2.is_empty(): stack1.push(stack2.pop()) if __name__ == "__main__": arr = [4, 3, 1, 2, 5] print(sort(arr))
""" Given a set of strings, print all anagrams together """ def collect_anagrams(words): d = {} for w in words: index = ''.join(sorted(w)) if index in d: d[index].append(w) else: d[index] = [w] return d if __name__ == "__main__": words = {"cat", "dog", "tac", "pot", "top", "god"} print(collect_anagrams(words))
""" Given an array with elements from 1 to n, but one is missing. Find missing element. """ def find_missing_arithm(arr, n): total_sum = n * (n + 1)/2 return total_sum - sum(arr) def find_missing_xor(arr, n): total = 0 actual = 0 for i in range(1, n + 1): total ^= i for v in arr: actual ^= v return total ^ actual if __name__ == "__main__": arr = [1, 2, 4, 6, 3, 7, 8] print(find_missing_arithm(arr, 8)) print(find_missing_xor(arr, 8))
""" There are n-pairs and therefore 2n people. everyone has one unique number ranging from 1 to 2n. All these 2n persons are arranged in random fashion in an Array of size 2n. We are also given who is partner of whom. Find the minimum number of swaps required to arrange these pairs such that all pairs become adjacent to each other. Input: n = 3 pairs[] = {1->3, 2->6, 4->5} // 1 is partner of 3 and so on arr[] = {3, 5, 6, 4, 1, 2} Output: 2 We can get {3, 1, 5, 4, 6, 2} by swapping 5 & 6, and 6 & 1 """ def arrange(arr, pairs): if len(arr) < 2: return 0 elif pairs[arr[0]] == arr[1]: # If first two elements are already paired return arrange(arr[2:], pairs) else: index = 0 # Find position of paired element in the array while index < len(arr) and arr[index] != pairs[arr[0]]: index += 1 arr1 = arr[:] arr2 = arr[:] # Swap first element with second arr1[1], arr1[index] = arr1[index], arr1[1] result1 = arrange(arr1[2:], pairs) # Swap in another way and compare results arr2[0], arr2[index - 1] = arr2[index - 1], arr2[0] result2 = arrange(arr2[2:], pairs) return min(result1, result2) + 1 if __name__ == "__main__": arr = [3, 5, 6, 4, 1, 2] pairs = {1: 3, 2: 6, 4: 5, 3: 1, 6: 2, 5: 4} print(arrange(arr, pairs))
""" The text is given. Each word of this text is scrambled(letters are permuted) Whitespaces are removed. The problem is to restore original text from scrambled if dictionary of words is given. Input: dict: {"world", "hello", "apple", "pear"} text: "ehlololwrd" Output: hello world """ def build_index(d): index = dict() for word in d: letters = set(word) for l in letters: if l in index: index[l].add(word) else: index[l] = set() index[l].add(word) return index def restore(text, dict): index = build_index(d) tmp = {} result = [] for c in text: if len(tmp) == 1: word = tmp.pop() result.append(word) tmp = set() elif len(tmp) == 0: tmp = index[c] else: tmp = tmp & index[c] return " ".join(result) if __name__ == "__main__": text = "ehlololwrd" d = {"world", "hello", "apple", "pear"} print restore(text=text, dict=d)
""" Convert sorted ddl to binary search tree """ class Node(object): def __init__(self, value): self.value = value self.next = None self.prev = None def find_mid(left, right): slow = left fast = left while fast != right: fast = fast.next if fast == right: slow = slow.next break fast = fast.next slow = slow.next return slow def convert(head, tail): if head == tail: head.next = None head.prev = None tail.next = None tail.prev = None return head mid = find_mid(head, tail) root = mid if head != mid: left_root = convert(head, mid.prev) else: left_root = None if mid != tail: right_root = convert(mid.next, tail) else: right_root = None root.prev = left_root root.next = right_root return root def inorder_traversal(root): if not root: return inorder_traversal(root.prev) print(root.value) inorder_traversal(root.next) if __name__ == "__main__": node1 = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(4) node5 = Node(5) node6 = Node(6) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 node5.next = node6 node6.prev = node5 node5.prev = node4 node4.prev = node3 node3.prev = node2 node2.prev = node1 root = convert(node1, node5) inorder_traversal(root)
""" Print reverse of string recursive """ def print_reverse(s): if s: print_reverse(s[1:]) print(s[0]) if __name__ == "__main__": print_reverse("hello")
nom = input("quel est votre nom?") age = 0 while age == 0: age_str = input("quel age avez vous?") try: age = int(age_str) except: print("Entrez numero uniquement pour l'age") # print("fin de la boucle") print("mon nom est " + nom + "," + "j'ai " + str(age) + " ans.") print("l'age prochain est "+str(age+1)+" ans.") # boucle while-->tant que # n = 0 # while n < 5: # n = n+1 # print(n) # mot_de_pass = "" # while not mot_de_pass == "toto": # mot_de_pass = input("entre votre mot de pass correctement:") # while mot_de_pass == "toto": # print("bon code") # break
def func(): for i in range(a, b+1): if i % c == 0: X.append(i) if __name__ == '__main__': X = [] a = int(input('Введите первое число -> ')) b = int(input('Введите второе число -> ')) c = int(input('Введите третье число -> ')) func() val = ','.join(map(str, X)) print(f"{len(X)} потому что {val} делятся на {c}.")
import re def func(text): if text.isalpha(): result = ''.join([i for i in text if not i.isdigit()]) print('Букв -> ', len(''.join(c for c in result if c not in '?:!/; '))) elif text.isdigit(): x = re.findall('(\d+)', text) print('Цифр -> ', len(x[0])) elif text.isalnum(): result = ''.join([i for i in text if not i.isdigit()]) print('Букв -> ', len(''.join(c for c in result if c not in '?:!/; '))) x = re.findall('(\d+)', text) print('Цифр -> ', len(x[0])) if __name__ == '__main__': func(input('Введите предложение -> '))
''' Use a Player class that provides attributes that store the first name, last name, position, at bats, and hits for a player. The class constructor should use these five attributes as parameters. This class should also provide a method that returns the full name of a player and a method that returns the batting average for a player. ''' class player: def __init__(self,firstname,lastname,position,at_bats,hits): self.firstName = firstname self.lastName = lastname self.position = position self.at_bats = at_bats self.hits = hits return self def getFirstName(self): return self.firstName def getLastName(self): return self.lastName def getPosition(self): return self.position def getAt_bats(self): return self.at_bats def getHits(self): return self.hits def setFirstName(self,firstname): self.firstName = firstname def setLastName(self,lastname): self.lastName = lastname def setPosition(self,position): self.position = position def setAt_bats(self,at_bats): self.at_bats = at_bats def setHits(self,hits): self.hits = hits def getFullName(self): return self.firstName+" "+self.lastName def getBattingAvg(self): ab = float(self.at_bats) hits = float(self.hits) if ab > 0: average = hits / ab return average class lineUp: def __init__(self,playerList): self.lineupList = playerList self.max = len(playerList) return self def displayLineup(self): # Print header print(' Player POS AB H AVG') print('-' * 60) count = 1 for player in self.lineupList: name = player.getFullName() position = player.getPosition() AB = player.getAt_bats() H = player.getHits() ab = float(AB) hits = float(H) average = 0 if ab > 0: average = hits / ab print("{0:3}{1:31}{2:>6}{3:>6}{4:>6}{5:>8}".format(str(count), name, position, AB, H, str(round(average, 3)))) count = count + 1 def addPlayer(self, player): self.lineupList.append(player) print('Player [',player.getFullName, '] has been added successfully!!') def removePlayer(self,LineUpNumber): if LineUpNumber > len(self.lineUpList)-1: print('\n\tInvalid LineUp Number') return None else: self.lineupList.pop(LineUpNumber-1) print('\n\tPlayer at LineUp Number ', LineUpNumber,' has been removed from the LineUpList') def movePlayer(self,oldLineUpNumber, newLineUpNumber): # Player to be moved player_to_move = self.LineUpList[int(oldLineUpNumber)-1] print('\n\t Player to be moved: \t', player_to_move.getFullName()) correct = False while correct == False: try: if int(newLineUpNumber) >= 1 and int(newLineUpNumber) <= len(self.LineUpList): correct = True else: print('Invalid LineUp number. Enter a valid LineUp number i.e. > = 1 and <=', n) except: print('Invalid LineUp number. Enter a valid LineUp number i.e. >= 1 and <=', n) # Now insert in new position and all players after elem are shifted to the right. self.LineupList.insert(newLineUpNumber - 1, player_to_move) print(player_to_move.getFullName(), ' has been moved to ',newLineUpNumber) def getPlayer(self,LineUpNumber): if LineUpNumber>len(self.LineUpList): print('\n\t Invalid LineUp number.') return None else: return self.LineUpList[LineUpNumber-1] def setPlayer(self,LineUpNumber,player): if LineUpNumber>len(self.LineUpList): print('\n\t Invalid LineUp number.') return None else: self.LineUpList.insert(LineUpNumber,player) def __iter__(self): self.n = 0 return self def __next__(self): if self.n <= self.max: self.n = self.n + 1 return self.LineUpList[self.n] else: raise StopIteration
# Listのスライス nums = range(5) # rangeは整数範囲を作成する組み込み型関数です print(nums) nums = range(5, 10) # 5, 6, 7, 8, 9 print(nums) nums = range(0, 10, 3) # 0, 3, 6, 9 print(nums) nums = range(-10, -100, -30) # -10, -40, -70 print(nums) nums = range(1, 5, 1) print(nums) nums = range(5) print(nums) # 整数配列 nums = [0, 1, 2, 3, 4] print(nums) # => "[0, 1, 2, 3, 4]" print(nums[2:4]) # インデックス2以上4未満;=> "[2, 3]" print(nums[2:]) # インデックス2以上最後まで;=> "[2, 3, 4]" print(nums[:2]) # 最初から2未満;=> "[0, 1]" print(nums[:]) # 全要素;=> ["0, 1, 2, 3, 4]" print(nums[:-1]) # 負のインデックスも可能;=> ["0, 1, 2, 3]" moji = "ABCDEF" print(moji[::2]) # 2 刻みで全て抽出 # indexを使おう a = ["a", "b", "c", "d"] print(a.index("b")) # 1 print(a.index("d")) # 3 # リストに値が存在するかどうか a = ["a", "b", "c", "d"] print("b" in a) # True print("f" in a) # False # 個数をカウント使用 a = ["a", "b", "c", "c", "b"] print(a.count("c")) # 2 print(a.count("g")) # 0 # ソートする a = [5, 2, 4, 3, 0, 1] s = sorted(a) print(s) # [0, 1, 2, 3, 4, 5] a = ["b", "g", "a", "d"] s = sorted(a) print(s) # ['a', 'b', 'd', 'g'] # 降順ソート a = [5, 2, 4, 3, 0, 1] a.sort(reverse=True) print(a) # [5, 4, 3, 2, 1, 0] # タプルをリストへ変換 a = ("takasi", "jun", "tomoki") print(list(a)) # ['takasi', 'jun', 'tomoki'] print(list((1, 2, 3, 4, 5))) # [1, 2, 3, 4, 5] # タプルアンパック d = ("python", "Java", "c") a, b, c = d print(a) # python print(b) # Java print(c) # c
def bubble_sort (array , order = True) : # length = len (array) if order == True : for i in range (len(array)) : for j in range (0,len(array)-i-1) : if array[j] > array [j+1] : (array[j],array[j+1]) = (array[j+1],array[j]) return array elif order == False : for i in range (len(array)) : for j in range (0,len(array)-i-1) : if array[j] < array [j+1] : (array[j],array[j+1]) = (array[j+1],array[j]) return array data = [2,5,4,-1,-9,5,0,-7] print (bubble_sort(data)) print (bubble_sort(data,order=False)) print("not changing your code dont worry")
from gamelibwillh2 import* import random #this code will give us a cover and lets us click space to start def start(): game = Game(800,800,"Pacman") cover=Image("PacMan_Files\\cover.png",game) cover.resizeTo(800,800) while not game.over: game.processInput() cover.draw() f1 = Font (blue,40,black,"Comic Sans Ms") game.drawText("Press Space bar to Play",300,740,f1) #When pressed the game starts and runs if keys.Pressed[K_SPACE]: game.over=True rundown() #if clicked you leave the game if keys.Pressed[K_ESCAPE]: game.over = True game.quit() quit() game.update(60) #start of lvl 1 and in this game it shows how pacman has to go around collecting #balls which are dots and get enough points to win. While doing that a ghost #will be following you and trying to make you lose. The ghost is another player. def rundown(): game = Game(1000,800,"Pac Man",50) bk = Image("PacMan_Files\\Background.png",game) pacman = Animation("PacMan_Files\\pacman.png",16,game,128/4,128/4) ghost= Animation("PacMan_Files\\ghost.png",4,game,80/4,20) song = Sound("PacMan_Files\\song.wav",1) #dots list dot=[] for index in range(100): dot.append(Animation("PacMan_Files\\dot.png",4,game,64/2,64/2)) dot[index].resizeBy(5) for index in range(100): dot[index].draw() x = randint(10,1000) y = randint(10,800) dot[index].moveTo(x,y) #apple list apple=[] for index in range(3): apple.append(Image("PacMan_Files\\apple.png",game)) apple[index].resizeBy(-80) for index in range(3): apple[index].draw() x = randint(10,1000) y = randint(10,800) apple[index].moveTo(x,y) game.setBackground(bk) bk.resizeTo(1000,800) pacman.resizeBy(80) pacman.moveTo(100,390) ghost.resizeBy(70) ghost.moveTo(500,390) while not game.over: game.processInput() bk.draw() ghost.draw() pacman.draw() song.play() #apple points for index in range(3): apple[index].draw() if apple[index].collidedWith(pacman): apple[index].visible=False game.score+=500 #dot/ghost points for index in range(100): dot[index].draw() if dot[index].collidedWith(pacman): dot[index].visible=False game.score+=100 if ghost.collidedWith(pacman): game.score-=500 ghost.moveTo(x,y) #pacman movement if keys.Pressed[K_ESCAPE]: game.over = True game.quit() quit() if keys.Pressed[K_DOWN]: pacman.y+=10 if keys.Pressed[K_UP]: pacman.y-=10 if keys.Pressed[K_LEFT]: pacman.x-=10 if keys.Pressed[K_RIGHT]: pacman.x+=10 #top pacman if pacman.y<=20: pacman.y+=50 game.score-=50 #bottom pacman if pacman.y>=780: pacman.y-=25 game.score-=50 #right pacman if pacman.x>980: pacman.moveTo(25,390) #left pacman if pacman.x<=0: pacman.moveTo(970,390) #ghost code now if keys.Pressed[K_s]: ghost.y+=11 if keys.Pressed[K_w]: ghost.y-=11 if keys.Pressed[K_a]: ghost.x-=11 if keys.Pressed[K_d]: ghost.x+=11 #top ghost if ghost.y<=20: ghost.y+=50 #bottom ghost if ghost.y>=780: ghost.y-=25 #right ghost if ghost.x>=980: ghost.moveTo(25,390) #left ghost if ghost.x<=0: ghost.moveTo(970,390) #pacman and ghost if ghost.collidedWith(pacman): game.score-=500 ghost.moveTo(500,390) #game over if game.time<=0 or game.score<=-1000: game.over=True ending() if game.score>=7000: game.over=True ending_2() game.displayScore(10,10) game.displayTime(110,10) game.update(20) game.quit() #when you lose the game because the time ran out or u got a certain negative #points.After you lose the game over screen pops up and u can either replay or #leave the game def ending(): game=Game(1000,800,"The End") gg = Image("PacMan_Files\\gg.jpg",game) gg.resizeTo(1000,800) while not game.over: game.processInput() gg.draw() #pressed and u leave the game if keys.Pressed[K_ESCAPE]: game.over = True game.quit() quit() f1 = Font (blue,80,black,"Comic Sans Ms") game.drawText("Press R to Replay lvl 1",100,30,f1) #pressed amd you can replay the game if keys.Pressed[K_r]: game.over=True rundown() game.update(30) game.quit() #if the pacman win the game because u got a certain points than a win screen #pops up and you can either replay the first level or go on to the next. def ending_2(): game=Game(1000,800,"The End") gg2 = Image("PacMan_Files\\gg2.png",game) win = Image("PacMan_Files\\win.png",game) gg2.resizeTo(1000,800) win.resizeBy(10) win.moveTo(500,700) while not game.over: game.processInput() gg2.draw() win.draw() #pressed and u leave the game if keys.Pressed[K_ESCAPE]: game.over = True game.quit() quit() f1 = Font (blue,50,black,"Comic Sans Ms") game.drawText("Press R to Replay lvl 1",255,30,f1) game.drawText("Press N to play lvl 2",280,-10,f1) #pressed r and u can play lvl 1 again if keys.Pressed[K_r]: game.over=True rundown() #pressed n and u can go to next lvl and play it if keys.Pressed[K_n]: game.over=True pt2() game.update(30) game.quit() #this is the second level of the game where it is the same code of rundown #but a few things are u need higher points and the ghostis bigger def pt2(): game = Game(1000,800,"Pac Man",40) bk = Image("PacMan_Files\\Background.png",game) pacman = Animation("PacMan_Files\\pacman.png",16,game,128/4,128/4) ghost= Animation("PacMan_Files\\ghost.png",4,game,80/4,20) song = Sound("PacMan_Files\\song.wav",1) #dots list dot=[] for index in range(100): dot.append(Animation("PacMan_Files\\dot.png",4,game,64/2,64/2)) dot[index].resizeBy(5) for index in range(100): dot[index].draw() x = randint(10,1000) y = randint(10,800) dot[index].moveTo(x,y) #apple list apple=[] for index in range(3): apple.append(Image("PacMan_Files\\apple.png",game)) apple[index].resizeBy(-80) for index in range(3): apple[index].draw() x = randint(10,1000) y = randint(10,800) apple[index].moveTo(x,y) game.setBackground(bk) bk.resizeTo(1000,800) pacman.resizeBy(80) pacman.moveTo(100,390) ghost.resizeBy(400) ghost.moveTo(500,390) while not game.over: game.processInput() bk.draw() ghost.draw() pacman.draw() song.play() #apple points for index in range(3): apple[index].draw() if apple[index].collidedWith(pacman): apple[index].visible=False game.score+=750 #dot/ghost points for index in range(100): dot[index].draw() if dot[index].collidedWith(pacman): dot[index].visible=False game.score+=150 if ghost.collidedWith(pacman): game.score-=650 ghost.moveTo(x,y) #pacman movement if keys.Pressed[K_DOWN]: pacman.y+=10 if keys.Pressed[K_UP]: pacman.y-=10 if keys.Pressed[K_LEFT]: pacman.x-=10 if keys.Pressed[K_RIGHT]: pacman.x+=10 if keys.Pressed[K_ESCAPE]: game.over = True game.quit() quit() #top pacman if pacman.y<=20: pacman.y+=50 game.score-=50 #bottom pacman if pacman.y>=780: pacman.y-=25 game.score-=50 #right pacman if pacman.x>980: pacman.moveTo(25,390) #left pacman if pacman.x<=0: pacman.moveTo(970,390) #ghost code now if keys.Pressed[K_s]: ghost.y+=10 if keys.Pressed[K_w]: ghost.y-=10 if keys.Pressed[K_a]: ghost.x-=10 if keys.Pressed[K_d]: ghost.x+=10 #top ghost if ghost.y<=20: ghost.y+=50 #bottom ghost if ghost.y>=780: ghost.y-=25 #right ghost if ghost.x>=980: ghost.moveTo(25,390) #left ghost if ghost.x<=0: ghost.moveTo(970,390) #pacman and ghost if ghost.collidedWith(pacman): game.score-=500 ghost.moveTo(500,390) #game over if game.time<=0 or game.score<=-1000: game.over=True ending() if game.score>=10000: game.over=True ending_3() game.displayScore(10,10) game.displayTime(110,10) game.update(20) game.quit() #if you win in lvl 2 def ending_3(): game=Game(1000,800,"The End") gg2 = Image("PacMan_Files\\gg2.png",game) win = Image("PacMan_Files\\win.png",game) gg2.resizeTo(1000,800) win.resizeBy(10) win.moveTo(500,700) while not game.over: game.processInput() gg2.draw() win.draw() #pressed and u leave the game if keys.Pressed[K_ESCAPE]: game.over = True game.quit() quit() f1 = Font (blue,50,black,"Comic Sans Ms") game.drawText("Press R to Replay lvl 1",255,20,f1) #press r to replay the game from level 1. if keys.Pressed[K_r]: game.over=True rundown() game.update(30) game.quit() start()
# Napisz klasę Python o nazwie Koło skonstruowaną za pomocą # promienia i dwóch metod, które obliczą obszar i obwód koła class Kolo(): def __init__(self, promien1): self.promien = promien1 def obszar(self): pi = 3.14 obszar1 = pi * self.promien ** 2 return obszar1 def obwod(self): pi = 3.14 obwod1 = (2 * pi) * self.promien return obwod1 obszar1= Kolo(3) obwod1 = Kolo(3) print("Obwod kola = ", obwod1.obwod()) print("Obszar kola = ", obszar1.obszar())
import numpy as np class Agent(object): # Constructor of the Agent class # <Params name="name" type="string">The name of the agent</Params> def __init__(self, name): super(Agent, self).__init__() self.name = name self.game_played=0 self.results=np.array([0,0,0,0,0], dtype=np.int32) # Method which choose an action # <Params name="state" type="np.array(np.int)">The current state of the game</Params> # <Returns type="np.int">The action choosen by the agent : random on available</Returns> def step(self, state): action = np.random.choice([i for i in range(state.shape[0]) if state[i] == 0]) return action # Method which choose an action without updating # <Params name="state" type="np.array(np.int)">The current state of the game</Params> # <Returns type="np.int">The action choosen by the agent : random on available</Returns> def step_train(self, state): return self.step(state) # Method which update the player on a winning game # <Params name="reward" type="np.float">The reward amount for winning</Params> def update(self, reward): pass # Method which update the player on a winning game # <Params name="result" type="string">The result of the game</Params> def end_game(self, result): self.game_played += 1 self.results[result] += 1 pass def __str__(self): return self.name def __repr__(self): return "<Object Agent:Random, Name:{}>".format(self.name)
import random word_bank = ['Do', "yOu", "KnOw", "dE", "wAY", "hOmE", "My", "BrOtHeR", "cLiCk", "ClIcK"] print(word_bank) the_word = random.choice(word_bank) print(the_word) guess_taken = '' letters_guessed = [] while guess_taken != 'quit': guess_taken = input("Guess a letter: ") guess_taken (10)
#!/usr/bin/python3 ''' Python script that, using this REST API, for a given employee ID, returns information about his/her TODO list progress. You must use urllib or requests module The script must accept an integer as a parameter, which is the employee ID The script must display on the standard output the employee TODO list progress in this exact format: First line: Employee EMPLOYEE_NAME is done with tasks (NUMBER_OF_DONE_TASKS/TOTAL_NUMBER_OF_TASKS): EMPLOYEE_NAME: name of the employee NUMBER_OF_DONE_TASKS: number of completed tasks TOTAL_NUMBER_OF_TASKS: total number of tasks, which is the sum of completed and non-completed tasks Second and N next lines: display the title of completed tasks: Tab TASK_TITLE (with 1 tabulation + 1 space before) ''' import requests from sys import argv try: int(argv[1]) id_user = argv[1] user_data = requests.get( 'https://jsonplaceholder.typicode.com/users/{}'.format(id_user)) user_tasks = requests.get( 'https://jsonplaceholder.typicode.com/todos', params={ 'userId': id_user}) username = user_data.json()['name'] user_tasks_json = user_tasks.json() tasks_completed = [] total_tasks = len(user_tasks_json) for task in user_tasks_json: if task['completed']: tasks_completed.append(task['title']) print('Employee {} is done with tasks({}/{}):'.format(username, len(tasks_completed), total_tasks)) for task in tasks_completed: print('\t {}'.format(task)) except Exception: print('Not a valid argument')
has_food = False has_clothes = False from sys import exit import time def song(): print("""I'll be your dream, I'll be your wish, I'll be your fantasy. I'll be your hope, I'll be your love, be everything that you need. I love you more with every breath, truly madly deeply do I will be strong, I will be faithful 'cause I'm counting on a new beginning. A reason for living. A deeper meaning. I want to stand with you on a mountain. I want to bathe with you in the sea. I want to lay like this forever. Until the sky falls down on me And when the stars are shining brightly in the velvet sky, I'll make a wish send it to heaven then make you want to cry The tears of joy for all the pleasure and the certainty. That we're surrounded by the comfort and protection of The highest power, in lonely hours, the tears devour you I want to stand with you on a mountain, I want to bathe with you in the sea. I want to lay like this forever, Until the sky falls down on me Oh can you see it baby? You don't have to close your eyes 'Cause it's standing right before you. All that you need will surely come I'll be your dream, I'll be your wish, I'll be your fantasy. I'll be your hope, I'll be your love, be everything that you need. I'll love you more with every breath, truly madly deeply do I want to stand with you on a mountain I want to bathe with you in the sea. I want to lay like this forever. Until the sky falls down on me I want to stand with you on a mountain I want to bathe with you in the sea. I want to live like this forever. Until the sky falls down on me.""") def kitchen(): global has_food global has_clothes print("""You enter the kitchen and you were pondering on what to get her. ('cat food') or ('human food').""") choice = input("") if "cat food" in choice: print("""You got a bowl and filled it with cat food but you died of heart attack. (Did you seriously think I'm gonna let you do that.)""") quit() if "human food" in choice: print("You got a cup of ramen and you filled it with fish.") has_food = True if has_clothes: living_room_() else: bed_room() def bed_room(): global has_clothes global has_food print("""You entered your bed room to get her clothes. Will you give her a ('black robe') or ('thread bear clothes').""") choice = input("") if "black robe" in choice: print("You went to your closet and got her a black robe and went back to the kicthen.") has_clothes = True if has_food: living_room_() else: kitchen() if "thread bear clothes" in choice: print("""You heard your window break but you fill pain in your head and you fell to the floor. (A little gift from me to you.(pays the sniper $2,000))""") quit() def living_room_(): print("""You enter the room and you place the stuff on the table and you notice that she is still asleep. You sit on the couch and waited for her to wake up.""") time.sleep(5) intro() def intro(): print("""I saw her shift around a little bit afterwards she woke up. She looked around the room than at me. Will you ('greet first') or ('let her greet first').""") choice = input("") if choice == "greet first": print("Hello there, my name is (Y/N) what is yours?") time.sleep(4) print("My name is Ayami. Umm, where am I and how did I get here.") time.sleep(4) print("""I found you in the snow in the worst condition. So, I brought you here. As for where. This place is my house.""") time.sleep(10) print("Thank you, I appreciate your kindness.") time.sleep(4) print("No problem, besides anyone with a kind heart would do the same.") time.sleep(6) print("I got you something to eat and some clothes for you.") time.sleep(5) print("Thank you.(She looks at the food first and grew devious smile.") time.sleep(3) print("(She grabs the bowl and eats the food as she cries with a anime smile on her face.)") time.sleep(6) print('(After a while she finished eating)'"I'll leave you in some privacy") time.sleep(3) print("(You walk out of the room and in the one next to it.)") time.sleep(5) print("I'm properly clothed! (I heard as I reentered the room.)") time.sleep(2) print("Thank you again for your kindness.(She bows her head to me.)") time.sleep(4) print("It's getting late I'll show you to the guest room.") time.sleep(5) print("(You showed her the way to the guest room and she thanked you again for your courtesy)") time.sleep(4) print("(You headed towards your room and lyed down until you fell asleep.)") time.sleep(4) song() if choice == "let her greet first": print("You two stood there forever looking at each other") quit() print("""You were strolling threw the snowy woods until you a beaten up neko girl on the ground. Will you take her with you (#1) or will you leave her in the cold(#2).""") answer = input("") if answer == "1": print("You were a kind hearted person.") time.sleep(6) print("So you decided to take care of her.") time.sleep(6) if answer == "2": print("You thought that the strong survives will the weak should learn.") time.sleep(6) print("So you left her.") time.sleep(6) print("Cruel End.") quit() print("""You droped her off in the living room in front of the fire place. Will you go to the ('kitchen') to get her food or to your ('bed room') to get her better clothing.""") choice = input("") if choice == "kitchen": kitchen() elif choice == "bed room": bed_room()
import socket class Resolver: def __init__(self): self._cache = {} def __call__(self, host): """__call__ makes instances of this class callable like a function e.g. resolver = Resolver() resolver("myhost") -- note this invokes the __call__ method The instructor said its good for caching, didnt follow on that exactly.""" if host not in self._cache: self._cache[host] = socket.gethostbyname(host) return self._cache[host] def conditional_expression_example(my_bool): """Below is an example of conditional expression It reads better than if else blocks""" return True if my_bool == "yes" else False def example_lambda_func(): """Example of using lambda functions in python""" names = ["Rico Romero", "Celine Zhang", "Brian Lawson", "Shelly Murriel", "Tom Abe"] sort_by_last_name = sorted(names, key=lambda name: name.split()[-1]); for name in sort_by_last_name: print(name) def example_extended_formal_arg_syntax(*args, **kwargs): """args is a tuple and kwargs is a dictionary, ordering of these arguments matter when defining the function. You can google search all rules""" print(type(args)) print(type(kwargs)) def example_extended_call_syntax_iter(name, age, *args): """You can pass in a itterable like a tuple that gets unpacked to name and age, and the rest in *args t = ("Rico", 27, "he is cool", "he is married") example_extended_call_sytax_iter(*t)""" print(name) print(age) print(args) def example_extended_call_syntax_map(name, phone, **kwargs): """You can pass in a map like a dectionary that gets unpacked to name and phone, and the rest in *args d = {name: "Rico", phone: 313, isCool: True} example_extended_call_syntax_map(**d)""" print(name) print(phone) print(kwargs) if __name__ == "__main__": example_lambda_func() t = ("Rico", 27, "he is cool", "he is married") example_extended_call_syntax_iter(*t) d = {"name": "Rico", "phone": 313, "isCool":True } example_extended_call_syntax_map(**d)
import numpy from chainer import backend from chainer import initializer from chainer import utils # Original code forked from MIT licensed keras project # https://github.com/fchollet/keras/blob/master/keras/initializations.py class Orthogonal(initializer.Initializer): """Initializes array with an orthogonal system. This initializer first makes a matrix of the same shape as the array to be initialized whose elements are drawn independently from standard Gaussian distribution. Next, it applies QR decomposition to (the transpose of) the matrix. To make the decomposition (almost surely) unique, we require the diagonal of the triangular matrix R to be non-negative (see e.g. Edelman & Rao, https://web.eecs.umich.edu/~rajnrao/Acta05rmt.pdf). Then, it initializes the array with the (semi-)orthogonal matrix Q. Finally, the array is multiplied by the constant ``scale``. If the ``ndim`` of the input array is more than 2, we consider the array to be a matrix by concatenating all axes except the first one. The number of vectors consisting of the orthogonal system (i.e. first element of the shape of the array) must be equal to or smaller than the dimension of each vector (i.e. second element of the shape of the array). Attributes: scale (float): A constant to be multiplied by. dtype: Data type specifier. Reference: Saxe et al., https://arxiv.org/abs/1312.6120 """ def __init__(self, scale=1.1, dtype=None): self.scale = scale super(Orthogonal, self).__init__(dtype) # TODO(Kenta Oono) # How do we treat overcomplete base-system case? def __call__(self, array): if self.dtype is not None: assert array.dtype == self.dtype xp = backend.get_array_module(array) if not array.shape: # 0-dim case array[...] = self.scale * (2 * numpy.random.randint(2) - 1) elif not array.size: raise ValueError('Array to be initialized must be non-empty.') else: # numpy.prod returns float value when the argument is empty. flat_shape = (len(array), utils.size_of_shape(array.shape[1:])) if flat_shape[0] > flat_shape[1]: raise ValueError('Cannot make orthogonal system because' ' # of vectors ({}) is larger than' ' that of dimensions ({})'.format( flat_shape[0], flat_shape[1])) a = numpy.random.normal(size=flat_shape) # cupy.linalg.qr requires cusolver in CUDA 8+ q, r = numpy.linalg.qr(a.T) q *= numpy.copysign(self.scale, numpy.diag(r)) array[...] = xp.asarray(q.T.reshape(array.shape))
import random import time #Players can create their name def newName(): print('>>>Please create a name for your player.<<<') global username username=input() print('***Name changed to >', username,'<***') print('\n\n') time.sleep(3) newName() #Intro scene one Note: Add more stories/levels def introScene(): print('>Welcome Master', username,'.') time.sleep(2) print('\n') print('>We are glad you have decided to set out on this quest.') print('>You are our last hope to reclaim what was righteously ours.') time.sleep(5) introScene() #Prompt that asks for special replies def selectReply(): print('\n') print('>>>Please reply by typing one of the numbered options<<<') time.sleep(1) selectReply() #Unlassicied- Prompts for Scene one introChoiceOne = ' 1 | What was stolen?' introChoiceTwo = '2 | Who stole what was yours?' print(introChoiceOne,'\n',introChoiceTwo) #Compares user input with prompts def INTROresponse(): introChoiceInput = input() global introChoiceResponse introChoiceResponse = int(introChoiceInput) #Returns user submission def INTROanswer(): if introChoiceResponse == 1: print('>Master',username,', our box of jewels was stolen. The box is priceless.') elif introChoiceResponse == 2: print('>Master',username,', the thief was a large dragon.') #Junks the repeats the process for all info above INTROresponse() INTROanswer() print('Try other option\n') INTROresponse() INTROanswer() print('\n') def chooseCave(): cave = '' while cave != '1' and cave != '2' and cave !='3': print('Select a cave to go into. (1,2,3)') cave = input() return cave chooseCave() ### I'll work on this later when I figure out the story. Kinda Lame ATM #def checkCave(): # global userName #print(str(username),' approaches the cave...') #time.sleep(2) #print('It is dark and spooky...') #time.sleep(2) # print('A large dragon jumps out in front of ',str(userName),'! He opens his jaws and...') # print() # time.sleep(2) #checkCave() # friendlyCave = random.randint(1,3) #if chooseCave == str(friendlyCave): # print('Gives ',str(userName),' his treasure!') # else: # print('Gobbles ',str(userName),' down in one bite!') #caveNumber = chooseCave() #checkCave(caveNumber)
words = ['one', 'two', 'three', 'four', 'five'] x = 0 while(x < 5): print(words[x]) x += 1
def unflatten_dict(d): result = {} for key, value in d.items(): key_parts = key.split(".") rdict = result for part in key_parts[:-1]: if part not in rdict: rdict[part] = {} rdict = rdict[part] rdict[key_parts[-1]] = value return result a= {'a':1, 'c.x':2, 'c.y.u':3, 'c.y.v':4, 'b':5} print unflatten_dict(a)
# the return values of key functions are checked instead of the original list def unique(a_list, key = lambda x: x): unique_elements = [] temp_list = [key(i) for i in a_list] for i in range(0,len(temp_list)): if temp_list[i] not in temp_list[i+1:]: unique_elements.append(temp_list[i]) return unique_elements print unique(['python', 'Java', 'PYTHON', 'jAVA', 'perl'], key = lambda x: x.lower())
def is_pref(pref, Str): if(len(pref) > len(Str)): return False if(pref != Str[0:len(pref)]): return False return True def search(a, b): queue = [] reminder_a = set() reminder_b = set() for i in range(0, len(a)): for j in range(0, len(b)): if(hash(a[i]) == hash(b[j]) and a[i] == b[j]): return [[i], [j]] if(is_pref(a[i], b[j])): if(b[j][len(a[i]):] not in reminder_b): reminder_b.add(b[j][len(a[i]):]) queue.append([False, [i], [j], a[i], b[j], b[j][len(a[i]):]]) print(i, j) if(is_pref(b[j], a[i])): if(a[i][len(b[j]):] not in reminder_a): print(i, j) print(a[i][len(b[j]):]) reminder_a.add(a[i][len(b[j]):]) queue.append([True, [i], [j], a[i], b[j], a[i][len(b[j]):]]) print("") #aaaabbbaabbaaaaabbbabbba abbba #aaa abb baa bbaaaa abbb aabbb aaabbb bbba # for q in queue: # q[0] = True if concatenated a-sequence is longer then concatenated b-sequence # q[1] = sequence of a-indexes # q[2] = sequence of b-indexes # q[3] = concatenated a-sequence # q[4] = concatenated b-sequence # q[5] = queue[4] - queue[3] if queue[0] == True while(queue != []): L = len(queue) for i in range(0, L): cur = queue.pop(0) if(cur[0]): for j in range(0, len(b)): if(is_pref(cur[5], b[j])): if(cur[3] == cur[4] + b[j]): return [cur[1], cur[2] + [j]] rem = b[j][len(cur[5]):] if(rem not in reminder_b): reminder_b.add(rem) print(cur[1], cur[2] + [j]) queue.append([False, cur[1], cur[2] + [j], cur[3], cur[4] + b[j], rem]) if(is_pref(b[j], cur[5])): rem = cur[5][len(b[j]):] if (rem not in reminder_a): reminder_a.add(rem) print(cur[1], cur[2] + [j]) queue.append([True, cur[1], cur[2] + [j], cur[3], cur[4] + b[j], rem]) else: for j in range(0, len(a)): if (is_pref(cur[5], a[j])): if (cur[4] == cur[3] + a[j]): return [cur[1] + [j], cur[2]] rem = a[j][len(cur[5]):] if (rem not in reminder_a): reminder_a.add(rem) print(cur[1] + [j], cur[2]) queue.append([True, cur[1] + [j], cur[2], cur[3] + a[j], cur[4], rem]) if (is_pref(a[j], cur[5])): rem = cur[5][len(a[j]):] if (rem not in reminder_b): reminder_b.add(rem) print(cur[1] + [j], cur[2]) queue.append([False, cur[1] + [j], cur[2], cur[3] + a[j], cur[4], rem]) return [[-1], [-1]] def main(): print("Enter strings a_i in one line divided by space") a = input().split() print("Enter strings b_i in one line divided by space") b = input().split() answer = search(a, b) if(answer[0][0] == -1): print("There's no solution") else: print("a:", end = " ") for i in range(0, len(answer[0])): print(answer[0][i] + 1, end=" ") print("\nb:", end = " ") for i in range(0, len(answer[1])): print(answer[1][i] + 1, end=" ") print("") for i in range(0, len(answer[0])): print(a[answer[0][i]], end = "") if(i != len(answer[0]) - 1): print(" + ", end = "") else: print(" = ", end = "") for i in range(0, len(answer[1])): print(b[answer[1][i]], end = "") if(i != len(answer[1]) - 1): print(" + ", end = "") if __name__ == "__main__": main()
# unit testing for card class import unittest import card class TestCardFunctions(unittest.TestCase): def setUp(self): self.validValues = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Ace', 'King', 'Queen', 'Jack'] self.validSuits = { 1 :'Spades', 2 : 'Clubs', 3 : 'Hearts', 4 : 'Diamonds'} self.cardValue = 'Jack' self.cardSuit = 2 self.card = card.Card(self.cardValue, self.cardSuit) def test_value(self): self.assertEqual(self.cardValue, self.card.get_value()) self.assertIn(self.card.get_value(), self.validValues) def test_str(self): self.assertEqual((str(self.cardValue) + " of " + self.validSuits[self.cardSuit]), str(self.card)) if __name__ == '__main__': unittest.main()
class Card: suits = {1 : 'Spades', 2 : 'Clubs', 3 : 'Hearts', 4 : 'Diamonds',} def __init__(self, value, suit): self.suit = suit self.value = value def get_value(self): return self.value def __repr__(self): return str(self.value) + " of " + Card.suits[self.suit]
import abc import random class ShuffleStrategy(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def shuffle(self, deck): return class RandomShuffleStrategy(ShuffleStrategy): def shuffle(self, deck): return random.shuffle(deck) class AppendShuffleStrategy(ShuffleStrategy): def shuffle(self, deck): for x in range(0, len(deck)): deck.append(deck.pop(random.randint(0, len(deck) -1))) class EvenOddShuffleStrategy(ShuffleStrategy): def shuffle(self, deck): for even_number in range(0, len(deck), 2): odd_number = random.choice(xrange(1, len(deck), 2)) temp = deck[even_number] deck[even_number] = deck[odd_number] deck[odd_number] = temp class ExchangeShuffleStrategy(ShuffleStrategy): def shuffle(self, deck): pass
#9. Palindrome Number #https://leetcode.com/problems/palindrome-number/ class Solution: def isPalindrome(self, x: int) -> bool: y=str(x) if x>=0: a=int(y[::-1]) else: a=int(y[:0:-1]) return bool(x==a)
#Import the argv variable from the sys package from sys import argv #Set script and filename equal to the first and second arguments script, filename = argv #Print out the file name and give users instructions print("We're going to erase %r." %filename) print("If you don't want that, hit CTRL-C (^C).") print("If you do want that, hit RETURN.") #Wait for the user to hit enter (or really any button) or ctrl-c input("?") #Open the file in write mode print("Opening the file...") target = open(filename, "w") #Delete the file by truncating everything after the current (i.e. before the first) line print("Truncating the file. Goodbye!") target.truncate() #Give user information print("Now I'm going to ask you for three lines.") #Get three strings and store in line1, line2, line3 line1 = input("Line 1: ") line2 = input("LIne 2: ") line3 = input("Line 3: ") #Give user information print("I'm going to write these to the file.") #Write the three input strings to the bare file target.write("%s\n%s\n%s\n" %(line1, line2, line3)) #Close the file print("And finally, we close it.") target.close()
def fibo(n): if n < 0: raise ValueError, "argument must be positive" if n == 0: return 0 if n == 1: return 1 return fibo(n-1) + fibo(n-2)
import re from collections import Counter, defaultdict from typing import Dict # re maintains internal cache of recent compiled expression, but we're compiling and storing it for clarity anyway word_re = re.compile('[a-zA-Z]+') # will eat all the memory if the file is a huge single line def process(file: str) -> Dict[str, int]: result = Counter() with open(file) as f: for line in f: for match in word_re.findall(line): result[match] += 1 return result def render(d: Dict[str, int]) -> str: buckets = defaultdict(set) for word, count in d.items(): buckets[count].add(word) result = '' for count, words in sorted(buckets.items(), reverse=True): # sort by count for word in sorted(words, key=lambda w: (w.lower(), len(w))): # sort by alphabet result += f'{word}: {count}\n' return result.strip()
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 10) # arg1 = start, arg2 = end, arg3 = number of points y = np.sin(x) plt.plot(x, y) plt.show() # Add some labels plt.xlabel("Time") plt.ylabel("Some function of time") plt.title("My cool chart") plt.show()
import numpy as np from pandas import DataFrame from patsy import dmatrices import dataframe as ka_df def predict(test_data, results, model_name): """ Return predictions of based on model results. Parameters ---------- test_data: DataFrame should be test data you are trying to predict results: dict should be dict of your models results wrapper and the formula used to produce it. ie. results['Model_Name'] = [<statsmodels.regression.linear_model.RegressionResultsWrapper>, "Price ~ I(Supply, Demand)] model_name: str should be the name of your model. You can iterate through the results dict. Returns ------- NumPy array Predictions in a flat NumPy array. Example ------- results = { 'Logit': [<statsmodels.discrete.discrete_model.BinaryResultsWrapper at 0x117896650>, 'survived ~ C(pclass) + C(sex) + age + sibsp + C(embarked)'] } compared_resuts = predict(test_data, results, 'Logit') """ model_params = DataFrame(results[model_name][0].params) formula = results[model_name][1] # Create regression friendly test DataFrame yt, xt = dmatrices(formula, data=test_data, return_type='dataframe') xt, model_params = ka_df.get_dataframes_intersections(xt, xt.columns, model_params, model_params.index) # Convert to NumPy arrays for performance model_params = np.asarray(model_params) yt = np.asarray(yt) yt = yt.ravel() xt = np.asarray(xt) # Use our models to create predictions row, col = xt.shape model_parameters = model_params.ravel() model_array = list((model_parameters for parameter in xrange(row))) model_array = np.asarray(model_array) # Multiply matrix together predictions = np.multiply(xt, model_array) predictions = np.sum(predictions, axis=1) return predictions def category_boolean_maker(series): ''' A function for to designate missing records from observed ones. When used with the pandas df.series.apply() method, it will create a boolean category variable. If values exist the bool will register as 1, if nan values exist the bool will register as 0. Parameters ---------- series : Series A pandas series to perform comparison on. Returns ------- Int : 0 or 1 for missing values. ''' return 0 if np.isnan(series) is True else 1 def columns_to_str(column_list, operand=', ', return_list=False): ''' Return the list of features as strings for easy implementation patsy formulas. Parameters ---------- column_list : list A list of features, usually from generated from pandas's df.columns function. operand : str a sting to join list together by. Default is a comma: ', '. Could be a plus: ' + ' for patsy equations. return_list : boolean ( optional ) return the list of features typecasted to str. Returns ------- list : a list with elements typecasted to str. Example ------- df.columns >>> Index([x3yv_E, x3yv_D, x1yv_E, x1yv_D], dtype=object) columns_to_str(df.columns) >>> Index(['x3yv_E', 'x3yv_D', 'x1yv_E', 'x1yv_D'], dtype=object) >>> ['x3yv_E', 'x3yv_D', 'x1yv_E', 'x1yv_D'] ''' if return_list: return list((str(feature) for feature in column_list)) print "[%s]" % operand.join(map(str, column_list)) def ml_formula(y, df): ''' Returns a string as a formula for patsy's dmatrices function. Parameters ---------- y : str a string of the variable your trying to predict. df : DataFrame the data frame your trying to make your predictions on. Returns ------- str : a string of the desired formula Example ------- y = "icecream_sales" df = pandas.DataFrame(columns=['icecream_sales','sunny_days', 'incidence_of_lactose_intolerance']) ml_formula(y, df) >>> 'icecream_sales ~ sunny_days + incidence_of_lactose_intolerance' ''' independent_variable = y + ' ~ ' dependent_variables = ' + '.join((val for i, val in enumerate(df.columns) if val != y)) formula = independent_variable + dependent_variables return formula def category_clean(category_value): """ Retun a 0 for np.NaN values. Useful for cleaning categorical variables in a df.apply() function by setting the NaN to 0 so it can be processed by a patsy dmatrices function. Parameters ---------- category_value : the category_value to be processed. Retruns ------- str / category_value : category_value or int(0) in place of a NaN value. """ if isinstance(category_value, str) is False and np.isnan(category_value) is True: return 0 return category_value def filter_features(model_results, significance=0.1): ''' Returns a list of features that are below a given level of significance. Parameters ---------- model_results : Series a pandas series of the results.pvalues of your model significance : float significance level, default at 90% confidence. Returns ------- list : a list of columns below the given significance level ''' return list((model_results.index[index] for index, pvalues in enumerate(model_results) if pvalues > significance))
#!/usr/bin/env python3 input = open('day03.txt').read().strip().split('\n') def consider(numbers, position, criteria): bits = [x[position] for x in numbers] if criteria == 'most': return '1' if bits.count('1') >= bits.count('0') else '0' elif criteria == 'least': return '0' if bits.count('0') <= bits.count('1') else '1' def part1(input): def calculate(criteria): rate = '' for i in range(len(input[0])): rate += consider(input, i, criteria) return int(rate, 2) gamma_rate = calculate('most') epsilon_rate = calculate('least') return gamma_rate * epsilon_rate def part2(input): def search(criteria): numbers = [x for x in input] for i in range(len(input[0])): bit = consider(numbers, i, criteria) numbers = [x for x in numbers if x[i] == bit] if len(numbers) == 1: break return int(numbers[0], 2) oxygen_generator_rating = search('most') CO2_scrubber_rating = search('least') return oxygen_generator_rating * CO2_scrubber_rating if __name__ == '__main__': print('--- Day 3: Binary Diagnostic ---') print(f'Part 1: {part1(input)}') print(f'Part 2: {part2(input)}')
#!/usr/bin/env python3 import re input = open("day10.txt").read().strip() class CPU: def __init__(self, program: str) -> None: self.instructions = program.split("\n") self.X = 1 self.V = 0 self.cycle = 0 self.index = 0 self.command = None self.remaining = 0 def start_cycle(self) -> bool: self.cycle += 1 if self.remaining > 0: return True try: instruction = self.instructions[self.index] self.index += 1 except: return False command = instruction.split(" ") self.command = command[0] if self.command == "noop": self.remaining = 1 return True elif self.command == "addx": self.V = int(command[1]) self.remaining = 2 return True return False def during_cycle(self): if self.remaining > 0: self.remaining -= 1 def end_cycle(self): if self.remaining == 0: if self.command == "addx": self.X += self.V class CRT: def __init__(self) -> None: self.cycle = 0 self.wide = 40 self.high = 6 self.pixels = {} for r in range(self.high): for c in range(self.wide): self.pixels[(r, c)] = "." def during_cycle(self, sprite): self.cycle += 1 position = self.cycle - 1 position %= self.wide * self.high r = int(position / self.wide) c = int(position % self.wide) self.pixels[(r, c)] = "#" if c in sprite else "." def draw(self): output = [] for r in range(self.high): for c in range(self.wide): pixel = self.pixels[(r, c)] output.append(pixel) output.append("\n") return "".join(output) def part1(): sum = 0 cpu = CPU(input) while cpu.start_cycle(): cpu.during_cycle() if cpu.cycle in (20, 60, 100, 140, 180, 220): strength = cpu.cycle * cpu.X sum += strength cpu.end_cycle() return sum def part2(): crt = CRT() cpu = CPU(input) while cpu.start_cycle(): cpu.during_cycle() sprite = [cpu.X - 1, cpu.X, cpu.X + 1] crt.during_cycle(sprite) cpu.end_cycle() return crt.draw() if __name__ == "__main__": print("--- Day 10: Cathode-Ray Tube ---") print(f"Part 1: {part1()}") print(f"Part 2: \n{part2()}")
#!/usr/bin/env python3 input = open("day08.txt").read().strip() map = [[int(c) for c in r] for r in input.split("\n")] def part1(): visible = 2 * len(map) + 2 * len(map[0]) - 4 for r in range(1, len(map) - 1): for c in range(1, len(map[r]) - 1): given = map[r][c] directions = [ [map[x][c] for x in range(0, r)], # up [map[x][c] for x in range(r + 1, len(map))], # down [map[r][x] for x in range(0, c)], # left [map[r][x] for x in range(c + 1, len(map[r]))], # right ] for direction in directions: if given > max(direction): visible += 1 break return visible def part2(): highest = 0 for r in range(1, len(map) - 1): for c in range(1, len(map[r]) - 1): given = map[r][c] directions = [ [map[x][c] for x in reversed(range(0, r))], # up [map[x][c] for x in range(r + 1, len(map))], # down [map[r][x] for x in reversed(range(0, c))], # left [map[r][x] for x in range(c + 1, len(map[r]))], # right ] score = 1 for direction in directions: view = 0 for tree in direction: view += 1 if tree >= given: break score *= view if score > highest: highest = score return highest if __name__ == "__main__": print("--- Day 8: Treetop Tree House ---") print(f"Part 1: {part1()}") print(f"Part 2: {part2()}")
#!/usr/bin/env python3 class Day9: def __init__(self, inputs): self.numbers = [int(x) for x in inputs.split('\n')] def check(self, preamble, number): length = len(preamble) for i in range(length - 1): for j in range(i + 1, length): if preamble[i] != preamble[j]: if preamble[i] + preamble[j] == number: return preamble[i], preamble[j] def part1(self): length = 25 index = 0 while index + length < len(self.numbers): preamble = self.numbers[index: index + length] number = self.numbers[index + length] if not self.check(preamble, number): self.weakness = number return number index += 1 def part2(self): length = 2 while length < len(self.numbers): index = 0 while index + length < len(self.numbers): numbers = self.numbers[index: index + length] if sum(numbers) == self.weakness: return min(numbers) + max(numbers) index += 1 length += 1 def main(): inputs = open("day09.txt").read().strip() day9 = Day9(inputs) print(f'Part 1: {day9.part1()}') print(f'Part 2: {day9.part2()}') if __name__ == "__main__": main()
#!/usr/bin/env python3 NORTH = 'N' SOUTH = 'S' EAST = 'E' WEST = 'W' LEFT = 'L' RIGHT = 'R' FORWARD = 'F' class Ship1: def __init__(self): self.face = EAST self.position = [0, 0] def handle(self, instruction): action = instruction[0] value = instruction[1] if action == FORWARD: action = self.face if action == NORTH: self.position[1] += value elif action == SOUTH: self.position[1] -= value elif action == EAST: self.position[0] += value elif action == WEST: self.position[0] -= value elif action == LEFT: self.turn_left(value) elif action == RIGHT: self.turn_right(value) def turn_left(self, value): def turn(): if self.face == EAST: self.face = NORTH elif self.face == NORTH: self.face = WEST elif self.face == WEST: self.face = SOUTH elif self.face == SOUTH: self.face = EAST while value: value -= 90 turn() def turn_right(self, value): def turn(): if self.face == EAST: self.face = SOUTH elif self.face == SOUTH: self.face = WEST elif self.face == WEST: self.face = NORTH elif self.face == NORTH: self.face = EAST while value: value -= 90 turn() def manhattan(self): return abs(self.position[0]) + abs(self.position[1]) class Ship2: def __init__(self): self.waypoint = [10, 1] self.position = [0, 0] def handle(self, instruction): action = instruction[0] value = instruction[1] if action == NORTH: self.waypoint[1] += value elif action == SOUTH: self.waypoint[1] -= value elif action == EAST: self.waypoint[0] += value elif action == WEST: self.waypoint[0] -= value elif action == LEFT: while value: value -= 90 self.waypoint = [-self.waypoint[1], self.waypoint[0]] elif action == RIGHT: while value: value -= 90 self.waypoint = [self.waypoint[1], -self.waypoint[0]] elif action == FORWARD: offset = [x * value for x in self.waypoint] self.position = [sum(x) for x in zip(self.position, offset)] def manhattan(self): return abs(self.position[0]) + abs(self.position[1]) class Day12: def __init__(self, inputs): self.instructions = [(x[0], int(x[1:])) for x in inputs.split('\n')] def part1(self): ship = Ship1() for instruction in self.instructions: ship.handle(instruction) return ship.manhattan() def part2(self): ship = Ship2() for instruction in self.instructions: ship.handle(instruction) return ship.manhattan() def main(): inputs = open("day12.txt").read().strip() day12 = Day12(inputs) print(f'Part 1: {day12.part1()}') print(f'Part 2: {day12.part2()}') if __name__ == "__main__": main()
#!/usr/bin/env python3 def six_digit(digits): return len(digits) == 6 def same_adjacent_digits(digits): for i in range(len(digits) - 1): if digits[i] == digits[i + 1]: return True return False def not_part_of_larger(digits): # [i-1] != [i] == [i+1] != [i+2] for i in range(len(digits) - 1): if (i == 0 or digits[i - 1] != digits[i]) and digits[i] == digits[i + 1] and (i >= 4 or digits[i + 1] != digits[i + 2]): return True return False def never_decrease(digits): for i in range(len(digits) - 1): if digits[i] > digits[i + 1]: return False return True def is_meet_criteria(password, part): digits = [int(digit) for digit in str(password)] # Six-digit number if not six_digit(digits): return False # Two adjacent digits are the same if part == 1 and not same_adjacent_digits(digits): return False # Not part of a larger group of matching digits elif part == 2 and not not_part_of_larger(digits): return False # The digits never decrease if not never_decrease(digits): return False return True def main(): with open('day4.txt') as f: values = f.read().strip().split('-') rule_range = [int(value) for value in values] def part(id): count = 0 for password in range(rule_range[0], rule_range[1] + 1): if is_meet_criteria(password, id): count += 1 return count # Part1 print("Part 1:", part(1)) # Part2 print("Part 2: ", part(2)) if __name__ == "__main__": main()
#!/usr/bin/env python3 rucksacks = [x for x in open("day03.txt").read().strip().split("\n")] def get_prioritie(item): if "a" <= item <= "z": return ord(item) - 96 elif "A" <= item <= "Z": return ord(item) - 38 return 0 def part1(): priorities = [] for items in rucksacks: half = int(len(items) / 2) compartment1 = items[:half] compartment2 = items[half:] def find_share(): for type1 in compartment1: for type2 in compartment2: if type1 == type2: return type1 share = find_share() prioritie = get_prioritie(share) priorities.append(prioritie) return sum(priorities) def part2(): priorities = [] for i in range(0, len(rucksacks), 3): rucksack1 = rucksacks[i] rucksack2 = rucksacks[i + 1] rucksack3 = rucksacks[i + 2] def find_share(): for type1 in rucksack1: for type2 in rucksack2: for type3 in rucksack3: if type1 == type2 == type3: return type1 share = find_share() prioritie = get_prioritie(share) priorities.append(prioritie) return sum(priorities) if __name__ == "__main__": print("--- Day 3: Rucksack Reorganization ---") print(f"Part 1: {part1()}") print(f"Part 2: {part2()}")
a = 10 b = 2 try: print('resource open') print(a/b) k = int(input('Enter a number')) print(k) except ZeroDivisionError as e:# not even e you can use another.... print('You cannot divide a number by zero',e) except ValueError as e: print('Invalid Input',':',e) except Exception as e: print('something went wrong',':',e) finally: print('resource closed') print('bye')
def count_construct(target,word_bank=[]): table_size=len(target)+1 table=[] for i in range(table_size): table.append(0) #initialize table[0] with 1 as there is ONE way to create an empty string table[0]=1 #now iterate through the indices of the table for i in range(table_size): #iterate through the words of the word_bank for word in word_bank: #check if the word matches the part of the string starting from this index if(target[i:i+len(word)]==word): #update the other positions of the table by adding the current position's number to those positions table[i+len(word)]+=table[i] return table[len(target)] def main(): print(count_construct("hello", ["he", "l", "o"])) print(count_construct("purple",["purp","p","ur","le","purpl"])) print(count_construct("rajamati", [ "s", "raj", "amat", "raja", "ma", "i", "t"])) print(count_construct("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef", [ "e", "eee", "eeee", "eeeee"])) main()
m = [9,15,24] def modify(k): k.append(39) print(f'k = {k}') modify(m) f = [14,23,37] def replace (g): g = [17,28,45] print(f'g = {g}') replace(f) print(f'f = {f}') #The original f list is still the same and g is a new list #To replace f by g, we need to modify the contents like this: def replace_contents(g): g[0]= 17 g[1]=28 g[2]=45 print(f'g = {g}') #now make the function call and print f replace_contents(f) print(f'f = {f}') def f(d): return d c = [6,10,16] e=f(c) print(e is c)
import math print(math.sqrt(81)) print(math.factorial(5)) print(math.factorial(6)) n = 5 k = 3 print((math.factorial(5))/((math.factorial(3))*math.factorial(n-k))) #Since we know it will always return an integer, we can change it to integer division by addin double slashes instead of one print((math.factorial(5))//((math.factorial(3))*math.factorial(n-k))) print(len(str(math.factorial(100))))
import unittest import os def analyze_text(filename): number_of_lines=0 number_of_chars = 0 with open(filename, mode='rt', encoding='utf-8') as f: for line in f: number_of_lines = number_of_lines+1 number_of_chars+=len(line) print(f"Number of lines is {number_of_lines}") return (number_of_lines,number_of_chars) class TextAnalysisTests(unittest.TestCase): """Test for the analyze_text() function""" def setUp(self): """Fixture that creates a file for the text methods to use""" self.filename = 'text_abalysis_test_file.txt' with open(self.filename, 'w') as f: f.write('Now we are engaged ina great civil war.\n' 'testing whether that nation,\n' 'or any nation so conceived and so dedicated,\n' 'can long endure.') def tearDown(self): try: os.remove(self.filename) except: pass def test_function_runs(self): """Basic smoke test: does the function run""" analyze_text(self.filename) def test_line_count(self): """Check that the line count is correct""" self.assertEqual(analyze_text(self.filename)[0],4) def test_character_count(self): self.assertEqual(analyze_text(self.filename)[1], 131) def test_no_such_file(self): with self.assertRaises(IOError): analyze_text('foobar') def test_no_deletion(self): analyze_text(self.filename) self.assertTrue(os.path.exists(self.filename)) if __name__ == '__main__': unittest.main()
from typing import List, Any Fruits = ["apple", "orange", "pear"] print(Fruits) Fruits[1] = "Bannana" print(Fruits) Fruits[2]=7 print(Fruits) emptyList=[] print(emptyList) emptyList.append(1.5) print(emptyList) emptyList.append(2) print(emptyList) charList= list("characters") print(charList)