text
stringlengths
37
1.41M
print('Enter command. Type "-help" for help.') command = input() if command == 'add': print('Enter your first number.') number1 = int(input()) print('Enter your second number.') number2 = int(input()) print('Answer:') print(number1 + number2) exit() if command == 'subtract': print('Enter your first number.') number1 = int(input()) print('Enter your second number.') number2 = int(input()) print('Answer:') print(number1 - number2) exit() if command == 'multiply': print('Enter your first number.') number1 = int(input()) print('Enter your second number.') number2 = int(input()) print('Answer:') print(number1 * number2) exit() if command == 'divide': print('Enter your first number.') number1 = int(input()) print('Enter your second number.') number2 = int(input()) print('Answer:') print(number1 / number2) exit() if command =='-help': print('What method would you like to use?') print('To use addition, type "add".') print('To use subtraction, type "subtract".') print('To use multiplication, type "multiply".') print('To use division, type "divide".') print('To calculate square root, type "square root" (will calculate your first number)') command_after_help = input() if command_after_help == 'add': print('Enter your first number.') number1 = int(input()) print('Enter your second number.') number2 = int(input()) print('Answer:') print(number1 + number2) exit() if command_after_help == 'subtract': print('Enter your first number.') number1 = int(input()) print('Enter your second number.') number2 = int(input()) print('Answer:') print(number1 - number2) exit() if command_after_help == 'multiply': print('Enter your first number.') number1 = int(input()) print('Enter your second number.') number2 = int(input()) print('Answer:') print(number1 * number2) exit() if command_after_help == 'divide': print('Enter your first number.') number1 = int(input()) print('Enter your second number.') number2 = int(input()) print('Answer:') print(number1 / number2) exit()
class Node(object): def __init__(self, element, next_=None): self.elem = element self.next = next_ class SingleLinkListUnderflow(ValueError): pass class SingleLinkList(object): def __init__(self): self._head = None def is_empty(self): return self._head is None def len(self): count = 0 if self._head is None: return count p = self._head while p is not None: p = p.next count += 1 print(count) return count def pop(self): if self._head is None: raise SingleLinkListUnderflow() v = self._head.elem self._head = self._head.next return v def pop_last(self): if self._head is None: raise SingleLinkListUnderflow() p = self._head if p.next is None: v = p.elem self._head = None return v while p.next.next is not None: p = p.next v = p.next.elem p.next = None return v def append(self, elem): self._head = Node(elem, self._head) def append_last(self, elem): if self._head is None: self._head = Node(elem) return p = self._head while p.next is not None: p = p.next p.next = Node(elem) def print_all(self): p = self._head while p is not None: print(p.elem, end='') if p.next is not None: print(',', end='') p = p.next print('') def rev_(self): q = None while self._head is not None: p = self._head self._head = self._head.next p.next = q q = p self._head = q if __name__ == '__main__': llist = SingleLinkList() for i in range(11, 25): llist.append(i) llist.print_all() llist.len() llist.pop_last() llist.len() llist.print_all()
from turtle import * import math class ColourfulSquare: def __init__(self, x, y, size): self.coords = (x,y) self.sideLength = size def getIncrementedCoords(self, numberToAdd): return (self.coords[0] + numberToAdd, self.coords[1] + numberToAdd) def isUnderDiagonal(self, coords): xSideLength = coords[0] - self.coords[0] alpha = math.radians(45) #diagonals in square heightOfPoint = (self.sideLength - xSideLength) * math.tan(alpha) return heightOfPoint >= coords[1] def draw(self): ownDrawer = Turtle() ownDrawer.speed(2000) ownDrawer.pensize(10) for i in range((self.coords[0] + self.sideLength)//10) : for j in range((self.coords[1] + self.sideLength) // 10): crntCoords = (i*10,j*10) crntColor = self.decide_color(crntCoords) ownDrawer.pencolor(crntColor) ownDrawer.penup() ownDrawer.goto(crntCoords) ownDrawer.pendown() ownDrawer.dot() print(crntCoords) pass def decide_color (self, coords): innerSquareCoords = self.getIncrementedCoords(self.sideLength / 3) isInInnreSquare = (coords[0] >= innerSquareCoords[0]) and (coords[0] <= innerSquareCoords[0] + self.sideLength / 3) and \ (coords[1] >= innerSquareCoords[1]) and (coords[1] <= innerSquareCoords[1] + self.sideLength / 3) isUnderDiagonal = self.isUnderDiagonal(coords) if isInInnreSquare: return "white" elif isUnderDiagonal: return "black" else: return "gray" square = ColourfulSquare(0,0,200) square.draw() while True: pass
# ----------------------------------------------- # I usually don't write that many comments, as I believe code is in most cases self-explanatory # my previous Teacher wanted a lot of comments, just tell me if I can write less and I'd be glad :) # ----------------------------------------------- # algorithm taken from lecture, as is def ggT(a, b): a0,b0 = a,b ra,sa = 1,0 rb,sb = 0,1 while b > 0: assert (a == ra * a0 + sa * b0 and b == rb * a0 + sb * b0) q = a // b a,b = b, a - q*b ra, sa, rb, sb = rb, sb, ra - q*rb, sa - q*sb return a, ra, sa #passing function as argument to tell which functon should be tested; default function is ggT def testGGT(a,b, ggtFunction = ggT): t,r,s = ggtFunction(a,b) myGgt = 1 #smallest possible greatest dividor for every number, will be used to recalculate ggT, as we loop through the smaller dividors anyways #this algorithm returns a detailed solution anyways, use it to check if it's true #important to make that check while a and b are stil with their initial, maybe negative values if r*a + s*b != t: return False #make sure a and b are positive #here we use abs for cleaner code, in the reworked algorithm we will need to use if-else statements a = abs(a) b = abs(b) # (b) i) if a == 0 and t == b or b == 0 and t == a: #0 can be divided by everything return True #first 2 conditions in this statement prevent ZeroDivisionError elif not a == 0 and not b == 0 and not (a % t == 0 and b % t == 0): #make sure t is really a divisor of both a and b return False for divisor in range(2, max(5,15) + 1): #1 is always a divisor, check all others to make sure t is really the greatest and is divided by all common divisors of a and b if a % divisor == 0 and b % divisor == 0: myGgt = divisor #find ggt to test if its equal to the output of the other function; we are doing this loop anyway # make sure every divisor of a and b is also a divisor of t (b) ii) if not t % divisor == 0: return False #testGGT(0,0) checks that t divides a and b, therefore causing an Exception; I added an if statement to make sure everything runs smoothly #testGGT(a,0) same as above, in case a = 0 we check if b = t #ggT(0,0) should be 0, as Infinity is not allowed in python #ggT(a,0) should be a; zero can be divided by everything without a rest return myGgt == t # algorithm taken from lecture, reworked def wholeGGT(a,b): #handle r and s for negative numbers, we use this flags to return correct r and s at the end signOfAChanged = False signOfBChanged = False #greatest divisors are always positive; negative numbers also have positive greatest common divisors if(a < 0): #if-else statements are used instead of abs to be able to set flags a *= -1 signOfAChanged = True if(b < 0): b *= -1 signOfBChanged = True a0,b0 = a,b ra,sa = 1,0 rb,sb = 0,1 while b > 0: assert (a == ra * a0 + sa * b0 and b == rb * a0 + sb * b0) q = a // b a,b = b, a - q*b ra, sa, rb, sb = rb, sb, ra - q*rb, sa - q*sb #When negative numbers are parsed to this function, we change the signs; we have to change the signs of ra and sa as well, otherwise the output won't be correct if signOfAChanged: ra *= -1 if signOfBChanged: sa *= -1 return a, ra, sa print("testGGT(10,15, ggT): ", testGGT(10,15, ggT)) print("testGGT(30,10, ggT): ", testGGT(30,10, ggT)) print("testGGT(10,15, ggT): ", testGGT(10,15, ggT)) print("testGGT(0,0, ggT): ", testGGT(0,0, ggT)) print("testGGT(5,0, ggT): ", testGGT(5,0, ggT)) print("testGGT(-5,0, ggT): ", testGGT(-5,0, ggT)) print("testGGT(-12,4, ggT): ", testGGT(-12,4, ggT)) print("testGGT(-15,-5, ggT): ", testGGT(-15,-5, ggT)) #--------------------------------- print("testGGT(10,15, wholeGGT): ", testGGT(10,15, wholeGGT)) print("testGGT(30,10, wholeGGT): ", testGGT(30,10, wholeGGT)) print("testGGT(10,15, wholeGGT): ", testGGT(10,15, wholeGGT)) print("testGGT(0,0, wholeGGT): ", testGGT(0,0, wholeGGT)) print("testGGT(5,0, wholeGGT): ", testGGT(5,0, wholeGGT)) print("testGGT(-5,0, wholeGGT): ", testGGT(-5,0, wholeGGT)) print("testGGT(-12,4, wholeGGT): ", testGGT(-12,4, wholeGGT)) print("testGGT(-15,-5, wholeGGT): ", testGGT(-15,-5, wholeGGT)) #-------------------------------- print("ggT(-12,4): ", ggT(-12,4)) print("ggT(-15,-5): ", ggT(-15,-5)) print("ggT(-5,0): ", ggT(-5,0)) #--------------------------------- print("wholeGGT(-12,4): ", wholeGGT(-12,4)) print("wholeGGT(-15,-5): ", wholeGGT(-15,-5)) print("wholeGGT(-5,0): ", wholeGGT(-5,0))
while B: S if C: T if D: U V #V is only executed, when D is true, therefore could easily be moved in the statement if (not C) | D W #W is executed, if C is false, as we have no chance of getting in the code-block with continue statement, #OR if C is true and D is true as well, so we don't get in this evil else block while B & C: #if C is false we only execute S and U, then brake, so we can reconstructor our code S if C: T V #V is executed only if C is True, otherwise we enter the else-statement and break the loop if B & (not C): #loop breaked because of C, execute S and U S U else: W #loop didn't break, execute W
import pandas as pd import numpy as np from operator import itemgetter import matplotlib.pyplot as plt import os from Classifier import Classifier import seaborn as sn import pandas as pd import matplotlib.pyplot as plt class LinearRegressionClassifier(Classifier): # B = (X^TX)^-1X^T*y # hat H = X*B^ =` X(X^TX)-1X^T @staticmethod def pseudoInverse(X): # Determining whether a matrix is invertable or not with gaus elimination # (most efficient from the naive approaches) takse n^3 time, which # makes the whole programm slower for not much precision gain # therefore we simply calculate the pseudo invsersed matrix every time # if LinearRegressionClassifier.isInvertable(X): # return np.linalg.inv(X) # calculate pseudo-inverse A+ of a matrix A (X in our case) # A+ = lim delta->0 A*(A.A* + delta.E)^(-1) where A* is the conjugate transpose # and E ist the identity matrix # In our case, we are working with real numbers, so A* = A^T # so the formula is A^T(A.A^T + delta.E)^(-1) delta = np.nextafter(np.float16(0), np.float16(1)) # as close as we can get to lim delta -> 0 pseudoInverted = X.T.dot(np.linalg.inv(X.dot(X.T) + delta * np.identity(len(X)))) return pseudoInverted @staticmethod def isInvertable(X): # apply gaus elimination # if the matrix is transformable in row-echelon form # then it is as well inverable X = np.copy(X) # don't really change given matrix m = len(X) n = len(X[0]) for k in range(min(m, n)): # Find the k-th pivot: # i_max = max(i = k ... m, abs(A[i, k])) i_max = k max_value = X[k][k] for i in range(k, m): if X[i][k] > max_value: max_value = X[i][k] i_max = i if X[i_max][k] == 0: return False for i in range(n): temp = X[k][i] X[k][i] = X[i_max][i] X[i_max][i] = temp # Do for all rows below pivot: for i in range(k+1, m): # for i = k + 1 ... m: f = X[i][k] / X[k][k] # Do for all remaining elements in current row: for j in range(k + 1, n): X[i][j] = X[i][j] - (X[k][j] * f) X[i][k] = 0 return True def __init__(self, trainSet, testSet, classA, classB): self.classA = classA self.classB = classB trainSet = self.filterDataSet(trainSet) testSet = self.filterDataSet(testSet) self.trainData = list(map(lambda x: x[1:], trainSet)) self.trainLabels = list(map(itemgetter(0), trainSet)) self.testSet = list(map(lambda x: x[1:], testSet)) self.testLabels = list(map(itemgetter(0), testSet)) self.fit() def filterDataSet(self, dataSet): return list(filter(lambda x: int(x[0]) in [self.classA, self.classB], dataSet)) def fit(self): # fill X with (1,1...,1) in it's first column to be able to get the # wished yi = B0 + B1Xi1 + B2Xi2 + ... + BnXin ones = np.ones((len(self.trainData), 1), dtype=float) X = np.append(ones, self.trainData, axis = 1) # and then used the following formula to calculate our closest possible B # which solves best our least squares regression # B = (X^TX)^(-1)X^Ty # where y = (-1, 1, -1, 1, ..., -1) (for example) is a vector # of the labels corresponding to the given data points xtxInversed = LinearRegressionClassifier.pseudoInverse(X.T.dot(X)) # normalize y, so the two possible classes are maped to -1 or 1 normalizedLabels = self.normalizeLabels(self.trainLabels) self.beta = xtxInversed.dot(X.T).dot(normalizedLabels) def predictSingle(self, X): X = np.append(np.array([1]), np.array(X), axis=0) return self.classA if (X.dot(self.beta) < 0) else self.classB def predict(self, X): return np.array(list(map(lambda x: self.predictSingle(x), X))) def test(self): print('Score for {} vs {}: {}%'.format( self.classA, self.classB, self.score(self.testSet, self.testLabels) * 100)) self.printConfusionsMatrix(self.confusion_matrix(self.testSet, self.testLabels)) def normalizeLabels(self, labels): return list(map(lambda x: -1 if int(x) == self.classA else 1, labels)) def printConfusionsMatrix(self, matrix): explicitImgPath = os.path.join(dir_path, './Plots/confusion_matrix_for_{}vs_{}.png'.format( self.classA, self.classB)) digits = [str(x) for x in range(10)]; df_cm = pd.DataFrame(matrix, index = digits, columns = digits ) plt.figure(figsize = (11,7)) heatmap = sn.heatmap(df_cm, annot=True) heatmap.set(xlabel='Klassifiziert', ylabel='Erwartet') plt.savefig(explicitImgPath, format='png') def extractDataFromLine(line): line = line.replace(' \n', '') # clear final space and new line chars return list(map(float, line.split(' '))); # map line to a list of floats def parseDataFromFile(file, dataArr): for line in file: line = line.replace(' \n', '') # clear final space and new line chars currentDigitData = extractDataFromLine(line) dataArr.append(currentDigitData) trainSet = [] testSet = [] dir_path = os.path.dirname(os.path.realpath(__file__)) explicitPathTrainData = os.path.join(dir_path, './Dataset/train') explicitPathTestData = os.path.join(dir_path, './Dataset/test') trainFile = open(explicitPathTestData, 'r') testFile = open(explicitPathTestData, 'r') parseDataFromFile(trainFile, trainSet) parseDataFromFile(testFile, testSet) LinearRegressionClassifier(trainSet, testSet, 3, 5).test() LinearRegressionClassifier(trainSet, testSet, 3, 7).test() LinearRegressionClassifier(trainSet, testSet, 3, 8).test() LinearRegressionClassifier(trainSet, testSet, 5, 7).test() LinearRegressionClassifier(trainSet, testSet, 5, 8).test() LinearRegressionClassifier(trainSet, testSet, 7, 8).test()
from tkinter import * import pandas from solver import * win = Tk() win.title("Sudoku Solver") rows = [] """Create all the entry boxes for user input""" for i in range(9): cols = [] for j in range(9): e = Entry(win, width=5) e.grid(row=i, column=j, sticky=NSEW) e.insert(END, "_") cols.append(e) rows.append(cols) def on_press(): ''' Takes all the data from entry boxes and creates a dataframe that can be solved by the solver ''' temp = [] data = [] id = 1 for row in rows: temp.append(row) for row in temp: # format the data so it can be converted to a dataframe new = [id] id += 1 for d in row: new.append(d.get()) data.append(new) df = pandas.DataFrame.from_records(data) df.columns = ["ID", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9"] # set column names df = df.set_index("ID") # print(df) solve(df) # call solve() from solver.py '''Create Labels to display the completed puzzle''' for row in range(9): for column in range(9): l = Label(win, text=df["c" + str(column + 1)][row + 1]) l.grid(row=row + 10, column=column) '''Refill the entries with _, in case the user wants to solve another puzzle''' for row in rows: for entry in row: entry.delete(0, "end") entry.insert(END, "_") Button(text='Solve', command=on_press).grid(column=4) mainloop()
#!/usr/bin/python3 missing_number = __import__('0-missing_number').missing_number array = [1, 5, 3, 2, 6] result = missing_number(array, 6) print("The missing number is {}".format(result))
def add_two(a,b): c=a+b return c num1=float(input("Please type one number:")) num2=float(input("Please type another number:")) print(num1, "+", num2,"=", add_two(num1,num2))
# A Program to aceept a integer number list from a user and search the element in that list list=eval(input("Enter the integer list: ")) print("The entered list is:",list) search=input("Enter the element to check :") for i in list: if i == int(search): print("Element is there in the list") break else: print("Element is not there in the list")
# Program to convert number from octal,binary and hexadecimal # number into decimal number--V2. s1='17' s2='1110010' s3='1c2' n=int(s1,8) print('Octal 17 =',n) n=int(s2,2) print('Binary 1110010 =',n) n=int(s3,16) print('Hexadecimal 1c2 =',n)
# A program to create an intger type array---V2 from array import * a = array('i',[10,20,30,40]) print('The array elememts are: ') for element in a: print(element)
# A program to know the effect of any() and all() function from numpy import * a=array([1,2,3,0]) b=array([0,2,3,1]) c=a>b print("Result of a>b:",c) print('Check if any one element is true:',any(c)) print('Check if all elements are true:',all(c))
# e a program which accept number from user and check whether it contains 0 # in it or not. # Input : 2395 # Output : There is no Zero # Function name : Digit() # Author : Shivaji Das # Date : 24 august 2021 def Digit(no): if no < 0: no=-(no) while no > 0: digit=int(no%10) if digit==0: no=1 break no=int(no/10) if no==1: return True else: return False def main(): num=int(input("Enter the number :")) ret=Digit(num) if ret==True: print("The Digit contains Zero") else: print("Thw Digit does not contain Zero") if __name__=="__main__": main()
# A python program thats help to know the effects of slicing operations in array from array import * a = array('i',[10,20,30,40,50,60,70]) b=a[1:4] print(b) b=a[0:] print(b) b=a[:4] print(b) b=a[:-4] print(b) b=a[-4:-1] print(b) b=a[0:7:2] print(b)
# Program to create bytearray type array and display,Modify all its elements elements=[10,20,30,40,50] #converting the list into bytearray type array x=bytearray(elements) print('Before Modification') for i in x:print(i) x[0]=100 x[2]=250 print('After Modification') for i in x:print(i)
# A Program to display prime number series max = int(input("Upto what number ?")) for num in range(2, max+1): for i in range(2,num): if(num % i) == 0: break else: print(num) break
# A program to display right angle triangle of star(*) using nested for loop for i in range(1,11): for j in range(1,i+1): print("* ",end='') print()
# A program to compare two arrays and display the boolean result from numpy import * a=array([1,2,3,0]) b=array([0,2,3,1]) c=a==b print("Result of a==b:",c) c=a>b print("Result of a>b:",c) c=a<=b print("Result of a<=b:",c)
class Edad(): def edad(self, num1): if num1 <= 0: return 'No existes' elif num1 <= 13: return 'Eres nino' elif num1<= 18: return 'Eres adolescente' elif num1<= 65: return 'Eres adulto' elif num1 <= 120: return 'Eres adulto mayor' elif num1 >= 121: return 'Eres Mumma-Ra' return ValueError #pragma: no cover """ def __init__(self): self.resultado = 0 def obtener_resutado(self): return self.resultado def edad(self, num): try: self.resultado = num if(resultado <= 0): return 'No existes' elif(resultado <= 13): return 'Eres nino' elif(resultado <= 18): return 'Eres adolescente' elif(resultado <= 65): return 'Eres adulto' elif(resultado <= 120): return 'Eres adulto mayor' elif(resultado >= 121): return 'Eres Mumma-Ra' except: return 'Datos incorrectos' """
# Ask user for calculation or exit the program while True: userInput = input("Would you like to add/sub(subtract)/mul(multiply)/div(divide)? or Type 'exit' to stop now!").lower( ) # Checking user input if userInput == "exit": print("Thank you for your checking!") break else: if userInput == "sub": print("You wrote {}, it means you chose 'subtract'.".format(userInput)) elif userInput =="div": print("You wrote {}, it means you chose 'divide'.".format(userInput)) elif userInput =="mul": print("You wrote {}, it means you chose 'multiply'.".format(userInput)) elif userInput == "add": print("You chose {}.".format(userInput)) else: print("Wrong Input") break try: num1 = float(input("What is the first number? ")) num2 = float(input("What is the second number? ")) if userInput == "add": result = num1 + num2 print( "{} + {} = {}".format(num1, num2, result)) elif userInput == "sub": result = num1 - num2 print( "{} - {} = {}".format(num1, num2, result)) elif userInput == "mul": result = num1 * num2 print( "{} * {} = {}".format(num1, num2, result)) elif userInput == "div": result = num1 / num2 print( "{} / {} = {}".format(num1, num2, result)) else: print("Sorry, but '{}' is not an option.".format(userInput)) except: print("Error: Input problem, please try again!") break
import pygame import time import random from datetime import datetime import neat import os pygame.init() class Line: def __init__(self,x,y,width,height = 3): self.x = x self.y = y self.width = width self.height = height def move(self,speed): self.x -= speed if (self.x + self.width) < 0: self.x = random.randrange(1920,5000,50) class ObstacleManager: obstacles = [] def __init__(self,OBSTACLES): self.obs_images = OBSTACLES def createObstacle(self,offset = 0,spawnPos = 2000): choice = random.randrange(0,3) offset += random.randrange(1000,1200,50) cactus = Obstacle(self.obs_images[choice],spawnPos + offset,1080 * 0.8 - self.obs_images[choice].get_height()) self.obstacles.append(cactus) def restart(self): self.obstacles = [] def main(self): if len(self.obstacles) > 0 : pass # If there are no obstacles , it creates 6 initial ones else: self.createObstacle() for x in range(0,6): self.createObstacle(offset = self.obstacles[x].get_width(),spawnPos = self.obstacles[x].x) # Returns passed variable class Obstacle: def __init__(self,img,x,y,passed = False): self.x = x self.y = y self.img = img self.spawnPos = x self.passed = passed def move(self,speed): if self.x < (0 - self.img.get_width()) : #Return true if the obstacles is out of the screen return True self.x -= speed def get_width(self): return self.img.get_width() def draw(self,screen): screen.blit(self.img,(self.x,self.y)) class Dino: ANIMATION_TIME = 30 MAX_JUMP = 600 def __init__(self,IMGS,x,y): self.img = IMGS[0] self.IMGS = IMGS self.STARTING_Y = y self.x = x self.y = y self.count = 0 self.img_count = 0 self.vel = 0 self.jumped = False def move(self): if self.jumped == True: if self.y >= self.MAX_JUMP: self.vel -= 2 else: self.vel += 2 self.y = self.y + self.vel if self.y >= self.STARTING_Y: self.jumped = False self.y = self.STARTING_Y self.vel = 0 #Jump ended def jump(self): if self.jumped == False: self.vel = -7 self.jumped = True def display(self,screen): self.img_count += 1 if self.img_count < self.ANIMATION_TIME: self.img = self.IMGS[1] elif self.img_count < self.ANIMATION_TIME * 2: self.img = self.IMGS[2] elif self.img_count < self.ANIMATION_TIME * 3: self.img_count = 0 screen.blit(self.img,(self.x,self.y)) #Fonts default_font = pygame.font.Font('freesansbold.ttf', 50) #Screen variables HEIGHT = 1080 WIDTH = 1920 #Screen settings screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) pygame.display.set_caption("Tigan de atac") #White Background Color white = (255,255,255) black = (0,0,0) screen.fill(white) SPEED = 8 #Images IMGS = [pygame.transform.scale(pygame.image.load('./data/dino0000.png'), (96, 112)),pygame.transform.scale(pygame.image.load('./data/dinorun0000.png'), (96, 112)),pygame.transform.scale(pygame.image.load('./data/dinorun0001.png'), (96, 112))] CACTUSES = [pygame.image.load('./data/cactusSmall0000.png'),pygame.image.load('./data/cactusBig0000.png'),pygame.image.load('./data/cactusSmallMany0000.png')] # GAME FUNCTIONS def restart(ObstacleManager): ObstacleManager.restart() def drawRoad(screen): """ return : Y position of the road """ pygame.draw.rect(screen,black,(0,HEIGHT * 0.8,WIDTH,3)) return HEIGHT * 0.8 def draw_lines(screen,lines): if len(lines) > 0: for line in lines: line.move(SPEED) pygame.draw.rect(screen,black,(line.x,line.y,line.width,line.height)) else: line_width = random.randrange(5,100) line_y = random.randrange(HEIGHT * 0.8,HEIGHT) line_x = random.randrange(1920,3000) NewLine = Line(line_x,line_y,line_width) lines.append(NewLine) #Generate lines for i in range(0,10): line_width = random.randrange(5,100) line_y = random.randrange(HEIGHT * 0.8 + 30,HEIGHT - 30,20) line_x = random.randrange(1920,5000,50) NewLine = Line(line_x,line_y,line_width) lines.append(NewLine) def display_score(score): text = default_font.render("Score: " + "{:1.0f}".format(score), True, black) screen.blit(text,(50,50)) # END OF GAME FUNCTIONS def main(genomes,config): global screen,gen,SPEED SPEED = 8 nets = [] ge = [] dinos = [] for _, g in genomes: net = neat.nn.FeedForwardNetwork.create(g,config) nets.append(net) dinos.append(Dino(IMGS,500,HEIGHT * 0.8 - IMGS[1].get_height())) g.fitness = 0 ge.append(g) #Game variables SCORE = 0 passed = False lines = [] #Clock and while loop running = True clock = pygame.time.Clock() #Instances Manager = ObstacleManager(CACTUSES) Manager.restart() obs_ind = 0 while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: if not passed: dino.jump() if passed: #Reset everything basically restart(Manager) passed = False SPEED = 8 SCORE = 0 lines = [] Manager.main() if len(dinos) > 0: pass else: run = False break for x,dino in enumerate(dinos): dino.move() dino.display(screen) ge[x].fitness += 0.05 output = nets[x].activate((dino.y,abs(Manager.obstacles[obs_ind].x - dino.x ),abs(Manager.obstacles[obs_ind].img.get_width()),abs(Manager.obstacles[obs_ind].img.get_height()),abs(Manager.obstacles[obs_ind + 1].x - Manager.obstacles[obs_ind].x),SPEED)) if output[0] > 0.7: dino.jump() SPEED += 0.0005 SCORE += 0.1 display_score(SCORE) #Draw background stuff draw_lines(screen,lines) drawRoad(screen) #Draw Dino #Ostacles index = 0 for obstacle in Manager.obstacles: hasPassed = obstacle.move(SPEED) obstacle.draw(screen) for x,dino in enumerate(dinos): if (dino.x + dino.img.get_width()) >= obstacle.x and dino.x < (obstacle.x + obstacle.get_width()): #Detects if objects passed on x axis if (dino.y + dino.img.get_height()) > obstacle.y : #If the object also passed on Y axis , it crashed and sets passed to true so the whole code can run ge[x].fitness -= 10 dinos.pop(x) nets.pop(x) ge.pop(x) if dino.x > obstacle.x + 10 and obstacle.passed == False: for g in ge: g.fitness += 5 obs_ind += 1 print(obs_ind) print("I passed a obstacle once!") obstacle.passed = True #Object has passed if hasPassed == True: Manager.createObstacle(offset = Manager.obstacles[-1].get_width(),spawnPos = Manager.obstacles[-1].x) Manager.obstacles.pop(index) obs_ind -= 1 index += 1 clock.tick(60) pygame.display.update() screen.fill(white) # NEAT FUNCTIONS def run(config_path): config = neat.config.Config(neat.DefaultGenome,neat.DefaultReproduction,neat.DefaultSpeciesSet,neat.DefaultStagnation,config_path) p = neat.Population(config) p.add_reporter(neat.StdOutReporter(True)) stats = neat.StatisticsReporter() p.add_reporter(stats) winner = p.run(main,100) # END OF NEAT FUNCTIONS if __name__ == "__main__": local_dir = os.path.dirname(__file__) config_path = os.path.join(local_dir,"config.txt") run(config_path)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Script : listas.py Autor : Julián Camilo Morales Agudelo <juliancmorales10@gmail.com> Versión : 1.0 Modificado : 2021-01-12 Documentación : Dada una lista se realizan varias operaciones de manipulacion. ''' # Dada un lista lista = [12, 23, 5, 29, 92, 64] print('') print(lista) # Eliminar el ultimo numero y añadir al principio de esta. lista.insert(0, lista.pop()) print(lista) # Mover el segndo elemento a la ultima posicion lista.append(lista.pop(1)) print(lista) # Añadir el 14 al inicio de la lista. lista.insert(0, 14) print(lista) # Suma todos los elementos de la lista y los añade al final lista.append(sum(lista)) print(lista) # Combina la lista actual con la siguiente [4,11,32] lista = lista + [4, 11, 32] print(lista) # Eliminar los impares de la lista. lista = [par for par in lista if par % 2 == 0] print(lista) # Ordena la lista lista.sort() print(lista)
#!/usr/bin/python # Import Library import sys # Create the StringText Class class StringText(object): # Constructor def __init__(self, content): self.content = content self.length = len(str(content)) # This is the maximum length that can be exported from the outliner without wrapping self.maxLength = 59 # Method to check if string is too long def isTooLong(self): if self.length > self.maxLength: return(True) else: return(False) # Method to get absolute character difference def charDiff(self): return(abs(self.maxLength-self.length)) # Method to determine if character difference is only one (for pluralization) def oneCharOverUnder(self): if StringText.charDiff(self) == 1: return(True) else: return(False) # * This is where the program is actually run * # Capture string to test strStringToTest = input("Please input string to test: ") # Create instance of the class from the command line parameter myString = StringText(strStringToTest) # Print out the string and its length print(f'The length of the string "{myString.content}" is {myString.length}. ') # Case when the string is too long if myString.isTooLong() == True: print(f'The string is too long. Please shorten by {myString.charDiff()} character', end = '') # Checking for a single character difference for correct pluralization if myString.oneCharOverUnder() == False: print('s.') else: print('.') # Case when the string is not too long else: print(f'The string is not too long, with {myString.charDiff()} character', end = '') # Checking for a single character difference for correct pluralization if myString.oneCharOverUnder() == False: print('s', end = '') print(' to spare.')
from collections import deque import sys def read_input(text, line): adjacent = dict() dic = [[] for i in range(10)] i = line while True: string = text[i].strip() i += 1 if string == '*': break p = len(string) adjacent[string] = [] for word in dic[p-1]: different = 0 for j in range(p): if word[j] != string[j]: different += 1 if different > 1: break if different == 1: adjacent[string].append(word) adjacent[word].append(string) dic[p-1].append(string) query = [] while text[i] != '\n': query.append((text[i].strip().split())) i += 1 if i >= len(text): break return adjacent, query, i def bfs(adjacent, u, w): q = deque([u]) visited = {} for key in adjacent: visited[key] = -1 visited[u] = 0 while q: u = q.popleft() if u == w: return visited[u] for v in adjacent[u]: if visited[v] == -1: q.append(v) visited[v] = visited[u] + 1 if __name__ == "__main__": text = sys.stdin.readlines() line = 2 for j in range(int(text[0])): if 0 < j < len(text): print() adjacent, query, i = read_input(text, line) line = i for (u, w) in query: print(u, w, bfs(adjacent, u, w))
import utils.helper as helper # # Contains methods used to load data from files stored on the disk # # Creates a mapping between the sequence of characters and all anagrams for that sequence # ex: <'acr', ['car', 'arc']> def load_dictionary(filename): file = open(filename) anagrams = {} for word in file: word = word.strip() # sorted() returns a list of sorted characters hence join() sorted_word = ''.join(sorted(word)) if sorted_word in anagrams: anagrams[sorted_word].append(word) else: anagrams[sorted_word] = [word] file.close() return anagrams # Returns the state of the board as a 2D array and the available tiles def load_current_game_state_and_validate_input(filename): tiles = '' board = [[0 for i in range(15)] for j in range(15)] x = 0 file = open(filename) for line in file: line = line.strip() # rack line if x == 15: tiles = line helper.validate_rack(tiles) break # too many lines elif x > 16: raise Exception('Invalid size of the board') y = 0 # first 15 lines for c in line: helper.validate_size_of_board(line) helper.validate_characters(c) board[x][y] = c y += 1 x += 1 game_state = { "board": board, "tiles": tiles } return game_state
import math import random import matplotlib.pyplot as plt """ A unit of a neural network. """ class NNUnit: def __init__(self, activation, inputs = None, weights = None): self.activation = activation self.inputs = inputs or [] self.weights = weights or [] self.value = None """ Creates a neural network. """ def createNN(input_layer_size, hidden_layer_sizes, output_layer_size, activation): layer_sizes = [input_layer_size] + hidden_layer_sizes + [output_layer_size] network = [[NNUnit(activation) for _ in range(s)] for s in layer_sizes] dummy_node = NNUnit(activation) dummy_node.value = 1.0 # create weighted links for layer_idx in range(1, len(layer_sizes)): for node in network[layer_idx]: node.inputs.append(dummy_node) node.weights.append(0.0) for input_node in network[layer_idx - 1]: node.inputs.append(input_node) node.weights.append(0.0) return network """ Sigmoid activation function """ def sigmoid(z): return float(1.0/(1.0 + math.exp(-1.0*float(z)))) """ Sigmoid activation function derivative """ def sigmoid_deriv(z): return sigmoid(z)*(1-sigmoid(z)) print(sigmoid_deriv(0)) """ [findInJ(n,idx)] is the InJ value for node [n] of layer [idx]. """ def findInJ(n,idx): total = 0 for idx,w in enumerate(n.weights): input_n = n.inputs[idx] if idx == 1: total += w*(input_n.value) else: total += w*(input_n.activation(input_n.value)) return total """ [back_prop_learning(examples, network, epochs, learning_rate, deriv = sigmoid_deriv)] is the trained network and mean squared errors resulting from backward propograted learning performed on neural network [network] with [examples], [learning_rate] and derivation function [deriv] over [epochs] runs for each individual example. Returns: network,errors """ def back_prop_learning(examples, network, epochs, learning_rate, deriv = sigmoid_deriv): """ [findDeltaI(n, deltas)] is the delta value for node [n] according to existing deltavalues [deltas] """ def findDeltaI(n, deltas): total = 0 for d_node in deltas: for i in range(len(d_node.inputs)): if d_node.inputs[i] == n: total += d_node.weights[i]*deltas[d_node] return deriv(n.value)*total """ [mse(output_layer,example)] is the mean squared error according to example output [example] and output layer [output_layer.] """ def mse(output_layer, example): total = 0 for idx,e in enumerate(example): n = output_layer[idx] total += (e-n.activation(n.value))**2 return float((1.0/len(example))*total) # Randomly initialize weights for l in network: for n in l: n.weights = [random.uniform(-0.5,0.5) for i in range(len(n.weights))] errors = [] for t in range(epochs): epoch_error = 0 for e in examples: deltas = {} inputs = e[0] outputs = e[1] for idx,n in enumerate(network[0]): # set values for input layer n.value = inputs[idx] for l_idx,layer in enumerate(network[1:]): # find inj values for n in layer: n.value = findInJ(n,l_idx) # Propogate backwards for idx,rev_layer in enumerate(network[::-1]): if not deltas: # output layer for idx,n in enumerate(rev_layer): deltas[n] = deriv(n.value)*(outputs[idx]-(n.activation(n.value))) else: # L-1 to 1 for n in rev_layer: delta = findDeltaI(n,deltas) deltas[n] = delta # Update weights for idx, layer in enumerate(network[1:]): for n in layer: for i_idx, i in enumerate(n.inputs): n.weights[i_idx] = n.weights[i_idx]+(learning_rate*i.activation(i.value)*deltas[n]) epoch_error += mse(network[-1],outputs) errors.append(epoch_error) return network,errors dataset = [([0,0],[0,0]), ([0,1],[0,1]), ([1,0],[0,1]), ([1,1],[1,0])] network = createNN(2, [2,2], 2, sigmoid) num_epochs = 10000 trained_network, total_errs = back_prop_learning(dataset, network, num_epochs, 0.25) _, axis = plt.subplots() epochs = [e for e in range(0, num_epochs, 1)] axis.plot(epochs, total_errs) axis.set(xlabel = 'Number of Epochs', ylabel = 'Total Error on Training Set') axis.grid() plt.show() """ [predict(network,exmaple)] is a list of outputted prediction values from propogating the inputs of [example] through the neural netwrok [network]. """ def predict(network, example): for idx,n in enumerate(network[0]): n.value = example[idx] for l_idx,layer in enumerate(network[1:]): for n in layer: n.value = findInJ(n,l_idx) return [n.activation(n.value) for n in network[-1]] test_set = [[0,0], [0,1], [1,0], [1,1]] correct_out = [[0,0], [0,1], [0,1], [1,0]] for t in range(len(test_set)): print('Example =', test_set[t]) preds = predict(trained_network, test_set[t]) print('Prediction =', preds) print('Actual =', correct_out[t]) devs = [abs(preds[p] - correct_out[t][p]) for p in range(len(preds))] print('Deviations =', devs) print() data_set = [([p,q,r,s],[int(p and not r), int(q <= p)]) for p in [0,1] for q in [0,1] for r in [0,1] for s in [0,1]] random.shuffle(data_set) training_set = data_set[0:12] network = createNN(4, [8,8], 2, sigmoid) num_epochs = 5000 trained_network, total_errs = back_prop_learning(training_set, network, num_epochs, 0.1) _, axis = plt.subplots() epochs = [e for e in range(0, num_epochs, 1)] axis.plot(epochs, total_errs) axis.set(xlabel = 'Number of Epochs', ylabel = 'Total Error on Training Set') axis.grid() plt.show() test_set = [x for (x,y) in data_set[12:]] correct_out = [y for (x,y) in data_set[12:]] num_misses = 0 for t in range(len(test_set)): preds = predict(trained_network, test_set[t]) devs = [abs(preds[p] - correct_out[t][p]) for p in range(len(preds))] for d in devs: if d >= 0.1: num_misses += 1 print('Error Rate:', num_misses / 8.0 * 100.0, '%') # Alternative Hyperparameter / Activation Functions def sin(z): return math.sin(z) def sin_deriv(z): return math.cos(z) def tanh(z): return (math.exp(z)-math.exp(-1.0*z))/(math.exp(z)+math.exp(-1.0*z)) def tanh_deriv(z): return 1 - (tanh(z)**2) def elu(z, alpha = 0.01): return 0.0*(math.exp(z)-1) if z <= 0 else z def elu_deriv(z, alpha = 0.01): return alpha*math.exp(z) if z <= 0 else z def relu(z): # subgradient return z if z > 0 else 0 def relu_deriv(z): # subgradient return 1 if z > 0 else 0 training_set = [([0,0],[0,0]), ([0,1],[0,1]), ([1,0],[0,1]), ([1,1],[1,0])] learning_rate = 0.25 num_epochs = 10000 funs = [sigmoid, sin, tanh, elu, relu] drvs = [sigmoid_deriv, sin_deriv, tanh_deriv, elu_deriv, relu_deriv] errs = [] r = random.getstate() for f in range(len(funs)): network = createNN(2, [2,2], 2, funs[f]) random.setstate(r) _, total_errs = back_prop_learning(training_set, network, num_epochs, learning_rate, deriv = drvs[f]) errs.append(total_errs) fig, axs = plt.subplots(5, 1, sharex = True, figsize = (7, 7)) fig.subplots_adjust(hspace = 0.25) t = [i for i in range(0, num_epochs, 1)] axs[0].plot(t, errs[0], color = 'b', label = 'sigmoid') axs[1].plot(t, errs[1], color = 'g', label = 'sin') axs[2].plot(t, errs[2], color = 'r', label = 'tanh') axs[3].plot(t, errs[3], color = 'y', label = 'elu') axs[4].plot(t, errs[4], color = 'm', label = 'relu') axs[0].set(title = 'Total Error Over Time') axs[4].set(xlabel = 'Epoch') for i in range(len(axs)): axs[i].legend(loc = 'upper right') plt.show() """ [check_alphas(examples, network, epochs, min_alpha, max_alpha, step_size, deriv = sigmoid_deriv)] is a list of errors corresponding to backward propogation learning on the given [network] and [exmaples] with the learning rate values inclusively between [min_alpha] and [max_alpha] with step size [step_size]. The error in each entry is the Mean Squared Error calculated in the final epoch, or, in other words, the MSE of epoch [epochs]. """ def check_alphas(examples, network, epochs, min_alpha, max_alpha, step_size, deriv = sigmoid_deriv): alphas=[] a = min_alpha while a <= max_alpha: n,error = back_prop_learning(examples, network, epochs, a, deriv) alphas.append(error[-1]) a += step_size return alphas dataset = [([0,0],[0,0]), ([0,1],[0,1]), ([1,0],[0,1]), ([1,1],[1,0])] network = createNN(2, [2,2], 2, sigmoid) num_epochs = 5000 mina = -0.3 maxa = 0.3 ss = 0.05 errs = check_alphas(dataset, network, num_epochs, mina, maxa, ss, sigmoid_deriv) _, axis = plt.subplots() alphas = [] while mina <= maxa: alphas.append(mina) mina += ss axis.plot(alphas, errs) axis.set(xlabel = 'Learning Rates', ylabel = 'Total Error at Final Epoch') axis.grid() plt.show()
from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ # 创建一个BeautifulSoup对象 soup = BeautifulSoup(html_doc) print(soup.prettify()) soup.title type(soup.title) dir(soup.title) soup.title.text #取出第一个a标签的所有属性 soup.a.attrs # 取出a标签的href属性 soup.a.attrs['href'] #判断是否有class属性 soup.a.has_attr('class') #取出第一个p标签下的所有的子节点 soup.p.children # 取出来的结果是一个迭代器,所以用list转换一下 list(soup.p.children) list(soup.p.children)[0] list(soup.p.children)[0].text # 取出本页面内所有的链接 for a in soup.find_all('a'): print(a.attrs['href']) # 取出id=link3的那个节点 soup.find(id='link3') # 取出页面内所有的文本 soup.get_text() # 支持CSS选择器 # 查找类名为story的节点 soup.select('.story') # 查找id=link1的节点 soup.select('#link1') soup_lxml = BeautifulSoup(html_doc, 'lxml') print('##' * 10, soup_lxml.a)
"""A poetry analyzer.""" import tkinter as tk import tkinter.ttk from tkinter import filedialog from tkinter import scrolledtext import poetry_functions import poetry_reader DICTIONARY_FILENAME = 'dictionary.txt' POETRY_FORMS_FILENAME = 'poetry_forms.txt' WELCOME_MESSAGE = '''\ Welcome to the poetry analyzer. Please select a poetry form and open a poetry file, then click the Analyze Poem button. Feel free to change this text in poetry.py. If you break it, you can always download it again. :-)''' # ************************ # Scrollable Frame Class # ************************ class ScrollFrame(tk.Frame): """A GUI frame with a scrollbar""" # Credit for this class is given to # https://gist.github.com/mp035/9f2027c3ef9172264532fcd6262f3b01 # with some modifications def __init__(self, parent: tk.Frame) -> None: """Initialize a frame with a scrollbar""" super().__init__(parent) # create a frame (self) # A Canvas for the window contents, and a viewport frame # to hold the widgets. self.canvas = tk.Canvas(self, borderwidth=0) self.view_port = tk.Frame(self.canvas) # Create scrollbars and add them to the canvas. self.vsb = tk.Scrollbar( self, orient="vertical", command=self.canvas.yview) self.hsb = tk.Scrollbar( self, orient="horizontal", command=self.canvas.xview) self.canvas.configure(yscrollcommand=self.vsb.set, xscrollcommand=self.hsb.set) self.vsb.pack(side="right", fill="y") # pack scrollbar to right self.hsb.pack(side="bottom", fill="x") # pack scrollbar to bottom # add view port frame to canvas self.canvas.pack(side="left", fill="both", expand=True) self.canvas_window = self.canvas.create_window( (4, 4), window=self.view_port, anchor="nw", tags="self.viewPort") # bind events for whenever the size of the viewPort frame changes. self.view_port.bind("<Configure>", self.on_frame_configure) self.canvas.bind("<Configure>", self.on_canvas_configure) # perform an initial stretch on render, otherwise the scroll region has # a tiny border until the first resize self.on_frame_configure(None) def on_frame_configure(self, event: tk.Event) -> None: """Reset the scroll region to encompass the inner frame""" self.canvas.configure(scrollregion=self.canvas.bbox("all")) def on_canvas_configure(self, event: tk.Event) -> None: """Reset the canvas window to encompass inner frame when required""" self.canvas.configure(scrollregion=self.canvas.bbox("all")) class PoetryApp(tk.Frame): """A GUI for the poetry application.""" def __init__(self, poetry_root: tk.Frame) -> None: """Initialize the Poetry App along with its gadgets""" # Read the dictionary and poetry forms files self.word_pronunciations = poetry_reader.read_pronouncing_dictionary( open(DICTIONARY_FILENAME, 'r', encoding="utf-8")) self.poetry_patterns = poetry_reader.read_poetry_form_descriptions( open(POETRY_FORMS_FILENAME, 'r', encoding="utf-8")) # Build the user interface poetry_root.title("Pure Poetry") screen_width = poetry_root.winfo_screenwidth() screen_height = poetry_root.winfo_screenheight() width, height = screen_width * 0.5, screen_height * 0.5 self.width, self.height = width, height # calculate x and y coordinates for the Tk root window x = (screen_width / 2) - (width / 2) y = (screen_height / 2) - (height / 2) self.annotation_height = int(self.height / 50) # set the dimensions of the screen and where it is placed poetry_root.geometry('%dx%d+%d+%d' % (width, height, x, y)) self.master = poetry_root tk.Frame.__init__(self, poetry_root) self.scroll_frame = ScrollFrame(self) self.scroll_frame.width = width self.scroll_frame.height = height self.create_screen_components() # pack scrollFrame itself self.scroll_frame.pack( side="top", fill="both", expand=True, padx=(5, 0), pady=(5, 0)) def create_screen_components(self) -> None: """Create the components of the app screen including text, text boxes, buttons, and so on""" # Put things in rows to organize gadgets. row_number = 0 # The greeting at the top of the window. welcome_label = tk.Label( self.scroll_frame.view_port, text=WELCOME_MESSAGE, justify=tk.LEFT, font="Arial 14") welcome_label.grid( row=row_number, column=0, columnspan=1, sticky=tk.W) row_number += 1 # The row of text fields containing the poetry analysis. self.build_poetry_analysis_frame(row_number) row_number += 1 # The row of buttons along the bottom. self.build_bottom_button_frame(row_number) self.scroll_frame.columnconfigure(0, weight=0) def build_poetry_analysis_frame(self, row_number: int) -> None: """Create and add a frame for a poem/syllable count/rhyme scheme frame, a poetry form frame, and a pronunciation frame. """ poetry_analysis_frame = tk.Frame(self.scroll_frame.view_port) poetry_analysis_frame.grid( row=row_number, column=0, columnspan=1, pady=10, sticky=tk.W) col_number = 0 self.build_poem_frame(poetry_analysis_frame, col_number) col_number += 1 self.build_poetry_form_frame(poetry_analysis_frame, col_number) col_number += 1 self.build_pronunciation_frame(poetry_analysis_frame, col_number) def build_pronunciation_frame( self, poetry_analysis_frame: tk.Frame, col_number: int) -> None: """Built the frame for the pronunciation. """ pronunciation_frame = tk.Frame( poetry_analysis_frame, borderwidth=1, relief=tk.GROOVE) pronunciation_frame.grid( row=0, column=col_number, columnspan=1, pady=10, sticky=tk.W) # Pronunciation header pronouncing_header = tk.Label( pronunciation_frame, text='Pronunciation') pronouncing_header.grid( row=0, column=0, columnspan=1, sticky=tk.W + tk.E + tk.N + tk.S) # Pronunciation self.pronunciation_text = tk.scrolledtext.ScrolledText( pronunciation_frame, width=int(self.width / 15), height=self.annotation_height) self.pronunciation_text.insert('1.0', 'Poem pronunciation') self.pronunciation_text.config(state=tk.DISABLED) self.pronunciation_text.grid( row=1, column=0, sticky=tk.W, columnspan=1, rowspan=1) def build_poem_frame( self, poetry_analysis_frame: tk.Frame, col_number: int) -> None: """Build the frame containing the poem.""" poem_frame = tk.Frame( poetry_analysis_frame, borderwidth=1, relief=tk.GROOVE) poem_frame.grid(row=0, column=col_number, padx=10, pady=10, sticky=tk.W) row_number = 0 self.add_poem_header(poem_frame, row_number) row_number += 1 col_number = 0 self.add_poem_text(col_number, poem_frame, row_number) col_number += 1 self.add_rhyme_scheme(col_number, poem_frame, row_number) col_number += 1 self.add_num_syllables(col_number, poem_frame, row_number) col_number += 1 def add_num_syllables( self, col_number: int, poem_frame: tk.Frame, row_number: int) -> None: """Add template number of syllables text to row row_number and column col_number of the poem_frame.""" self.num_syllables_text = tk.scrolledtext.ScrolledText( poem_frame, width=3, height=self.annotation_height) self.num_syllables_text.insert('1.0', '# Syllables') self.num_syllables_text.config(state=tk.DISABLED) self.num_syllables_text.grid( row=row_number, column=col_number, sticky=tk.W, columnspan=1, rowspan=1) def add_rhyme_scheme( self, col_number: int, poem_frame: tk.Frame, row_number: int) -> None: """Add template rhyme scheme text to row row_number and column col_number of the poem_frame.""" self.rhyme_scheme_text = tk.scrolledtext.ScrolledText( poem_frame, width=3, height=self.annotation_height) self.rhyme_scheme_text.insert('1.0', 'Rhyme scheme') self.rhyme_scheme_text.config(state=tk.DISABLED) self.rhyme_scheme_text.grid( row=row_number, column=col_number, sticky=tk.W, columnspan=1, rowspan=1) def add_poem_text( self, col_number: int, poem_frame: tk.Frame, row_number: int) -> None: """Add template poem text to row row_number and column col_number of the poem_frame.""" self.poem_text = tk.scrolledtext.ScrolledText( poem_frame, width=int(self.width / 30), height=self.annotation_height) self.poem_text.insert('1.0', 'Poem') self.poem_text.grid( row=row_number, column=col_number, sticky=tk.W, columnspan=1, rowspan=1) def add_poem_header(self, poem_frame: tk.Frame, row_number: int) -> None: """Add the poem header to row number row_number of poem_frame.""" poem_header = tk.Label(poem_frame, text='Poem') poem_header.grid( row=row_number, column=0, columnspan=3, sticky=tk.W + tk.E + tk.N + tk.S) def build_poetry_form_frame( self, poetry_analysis_frame: tk.Frame, col_number: int) -> None: """Build the frame containing the poem, poetry form, and pronunciation subframes.""" # The poetry form rhyme scheme and number of syllables. poetry_form_frame = tk.Frame( poetry_analysis_frame, borderwidth=1, relief=tk.GROOVE) poetry_form_frame.grid( row=0, column=col_number, padx=10, pady=10, sticky=tk.W) row_number = 0 col_number = 0 # Poetry form header poetry_form_header = tk.Label(poetry_form_frame, text='Poetry Form') poetry_form_header.grid( row=row_number, column=col_number, columnspan=2, sticky=tk.W + tk.E + tk.N + tk.S) row_number += 1 col_number = 0 # Poetry form rhyme scheme self.form_rhyme_scheme_text = tk.scrolledtext.ScrolledText( poetry_form_frame, width=3, height=self.annotation_height) self.form_rhyme_scheme_text.insert('1.0', 'Rhyme scheme') self.form_rhyme_scheme_text.config(state=tk.DISABLED) self.form_rhyme_scheme_text.grid(row=row_number, column=col_number, sticky=tk.W, columnspan=1, rowspan=1) col_number += 1 # Poetry form number of syllables self.form_num_syllables_text = tk.scrolledtext.ScrolledText( poetry_form_frame, width=3, height=self.annotation_height) self.form_num_syllables_text.insert('1.0', '# Syllables') self.form_num_syllables_text.config(state=tk.DISABLED) self.form_num_syllables_text.grid( row=row_number, column=col_number, sticky=tk.W, columnspan=1, rowspan=1) return col_number, row_number def build_bottom_button_frame(self, row_number: int) -> None: """Build the bottom frame of buttons.""" # A frame for the buttons and menus button_frame = tk.Frame(self.scroll_frame.view_port) button_frame.grid( row=row_number, column=0, columnspan=6, padx=10, pady=10, sticky=tk.W) row_number = 0 col_number = 0 self.add_open_poem_button(button_frame, col_number) col_number += 1 self.add_analyze_poem_button(button_frame, col_number) col_number += 1 self.add_form_selector_label(button_frame, col_number, row_number) col_number += 1 self.add_form_dropdown_menu(button_frame, col_number, row_number) col_number += 1 # Quit quit_btn = tk.Button( button_frame, text="QUIT", fg="red", width=int(self.width / 80), height=2, command=lambda: self.master.destroy()) quit_btn.grid(row=0, column=col_number, padx=10, pady=2, sticky=tk.W) def add_form_dropdown_menu( self, button_frame: tk.Frame, col_number: int, row_number: int) -> None: """Create and add a dropdown menu of poetry forms to row row_number and column col_number of the button_frame.""" self.poetry_form_var = tk.StringVar(button_frame) self.poetry_form_var.set("") # default value self.poetry_pattern_menu = tk.ttk.Combobox( button_frame, state="readonly", textvariable=self.poetry_form_var, values=list(self.poetry_patterns.keys())) self.poetry_pattern_menu.grid( row=row_number, column=col_number, padx=10, pady=2, sticky=tk.W) self.poetry_pattern_menu.bind( '<<ComboboxSelected>>', self.update_poetry_form) def add_form_selector_label( self, button_frame: tk.Frame, col_number: int, row_number: int) -> None: """Create and add open poem file button to row row_number and column col_number of the button_frame.""" form_selector_lbl = tk.Label(button_frame, text='Select poetry form:') form_selector_lbl.grid( row=row_number, column=col_number, padx=10, pady=2, sticky=tk.W) def add_analyze_poem_button( self, button_frame: tk.Frame, col_number: int) -> None: """Create and add open poem file button to column col_number of the button_frame.""" analyze_btn = tk.Button( button_frame, text="Analyze Poem", width=int(self.width / 80), height=2, command=lambda: self.analyze_poem()) analyze_btn.grid( row=0, column=col_number, columnspan=1, padx=10, pady=2, sticky=tk.E) def add_open_poem_button( self, button_frame: tk.Frame, col_number: int) -> None: """Create and add open poem file button to column col_number of the button_frame.""" open_poem_btn = tk.Button( button_frame, text="Open Poem File", width=int(self.width / 80), height=2, command=lambda: self.choose_poem_file()) open_poem_btn.grid( row=0, column=col_number, columnspan=1, padx=10, pady=2, sticky=tk.E) def update_poetry_form(self, event: tk.Event) -> None: """React to a new poetry form being chosen: update self.form_rhyme_scheme_text and self.form_num_syllables_text. """ poetry_form = self.poetry_form_var.get() form_num_syllables = ( str(i) for i in self.poetry_patterns[poetry_form][0]) form_rhyme_scheme = ( str(i) for i in self.poetry_patterns[poetry_form][1]) syllables = '\n'.join(form_num_syllables) scheme = '\n'.join(form_rhyme_scheme) self.update_box(self.form_rhyme_scheme_text, scheme) self.update_box(self.form_num_syllables_text, syllables) def choose_poem_file(self) -> None: """Prompt for a text file containing a poem, read it, clean it, and display it in self.poem_text. """ poem_filename = filedialog.askopenfilename( initialdir=".", title="Select poetry file", filetypes=(("text files", "*.txt"), ("all files", "*.*"))) # poem_filename = get_valid_filename("Enter a poem filename: ") poem_file = open(poem_filename) poem = poetry_reader.read_and_trim_whitespace(poem_file) self.update_box(self.poem_text, poem) def analyze_poem(self) -> None: """Analyze the poem in self.poem_text (which has already been cleaned!) and display the number of syllables per line and the rhyme scheme. Also display the phonetic representation. """ poem = self.poem_text.get('1.0', tk.END) # Tokenize the words by cleaning them and extracting the phonemes. poem_lines = poetry_functions.clean_poem(poem) poem_pronunciation = poetry_functions.extract_phonemes( poem_lines, self.word_pronunciations) # Show the pronunciation. poem_pronunciation_str = poetry_functions.phonemes_to_str( poem_pronunciation) self.update_box(self.pronunciation_text, poem_pronunciation_str) # Show the rhyme scheme. poem_scheme = poetry_functions.get_rhyme_scheme(poem_pronunciation) self.update_box(self.rhyme_scheme_text, '\n'.join(poem_scheme)) # Show the number of syllables for each line. poem_syllables = poetry_functions.get_num_syllables(poem_pronunciation) # We nearly made this next one a required function in # poetry_functions.py, but wanted to show you this cool trick. :-) poem_syllables_text = '\n'.join((str(i) for i in poem_syllables)) self.update_box(self.num_syllables_text, poem_syllables_text) def update_box(self, box: scrolledtext.ScrolledText, message: str) -> None: """Clear the output box in the app and put message inside it.""" box.config(state=tk.NORMAL) box.delete('1.0', tk.END) box.insert('1.0', message) box.config(state=tk.DISABLED) if __name__ == '__main__': root = tk.Tk() PoetryApp(root).pack(side="top", fill="both", expand=True) root.mainloop()
"""Amazing Banking Corporation functions""" from typing import List, Tuple, Dict, TextIO # Constants # client_to_accounts value indexing BALANCES = 0 INTEREST_RATES = 1 # transaction codes WITHDRAW_CODE = -1 DEPOSIT_CODE = 1 LOAN_INTEREST_RATE = 2.2 # percent ## ------------ HELPER FUNCTIONS GIVEN BELOW ----------- # do not modify def display_client_accounts(client_to_accounts: Dict, client: Tuple) -> None: """ Display the indicated client's account balances in a human-friendly format, using the client_to_account dictionary. The first account is a chequing account, followed by subsequent savings account(s). A loan account, if present, is signified as the last account if it has a negative balance. """ i = 0 for account in client_to_accounts[client][BALANCES]: if i == 0: # the first account is always a chequing account print("Chequing Account") elif account > 0: print("Savings Account {}".format(i)) else: print("Loan Account") print("$ {:.2f}".format(account)) i += 1 def get_fv(present_value: float, r: float, n: int) -> float: """ Return the future value calculated using the given present value (pv) growing with rate of return (interest rate) r, compounded annually, for a total of n years. r is given as a percentage value. """ return present_value * (1 + r / 100) ** n def get_sd(x: List[float]) -> float: """ Return the standard deviation of the values in the list x. """ n = len(x) x_bar = (sum(x)) / n sd = 0 for x_i in x: sd += (x_i - x_bar) ** 2 return (sd / n) ** 0.5 ### ----------- END OF PROVIDED HELPER FUNCTIONS -------------- def load_financial_data(file: TextIO) -> \ Dict[Tuple[str, int], List[List[float]]]: """ Return a client to accounts dictionary buy input file. """ diction, index = {}, 0 acc = file.readlines() for line in acc: if acc[index].strip() == '' or index == 0: if acc[index].strip() == '': index += 1 key_1 = line.strip() index += 1 key_2 = int(float(acc[index].strip().replace(' ', ''))) index += 1 key, diction[key] = (key_1, key_2), [[], []] elif line.strip() == '' or line.strip()[0] == 'C' \ or line.strip()[0] == 'S': index += 1 elif line.strip()[0] == 'B': diction[key][0].append(float(acc[index].strip().split()[-1])) index += 1 elif line.strip()[0] == 'I': diction[key][1].append(float(acc[index].strip().split()[-1])) index += 1 return diction def get_num_clients(client_to_accounts: Dict[Tuple[str, int], List[List[float]]]) -> int: """ Returns the number of clients present in the client_to_accounts dictionary. >>> get_num_clients({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0], [2.0]]}) 2 >>> get_num_clients({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0], [2.0]],\ ('Niko', 555552555): [[110.0], [1.1]]}) 3 """ return len(client_to_accounts.keys()) def validate_identity(refer: Dict[Tuple[str, int], List[List[float]]], name: str, sin: int) -> bool: """ Return True iff the name and sin are valid client in refer. >>> validate_identity({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0], [2.0]]}, 'Bob', 555555555) True >>> validate_identity({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0], [2.0]]}, 'Bob', 555234555) False """ identity = (name, sin) return identity in refer.keys() def get_num_accounts(refer: Dict[Tuple[str, int], List[List[float]]], valid: Tuple[str, int]) -> int: """ Return number of the total number of accounts the valid has open without loan accounts. >>> get_num_accounts({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0], [2.0]]}, ('Bob', 555555555)) 1 >>> get_num_accounts({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0, 223.0], [2.0, 1.5]]}, ('Sally', 123123123)) 2 >>> get_num_accounts({('Bob', 555555555): [[100.-1], [1.0]], \ ('Sally', 123123123): [[250.0], [2.0]]}, ('Bob', 555255555)) 0 """ acc = 0 if valid in refer: for item in refer[valid][0]: if item >= 0: acc += 1 return acc def get_account_balance(refer: Dict[Tuple[str, int], List[List[float]]], valid: Tuple[str, int], num: int) -> float: """ Return relative number of money in refer based on valid_client and its account number. >>> get_account_balance({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0, 223.0], [2.0, 1.5]]},\ ('Sally', 123123123), 0) 250.0 >>> get_account_balance({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0, 223.0], [2.0, 1.5]]},\ ('Sally', 123123123), 1) 223.0 """ if valid in refer: return refer[valid][0][num] else: return 0 def open_savings_account(data: Dict[Tuple[str, int], List[List[float]]], name: Tuple[str, int], money: float, rate: float) -> None: if name not in data: return None else: last = data[name][0][-1] if last >= 0: data[name][0].append(money) data[name][-1].append(rate) else: data[name][0].insert(len(data[name][0]) - 1, money) data[name][-1].insert(len(data[name][0]) - 1, rate) def get_client_to_total_balance(refer: Dict[Tuple[str, int], List[List[float]]]) \ -> Dict[Tuple[str, int], float]: """ Return a new dictionary with the specific format. >>> get_client_to_total_balance({('Bob', 555555555): [[100.0], [1.0]],\ ('Sally', 123123123): [[250.0, 223.0], [2.0, 1.5]]}) {('Bob', 555555555): 100.0, ('Sally', 123123123): 473.0} >>> get_client_to_total_balance({('Bob', 555555555): [[102.0], [1.0]],\ ('Sally', 123123123): [[252.0, 2113.0], [2.0, 1.5]]}) {('Bob', 555555555): 102.0, ('Sally', 123123123): 2365.0} """ acc = {} for key in refer: if key not in acc: acc[key] = sum(refer[key][0]) return acc def update_balance(refer: Dict[Tuple[str, int], List[List[float]]], valid: Tuple[str, int], num: int, change: float, code: int) -> None: """ Update the refer dictionary of the valid client by a plenty of rules from account number, change balance amount and code. >>> refer = {('Karla Hurst', 770898021): \ [[768.0, 4399.0, -2070.0], [0.92, 2.3, 1.5]]} >>> update_balance(refer, ('Karla Hurst', 770898021), 1, 1.0, 1) >>> refer {('Karla Hurst', 770898021): [[768.0, 4400.0, -2070.0], [0.92, 2.3, 1.5]]} >>> refer = {('Karla Hurst', 770898021): \ [[768.0, 4399.0, -2070.0], [0.92, 2.3, 1.5]]} >>> update_balance(refer, ('Karla Hurst', 770898021), 1, 1.0, -1) >>> refer {('Karla Hurst', 770898021): [[768.0, 4398.0, -2070.0], [0.92, 2.3, 1.5]]} """ if code == WITHDRAW_CODE: refer[valid][0][num] = refer[valid][0][num] - change else: refer[valid][0][num] = refer[valid][0][num] + change # def get_loan_status(refer: Dict[Tuple[str, int], # List[List[float]]], # balance: Dict[Tuple[str, int], float], # valid: Tuple[str, int], loan: float) -> bool: # """ Return True iff if the loan is approved, otherwise the function # will return False. # # >>> >>> refer = {('Karla Hurst', 770898021): [[768.0, 2070.0], [0.92, 1.5]], \ # ('Pamela Dickson', 971875372): [[333.0, 222.0, 111.0, 100000.0], \ # [2.1, 2.45, 2.4, 2.0]], ('Roland Lozano', 853887123): \ # [[1500.0, 1100.0, 1400.0, 3500.0, -500.0], [0.63, 0.05, 0.34, 0.92, 0.04]]} # >>> balance = {('Karla Hurst', 770898021): 2838.0, \ # ('Pamela Dickson', 971875372): 100666.0, \ # ('Roland Lozano', 853887123): 7000.0} # >>> get_loan_status(refer, balance, ('Roland Lozano', 853887123), 800.0) # False # >>> get_loan_status(refer, balance, ('Pamela Dickson', 971875372), 500.0) # True # """ # # avg, acc, point, half, count = \ # average(balance), [], 0, round(len(refer[valid][0]) / 2), 0 # for key in balance: # acc.append(balance[key]) # sigma = get_sd(acc) # if sum(refer[valid][0]) <= 0 or refer[valid][0][-1] < 0: # return False # if sum(refer[valid][0]) > avg: # point += 1 # if refer[valid][0][-1] < 0: # if sum(refer[valid][0]) > refer[valid][0][-1]: # point += 1 # if balance[valid] < avg - sigma: # point -= 2 # if balance[valid] > avg + sigma: # point += 2 # if not refer[valid][0][-1] < 0: # point += 5 # for item in refer[valid][0]: # if item > avg + sigma: # count += 1 # if count > half: # point += 5 # return point >= 5 def get_financial_range_to_clients(data: Dict[Tuple[str, int], float], chosen: List[Tuple[float, float]]) -> \ Dict[Tuple[float, float], List[Tuple[str, int]]]: acc = {} for key_1 in chosen: acc[key_1] = [] for key_2 in data: for key2 in acc: lower = key2[0] upper = key2[-1] if lower <= data[key_2] <= upper: acc[key2].append(key_2) acc2 = {} for key8 in acc: if not acc[key8] == []: acc2[key8] = acc[key8] return acc2 def get_fv_from_accounts(list1: List[float], list2: List[float], year: int) -> float: amount = 0 for index in range(len(list1)): value = get_fv(list1[index], list2[index], year) amount += value return amount def time_to_client_goal(data: Dict[Tuple[str, int], List[List[float]]], name: Tuple[str, int], standard: float) -> int: amount = 0 year = 1 flag = True for item in data[name][0]: amount += item if not amount >= standard: while flag: for position in range(len(data[name][0])): num1 = data[name][0][position] num2 = data[name][-1][position] amount += get_fv(num1, num2, year) if not amount >= standard: year += 1 amount = 0 else: return year return year else: return 0 if __name__ == "__main__": import doctest # uncomment the following line to run your docstring examples doctest.testmod()
"""Amazing Banking Corporation functions""" from typing import List, Tuple, Dict, TextIO # Constants # client_to_accounts value indexing BALANCES = 0 INTEREST_RATES = 1 # transaction codes WITHDRAW_CODE = -1 DEPOSIT_CODE = 1 LOAN_INTEREST_RATE = 2.2 # percent ## ------------ HELPER FUNCTIONS GIVEN BELOW ----------- # do not modify def display_client_accounts(client_to_accounts: Dict, client: Tuple) -> None: """ Display the indicated client's account balances in a human-friendly format, using the client_to_account dictionary. The first account is a chequing account, followed by subsequent savings account(s). A loan account, if present, is signified as the last account if it has a negative balance. """ i = 0 for account in client_to_accounts[client][BALANCES]: if i == 0: # the first account is always a chequing account print("Chequing Account") elif account > 0: print("Savings Account {}".format(i)) else: print("Loan Account") print("$ {:.2f}".format(account)) i += 1 def get_fv(present_value: float, r: float, n: int) -> float: """ Return the future value calculated using the given present value (pv) growing with rate of return (interest rate) r, compounded annually, for a total of n years. r is given as a percentage value. """ return present_value * (1 + r / 100) ** n def get_sd(x: List[float]) -> float: """ Return the standard deviation of the values in the list x. """ n = len(x) x_bar = (sum(x)) / n sd = 0 for x_i in x: sd += (x_i - x_bar) ** 2 return (sd / n) ** 0.5 ### ----------- END OF PROVIDED HELPER FUNCTIONS -------------- def load_financial_data(file: TextIO) -> \ Dict[Tuple[str, int], List[List[float]]]: """ Return a client to accounts dictionary buy input file. """ diction, index = {}, 0 acc = file.readlines() for line in acc: if acc[index].strip() == '' or index == 0: if acc[index].strip() == '': index += 1 key_1 = line.strip() index += 1 key_2 = int(float(acc[index].strip().replace(' ', ''))) index += 1 key, diction[key] = (key_1, key_2), [[], []] elif line.strip() == '' or line.strip()[0] == 'C' \ or line.strip()[0] == 'S': index += 1 elif line.strip()[0] == 'B': diction[key][0].append(float(acc[index].strip().split()[-1])) index += 1 elif line.strip()[0] == 'I': diction[key][1].append(float(acc[index].strip().split()[-1])) index += 1 return diction def get_num_clients(client_to_accounts: Dict[Tuple[str, int], List[List[float]]]) -> int: """ Returns the number of clients present in the client_to_accounts dictionary. >>> get_num_clients({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0], [2.0]]}) 2 >>> get_num_clients({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0], [2.0]],\ ('Niko', 555552555): [[110.0], [1.1]]}) 3 """ return len(client_to_accounts.keys()) def validate_identity(refer: Dict[Tuple[str, int], List[List[float]]], name: str, sin: int) -> bool: """ Return True iff the name and sin are valid client in refer. >>> validate_identity({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0], [2.0]]}, 'Bob', 555555555) True >>> validate_identity({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0], [2.0]]}, 'Bob', 555234555) False """ identity = (name, sin) return identity in refer.keys() def get_num_accounts(refer: Dict[Tuple[str, int], List[List[float]]], valid: Tuple[str, int]) -> int: """ Return number of the total number of accounts the valid has open without loan accounts. >>> get_num_accounts({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0], [2.0]]}, ('Bob', 555555555)) 1 >>> get_num_accounts({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0, 223.0], [2.0, 1.5]]}, ('Sally', 123123123)) 2 >>> get_num_accounts({('Bob', 555555555): [[100.-1], [1.0]], \ ('Sally', 123123123): [[250.0], [2.0]]}, ('Bob', 555255555)) 0 """ acc = 0 if valid in refer: for item in refer[valid][0]: if item >= 0: acc += 1 return acc def get_account_balance(refer: Dict[Tuple[str, int], List[List[float]]], valid: Tuple[str, int], num: int) -> float: """ Return relative number of money in refer based on valid_client and its account number. >>> get_account_balance({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0, 223.0], [2.0, 1.5]]},\ ('Sally', 123123123), 0) 250.0 >>> get_account_balance({('Bob', 555555555): [[100.0], [1.0]], \ ('Sally', 123123123): [[250.0, 223.0], [2.0, 1.5]]},\ ('Sally', 123123123), 1) 223.0 """ if valid in refer: return refer[valid][0][num] else: return 0 def open_savings_account(refer: Dict[Tuple[str, int], List[List[float]]], valid: Tuple[str, int], balance: float, interest: float) -> None: """ Update the refer dictionary of the valid client by new balance and interest. >>> refer2 = {('Bob', 555555555): [[100.0], [1.0]]} >>> open_savings_account(refer2, ('Bob', 555555555), 23.0 , 1.7) >>> refer2 {('Bob', 555555555): [[100.0, 23.0], [1.0, 1.7]]} >>> refer2 = {('Bob', 555555555): [[100.0], [1.0]]} >>> open_savings_account(refer2, ('Bob', 555555555), 33.0 , 4.7) >>> refer2 {('Bob', 555555555): [[100.0, 33.0], [1.0, 4.7]]} """ if valid in refer: if refer[valid][0][-1] < 0: refer[valid][0].insert(-1, balance) refer[valid][-1].insert(-1, interest) else: refer[valid][0].extend([balance]) refer[valid][-1].extend([interest]) def get_client_to_total_balance(refer: Dict[Tuple[str, int], List[List[float]]]) \ -> Dict[Tuple[str, int], float]: """ Return a new dictionary with the specific format. >>> get_client_to_total_balance({('Bob', 555555555): [[100.0], [1.0]],\ ('Sally', 123123123): [[250.0, 223.0], [2.0, 1.5]]}) {('Bob', 555555555): 100.0, ('Sally', 123123123): 473.0} >>> get_client_to_total_balance({('Bob', 555555555): [[102.0], [1.0]],\ ('Sally', 123123123): [[252.0, 2113.0], [2.0, 1.5]]}) {('Bob', 555555555): 102.0, ('Sally', 123123123): 2365.0} """ acc = {} for key in refer: if key not in acc: acc[key] = sum(refer[key][0]) return acc def update_balance(refer: Dict[Tuple[str, int], List[List[float]]], valid: Tuple[str, int], num: int, change: float, code: int) -> None: """ Update the refer dictionary of the valid client by a plenty of rules from account number, change balance amount and code. >>> refer = {('Karla Hurst', 770898021): \ [[768.0, 4399.0, -2070.0], [0.92, 2.3, 1.5]]} >>> update_balance(refer, ('Karla Hurst', 770898021), 1, 1.0, 1) >>> refer {('Karla Hurst', 770898021): [[768.0, 4400.0, -2070.0], [0.92, 2.3, 1.5]]} >>> refer = {('Karla Hurst', 770898021): \ [[768.0, 4399.0, -2070.0], [0.92, 2.3, 1.5]]} >>> update_balance(refer, ('Karla Hurst', 770898021), 1, 1.0, -1) >>> refer {('Karla Hurst', 770898021): [[768.0, 4398.0, -2070.0], [0.92, 2.3, 1.5]]} """ if code == WITHDRAW_CODE: refer[valid][0][num] = refer[valid][0][num] - change else: refer[valid][0][num] = refer[valid][0][num] + change def get_loan_status(client_to_account: Dict[Tuple[str, int], List[List[float]]], client_bal: Dict[Tuple[str, int], float], client: Tuple[str, int], loan: float) -> bool: """ Return True iff if the loan is approved, otherwise the function will return False. >>> client_to_account = {('Dog', 111): [[100.0, 200.0], [0.5, 1.2]],\ ('Cat', 222): [[700.0], [7.6]], ('Elephant', 333):\ [[200.0, 200.0, 200.0, 200.0, -500.0], [0.63, 0.05, 0.34, 0.92, 0.04]]} >>> cli_dic= {('Dog', 111): 300.0, ('Cat', 222):\ 700.0, ('Elephant', 333): 0.0} >>> get_loan_status(client_to_account, cli_dic, ('Elephant', 333), 300.0) False >>> get_loan_status(client_to_account, cli_dic, ('Cat', 222), 20.0) True """ point, acr, mean, acc = 0, 0, 0, 0 for num in client_bal: acr += client_bal[num] mean = acr / len(client_bal) empty_list = [] for a in client_bal.values(): empty_list.append(a) sigma = get_sd(empty_list) if client_bal[client] > mean: point += 1 if client_bal[client] >= loan: point += 1 for each_account in client_to_account[client][0]: if mean - sigma > each_account: point -= 2 if mean + sigma < each_account: point += 2 acc += 1 if acc >= len(client_to_account[client][1]) // 2 + 1: point += 5 if point >= 5: client_to_account[client][0].append(-loan) client_to_account[client][-1].append(LOAN_INTEREST_RATE) return True else: return False def get_financial_range_to_clients(refer: Dict[Tuple[str, int], float], ranges: List[Tuple[float, float]]) -> \ Dict[Tuple[float, float], List[Tuple[str, int]]]: """ Return a new dictionary with the a lot of asked format. >>> refer2 = {('Bob', 555555555): 20.0 ,('Sally', 123123123): 100.0} >>> ranges2 = [(0.0, 20.0), (30.0, 140.0)] >>> get_financial_range_to_clients(refer2, ranges2) {(0.0, 20.0): [('Bob', 555555555)], (30.0, 140.0): [('Sally', 123123123)]} >>> refer3 = {('Bob', 555555555): 17.0 ,('Sally', 123123123): 18.0} >>> ranges3 = [(0.0, 20.0), (30.0, 140.0)] >>> get_financial_range_to_clients(refer3, ranges3) {(0.0, 20.0): [('Bob', 555555555), ('Sally', 123123123)]} """ acc = {} for item in ranges: if item not in acc: acc[item] = [] for key in refer: for key2 in acc: if key2[0] <= refer[key] <= key2[-1]: acc[key2].append(key) invalid = [] for key3 in acc: if not acc[key3]: invalid.append(key3) for key4 in invalid: acc.pop(key4) return acc def get_fv_from_accounts(balances: List[float], rates: List[float], time: int) -> float: """ Return the sum of the future amount of money of all the account balances given their respective interest rates. >>> balances = [768.0, 2070.0] >>> rates = [0.92, 1.5] >>> get_fv_from_accounts(balances, rates, 2) 2914.761953519999 >>> balances2 = [78.0, 20.0] >>> rates2 = [0.22, 1.2] >>> get_fv_from_accounts(balances2, rates2, 2) 98.82645751999998 """ acc = 0 for index in range(len(balances)): acc += get_fv(balances[index], rates[index], time) return acc def time_to_client_goal(refer: Dict[Tuple[str, int], List[List[float]]], valid: Tuple[str, int], amount: float) -> int: """ Return the smallest number of years it would spend for the client's total balance in order to get or overcome the goal that set before. >>> refer = {('Karla Hurst', 770898021):\ [[768.0, 2070.0], [0.92, 1.5]],\ ('Pamela Dickson', 971875372):\ [[36358866.0, 5395448.0, 23045442.0,\ 14316660.0, 45068981.0, 4438330.0,\ 16260321.0, 7491204.0, 23330669.0],\ [2.3, 2.35, 2.25, 2.35, 2.05,\ 2.1, 2.45, 2.4, 2.0]],\ ('Roland Lozano', 853887123):\ [[1585.0, 1170.0, 1401.0,\ 3673.0], [0.63, 0.05,\ 0.34, 0.92]]} >>> valid = ('Karla Hurst', 770898021) >>> time_to_client_goal(refer, valid, 100000.0) 255 >>> refer2 = {('Karla Hurst', 770898021):\ [[100.0, 100.0], [2.0, 2.0]],\ ('Pamela Dickson', 971875372):\ [[36358866.0, 5395448.0, 23045442.0,\ 14316660.0, 45068981.0, 4438330.0,\ 16260321.0, 7491204.0, 23330669.0],\ [2.3, 2.35, 2.25, 2.35, 2.05,\ 2.1, 2.45, 2.4, 2.0]],\ ('Roland Lozano', 853887123):\ [[1585.0, 1170.0, 1401.0,\ 3673.0], [0.63, 0.05,\ 0.34, 0.92]]} >>> valid2 = ('Karla Hurst', 770898021) >>> time_to_client_goal(refer2, valid2, 500.0) 47 """ if sum(refer[valid][0]) >= amount: return 0 year = 1 while True: money = 0 for index in range(len(refer[valid][0])): money += get_fv(refer[valid][0][index], refer[valid][-1][index], year) if money >= amount: return year else: year += 1 return year def average(refer: Dict[Tuple[str, int], float]) -> float: """ Return average value of refer. >>> {('Karla Hurst', 770898021): 2838.0} {('Karla Hurst', 770898021): 2838.0} """ amount, count = 0, 0 for key in refer: count += 1 amount += refer[key] return amount / count if __name__ == "__main__": import doctest import python_ta python_ta.check_all() # uncomment the following line to run your docstring examples doctest.testmod()
#310. Minimum Height Trees from typing import List class Solution: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: graph = [set() for _ in range(n)] for u, v in edges: graph[u].add(v) graph[v].add(u) leaves = [x for x in range(n) if len(graph[x]) <= 1] pre_leaves = leaves while leaves: new_leaves = [] for leaf in leaves: if not graph[leaf]: return leaves neighbor = graph[leaf].pop() graph[neighbor].remove(leaf) if len(graph[neighbor]) == 1: new_leaves.append(neighbor) pre_leaves, leaves = leaves, new_leaves return pre_leaves
from typing import List class Solution: def combine(self, n: int, k: int) -> List[List[int]]: res = [] self.dfs(res, [], n, 1, 0, k) return res def dfs(self, res, path, n, curVal, curSize, k): if curSize == k: res.append(list(path)) return if curVal > n or curSize > k: return # not add curVal self.dfs(res, path, n, curVal + 1, curSize, k) # add curVal path.append(curVal) self.dfs(res, path, n, curVal + 1, curSize + 1, k) path.pop() if __name__ == '__main__': print(Solution().combine(4, 2))
from collections import deque from typing import List class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ if not board or not board[0]: return row, col = len(board), len(board[0]) queue = deque() for i in range(row): queue.append((i, 0)) queue.append((i, col - 1)) for j in range(col): queue.append((0, j)) queue.append((row - 1, j)) while queue: i,j = queue.popleft(); if 0<= i < row and 0<= j < col and board[i][j] == 'O': board[i][j] = 'Y' queue.append((i - 1, j)) queue.append((i + 1, j)) queue.append((i, j - 1)) queue.append((i, j + 1)) for i in range(row): for j in range(col): if board[i][j] == 'O': board[i][j] = 'X' if board[i][j] == 'Y': board[i][j] = 'O'
"""This module provides the function to split a string of names into a list of names.""" import argparse parser = argparse.ArgumentParser() parser.add_argument('-s', '--string', type=str, default='Денис, Олег, Вася, Петя,Дима,Женя', help='String of names. Ex: \'Вася, Петя,Денис, Женя\' ') args = parser.parse_args() def split(string: str = args.string) -> list: ''' Splitting a string of names into a list of names. List items (names) do not contain spaces. Args: string: string of names. Returns: list of names. ''' return [x.replace(' ', '') if ' ' in x else x for x in string.split(',')] if __name__ == '__main__': print('List of names:', split())
import os import csv budget_data = os.path.join('budget_data.csv') with open(budget_data, newline='') as csvfile: csvreader = csv.reader (csvfile, delimiter=',') print (csvreader) csv_header = next (csvreader) total_month_count = [] total_month_count = 0 net_total = [] net_total = 0 beginning_number = 0 monthly_difference = [] monthly_difference_list = [] total_difference = [] total_difference = 0 date = [] for row in csvreader: total_month_count = total_month_count + 1 net_total = net_total + int(row[1]) ending_number = int(row[1]) monthly_difference = ending_number - beginning_number monthly_difference_list.append(monthly_difference) beginning_number = ending_number total_difference = total_difference + monthly_difference average_difference = total_difference / total_month_count greatest_increase = max(monthly_difference_list) greatest_decrease = min(monthly_difference_list) date.append(row[0]) greatest_increase_date = date[monthly_difference_list.index(greatest_increase)] greatest_decrease_date = date[monthly_difference_list.index(greatest_decrease)] print("Financial Analysis") print("------------------------") print("Total Month: " + str(total_month_count)) print("Total: " + "$" + str(net_total)) print("Average Change: " + "$"+ str(average_difference)) print("Greatest Increase in Profits: " + str(greatest_increase_date) + " ($"+str(greatest_increase)+")") print("Greatest decrease in Profits: " + str(greatest_decrease_date) + " ($"+str(greatest_decrease)+")")
n=input() nn=list(n) s="Hello," c=0 for x in nn: if 97<=ord(x)<=122 or 65<=ord(x)<=90 or 32<=ord(x)<=42 or 58<=ord(x)<=64 or 91<=ord(x)<=96 or 123<=ord(x)<=127 or ord(x)==47 or ord(x)==44 or ord(x)==43 or ord(x)==45 or ord(x)==46: c+=1 if c==0: z=s*int(n) lst=z.split(",") for x in range(len(lst)): print(lst[x]) else: print("invalid input")
n1=float(input()) n2=float(input()) n3=float(input()) if n1!=n2!=n3: if n1>n2 and n1>n3: print(n1) elif n2>n3 and n2>n1: print(n2) else: print(n3) elif n1==n2==n3: print(n1) else : if n1==n2: if n1>n3: print(n1) else: print(n3) if n2==n3: if n2>n1: print(n2) else: print(n1) if n3==n1: if n3>n2: print(n3) else: print(n2)
class Nodo: # Clase para crear los nodos def __init__(self, estado, madre, accion, costo_camino, codigo): self.estado = estado self.madre = madre self.accion = accion self.costo_camino = costo_camino self.codigo = codigo def nodo_hijo(problema, madre, accion): # Función para crear un nuevo nodo # Input: problema, que es un objeto de clase ocho_reinas # madre, que es un nodo, # accion, que es una acción que da lugar al estado del nuevo nodo # Output: nodo estado = problema.transicion(madre.estado, accion) costo_camino = madre.costo_camino + problema.costo(madre.estado, accion) codigo = problema.codigo(estado) return Nodo(estado, madre, accion, costo_camino, codigo) def depth_first_search(problema): nodo = Nodo(problema.estado_inicial, None, None, 0, problema.codigo(problema.estado_inicial)) if problema.test_objetivo(nodo.estado): return nodo frontera = [nodo] explorados = [] while len(frontera) > 0: nodo = frontera.pop() explorados.append(nodo.codigo) for accion in problema.acciones_aplicables(nodo.estado): hijo = nodo_hijo(problema, nodo, accion) if problema.test_objetivo(hijo.estado): return hijo if hijo.codigo not in explorados: frontera.append(hijo) return None def breadth_first_search(problema): nodo = Nodo(problema.estado_inicial, None, None, 0, problema.codigo(problema.estado_inicial)) if problema.test_objetivo(nodo.estado): return nodo frontera = [nodo] explorados = [] while len(frontera) > 0: nodo = frontera.pop(0) explorados.append(nodo.codigo) for accion in problema.acciones_aplicables(nodo.estado): hijo = nodo_hijo(problema, nodo, accion) if problema.test_objetivo(hijo.estado): return hijo if hijo.codigo not in explorados: frontera.append(hijo) return None def solucion(n): if n.madre == None: return [] else: return solucion(n.madre) + [n.accion] def backtracking_search(prob, estado): if prob.test_objetivo(estado): return estado for accion in prob.acciones_aplicables(estado): hijo = prob.transicion(estado, accion) resultado = backtracking_search(prob, hijo) if resultado is not None: return resultado return None def best_first_search(problema, f = None): if f is not None: setattr(problema, "costo", f) problema.costo = setattr(problema,"costo", f) s = problema.estado_inicial cod = problema.codigo(s) nodo = Nodo(s, None, None, 0, cod) frontera = ListaPrioritaria() frontera.push(nodo, 0) explorados = {} explorados[cod] = 0 while not frontera.is_empty(): nodo = frontera.pop() if problema.test_objetivo(nodo.estado): return nodo for hijo in expand(problema, nodo): s = hijo.estado cod = problema.codigo(s) c = hijo.costo_camino if cod not in explorados.keys() or c < explorados[cod]: frontera.push(hijo, c) explorados[cod] = c return None
def pushupCounter(maxCount): if maxCount == 1: return(1) else: return(maxCount + pushupCounter(maxCount-1)) def Main(): total = pushupCounter(12) print(total) Main()
import turtle from itertools import cycle colors = cycle(['red', 'orange', 'yellow', 'green', 'blue', 'purple']) # def draw_circle(size, angle, shift): # turtle.bgcolor(next(colors)) # turtle.pencolor(next(colors)) # turtle.circle(size) # turtle.right(angle) # turtle.forward(shift) # draw_circle(size + 5, angle + 1, shift + 1) def draw_shape(size, angle, shift, shape): turtle.pencolor(next(colors)) next_shape = '' if shape == 'circle': turtle.circle(size) next_shape = 'square' elif shape == 'square': for i in range(4): turtle.forward(size * 2) turtle.left(90) next_shape = 'circle' turtle.right(angle) turtle.forward(shift) draw_shape(size + 5, angle + 1, shift + 1, next_shape) def main(): turtle.bgcolor('black') turtle.speed(10) turtle.pensize(4) turtle.pencolor('red') draw_shape(30, 0, 1, 'circle') if __name__ == "__main__": main()
"""implements a Convoluted NN using TensorFlow Core APIs from Udacity's tutorial. It is meant as an exercise to package up TF code, run and deploy it on Google ML Cloud. To understand the TF code, refer to 4_convolutions.ipynb. """ from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range IMAGE_SIZE = 28 NUM_LABELS = 10 NUM_CHANNELS = 1 # grayscale PATCH_SIZE = 4 DEPTH = 24 NUM_HIDDEN = 256 NUM_HIDDEN2 = 128 BATCH_SIZE = 32 TRAIN, EVAL, PREDICT = 'TRAIN', 'EVAL', 'PREDICT' def model_fn(mode): """Create a Recurrent DNN (from Problem 2 in Assignment 4 - Convolutions) Args: mode (string): Mode running training, evaluation or prediction features (dict): Dictionary of input feature Tensors labels (Tensor): Class label Tensor hidden_units (list): Hidden units learning_rate (float): Learning rate for the SGD Returns: Depending on the mode returns Tuple or Dict """ train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels = input_fn() # Input data. tf_train_dataset = tf.placeholder( tf.float32, shape=(BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS)) tf_train_labels = tf.placeholder(tf.float32, shape=(BATCH_SIZE, NUM_LABELS)) tf_valid_dataset = tf.constant(valid_dataset) tf_test_dataset = tf.constant(test_dataset) # Variables. layer1_weights = tf.Variable(tf.truncated_normal( [PATCH_SIZE, PATCH_SIZE, NUM_CHANNELS, DEPTH], stddev=0.1)) layer1_biases = tf.Variable(tf.zeros([DEPTH])) layer2_weights = tf.Variable(tf.truncated_normal( [PATCH_SIZE, PATCH_SIZE, DEPTH, DEPTH], stddev=0.1)) layer2_biases = tf.Variable(tf.constant(1.0, shape=[DEPTH])) layer3_weights = tf.Variable(tf.truncated_normal( [IMAGE_SIZE // 4 * IMAGE_SIZE // 4 * DEPTH, NUM_HIDDEN], stddev=0.1)) layer3_biases = tf.Variable(tf.constant(1.0, shape=[NUM_HIDDEN])) layer4_weights = tf.Variable(tf.truncated_normal( [NUM_HIDDEN, NUM_LABELS], stddev=0.1)) layer4_biases = tf.Variable(tf.constant(1.0, shape=[NUM_LABELS])) # Model. def model(data): # conv2d computes a a 2D convolution given # - a 4D input tensor (our data) # - a 4D filter tensor (our weights) # - strides: 1D tensor of length 4 # - padding # This is flattened to a 2D matrix of shape # [filter_height * filter_width * in_channels, output_channels] conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME') hidden = tf.nn.relu(conv + layer1_biases) conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME') hidden = tf.nn.relu(conv + layer2_biases) shape = hidden.get_shape().as_list() reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]]) hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases) return tf.matmul(hidden, layer4_weights) + layer4_biases # Training computation. logits = model(tf_train_dataset) loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits)) if mode in (TRAIN, EVAL): # global_step is necessary in eval to correctly load the step # of the checkpoint we are evaluating global_step = tf.contrib.framework.get_or_create_global_step() # Optimizer. optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss, global_step=global_step) # Predictions for the training, validation, and test data. train_prediction = tf.nn.softmax(logits) valid_prediction = tf.nn.softmax(model(tf_valid_dataset)) test_prediction = tf.nn.softmax(model(tf_test_dataset)) if mode == TRAIN: return tf_train_dataset, tf_train_labels, optimizer, loss, train_prediction, valid_prediction, test_prediction def accuracy(predictions, labels): return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / predictions.shape[0]) def reformat(dataset, labels): dataset = dataset.reshape( (-1, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS)).astype(np.float32) labels = (np.arange(NUM_LABELS) == labels[:, None]).astype(np.float32) return dataset, labels
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pathSum(self, root: TreeNode, sum: int) -> int: def findSum(root): if root: traverse(root, sum) findSum(root.left) findSum(root.right) def traverse(root, target): if root: if root.val == target: self.allPaths += 1 traverse(root.left, target-root.val) traverse(root.right, target-root.val) self.allPaths = 0 findSum(root) return self.allPaths class Solution: def pathSum(self, root: TreeNode, sum: int) -> int: if root: return self.traverse(root, sum) +\ self.pathSum(root.left, sum) +\ self.pathSum(root.right, sum) else: return 0 def traverse(self, root, target): if root: return int(root.val == target) + \ self.traverse(root.left, target-root.val) +\ self.traverse(root.right, target-root.val) else: return 0
#bubblesort def bubblesort(nums: list): switched = True while switched: switched = False for i in range(len(nums)): if nums[i] > nums[i+1]: nums[i],nums[i+1] = nums[i+1], nums[i] switched = True
# coding: utf-8 """ 斐波那契数列: 又称黄金分割数列, 指得是这样一个数列, 1, 1, 2, 3, 5, 8..., 这个数列从第三项开始, 每一项都等于前两项之和。 求数列第n项 """ # 我们很容易就可以写出这么一个递归函数 def fibonacci(n): if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2) li = fibonacci(5) print(li) # 改进一 def fibonacci(n, cache=None): if cache is None: cache = {} if n in cache: return cache[n] if n <= 1: return n cache[n] = fibonacci(n - 1, cache) + fibonacci(n - 2, cache) return cache[n] print(fibonacci(100)) # 改进二 def memo(func): cache = {} def wrap(*args): if args not in cache: cache[args] = func(*args) return cache[args] return wrap @memo def fibonacci(n): if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(60))
i = 4 d = 4.0 s = 'HackerRank ' I=int(input()) D=float(input()) string=input() intsum=i+I floatsum=d+D stringsum=s+string print(intsum) print(floatsum) print(stringsum)
T=int(input()) for i in range(0,T): S=str(input()) even_string='' odd_string='' for j in range(0,len(S)): if j%2==0: even_string+=S[j] else : odd_string+=S[j] print(even_string,odd_string)
from flask import Flask, request # Crear una aplicación de Flask # Para correr Flask tenemos que poner en terminal "py -m flask run" adicional tenemos que nombrar el archivo como app.py ó podemos asignar la variable FLASK_APP en un archivo nuevo que nombraremos .flaskenv app = Flask(__name__) # Creando la ruta raiz "/" @app.route("/") def hello(): return "Hello World" # Agregamos la variable FLASK_ENV=development en el archivo .flaskenv para poder actualizar el navegador y corra los cambios. # Podemos crear las rutas que queramos, simplemente en el navegador vamos a agregar la ruta por ejemplo "http://127.0.0.1:5000/test" @app.route("/test") def test(): return "Esto es una prueba" # Querystring @app.route("/suma") def suma(): # Acceder a un parametro en Querystring #request.args.get('parametro', 'valor por defecto', 'tipo') tambien debemos importar request param1 = request.args.get('a', 0, int) param2 = request.args.get('b', 0, int) resultado = param1 + param2 return "La suma de {} + {} = {}".format(param1, param2, resultado) # Querystring ===> tenemos que usar la url ej "http://127.0.0.1:5000/suma" agregamos un "?" posterior K "parametro"=V 'valor' # <<===================================================================================================================================================>> # URL @app.route("/saluda/<nombre>/<edad>") def saluda(nombre, edad): return "Hola {} de {} años".format(nombre, edad) #Colocando el parametro entre <> lo hace dinámico #Consultandolo por url ejemplo "http://127.0.0.1:5000/saluda/Luis/34" """ Ejercicio: Implementar una ruta que a traves de la URL le indique la opeación matemática a realizar y por Query String los operandos. """ @app.route("/calculadora/<operador>") def calculadora(operador): param1 = request.args.get('a', 0, int) param2 = request.args.get('b', 0, int) if operador == "suma": return "La Suma de {} y {} = {}".format(param1, param2, param1 + param2) elif operador == "resta": return "La Resta de {} y {} = {}".format(param1, param2, param1 - param2) elif operador == "multiplicacion": return "La Multiplicación de {} y {} = {}".format(param1, param1, param1 * param2) elif operador == "division": if param1 == 0: return "ERROR: División entre 0" else: return "La División de {} y {} = {}".format(param1, param2, param1 / param2)
#Numeros (+, -, *, /, //, **, %) num1 = 10 num2 = 20 print(num1 + num2) #Concatenación (suma de las cadenas de texto) nombre1 = "Luis" nombre2 = "Dominguez" print(nombre1 + " "+ nombre2) #Operadores de comparación (<, >, <=, >=, ==) print(num1 == num2) #Operadores Logicos (or, and, not) bool1 = True bool2 = False print(bool1 or bool2)
def es_palindromo(texto): # Convierte cualquier string en minúsculas y elimina todos los caracteres no alfabéticos def toChar(texto): texto = texto.lower() ans = '' for letras in texto: if letras in 'abcdefghijklmnopqrstuvwxyz': ans = ans + letras return ans def esPal(texto): if len(texto) <= 1: return True else: return texto[0] == texto[-1] and esPal(texto[1:-1]) return esPal(toChar(texto)) # Examples of calling isPalindrome() print ("") print ('Is eve a Palindrome?') print (es_palindromo('eve')) print ("") print ('Is able was I ere saw Elba a Palindrome?') print (es_palindromo('Able was I, ere I saw Elba'))
from operaciones import * def test_suma_cero(): resultado = suma(0, 0) # Espero que resultado sea 0 assert resultado == 0 # Para correr el test tenemos que escibir en consola lo siguiente: "py -m pytest" # Para tener mas detalle podemos escribir al final -v def test_suma_numeros_iguales(): assert suma (2, 2) == 2 * 2 assert suma (8, 8) == 8 * 2 def test_suma_cadenas(): resultado = suma("Hello ", "World") assert len(resultado) > 0 assert type(resultado) == str assert resultado == "Hello World" # Agregando -x en la consola podemos hacer que el test se detenga hasta donde las pruebas pasan
"2.6 Fibonacci Series" def fibonacci(number): " the value of the Fibonacci sequence." if number in (1, 2): return 1 return fibonacci(number - 2) + fibonacci(number - 1) print(fibonacci(10))
from Tkinter import * root= Tk() root.title('deep.tech') root.configure(background='black') root.geometry('360x480') details = Label(root, text='enter roll no:', width=30, bg = "green") details.grid(row=0,column=0) num1=Entry(root, width=10, bg='pink') num1.grid(row=1,column=0) def changename(): roll_number=int(num1.get() ) f=open('student.py') i=1 for student in f: if i ==roll_number: all_details=student i=i+1 li_details=all_details.split(',') details_of_user='name:'+ li_details[0] + 'marks' + li_details[1]+ 'attendance:' + li_details[2] details.configure(text=details_of_user) btn=Button(root, width=10,bg='red', fg='red', command=changename) btn.grid(row=2,column=1) root.mainloop()
from util.geometry import is_in_polygon class world(object): def __init__(self, width, height): self.width = width self.height = height # list of objects that are within the physics environment self.bodies = [] # list of objects that are in the world self.entities = [] def get_entities_in(self, top_left, top_right, bottom_left, bottom_right): """ Returns a list of objects that are within the bounding box. """ # returns any object with a vertice within the dimensions given result = [] for _ in self.entities: for v in _.get_abs_vertices(): vertices = ((top_left['x'], top_left['y']),(top_right['x'], top_right['y']),(bottom_left['x'], bottom_left['y']),(bottom_right['x'], bottom_right['y'])) if is_in_polygon(vertices, (v['x'], v['y'])): result.append(_) break return result def add_entity(self, entity): self.entities.append(entity) def remove_entity(self, entity): self.entities.remove(entity) def add_body(self, body): self.bodies.append(body) def remove_body(self, body): self.bodies.remove(body)
#! /usr/bin/python3 def main(): f= open("7segfont.txt","a+") print("This script shows you every ASCII character from 0x20 to 0x60") print("and prompts you to enter a binary number for the Seven Segment pattern") print("where the least significent bit is the 'a' segment") print("and the most significent bit is for the decimal point. ") print("Other segments are in between.") print("for example for the charecter '1' you should enter 01100000 ") print("More info about Seven Segments and their pins:") print("https://circuitdigest.com/article/7-segment-display") f.write("// Seven Segment patterns for ASCII characters from 0x20 to 0x60 \n") f.write("byte ss_fonts [] = { \n") for i in range(0x20, 0x60): print(format(i, 'c'), end='') x = int(input(" : "), 2) s = "0x" s += format(x, '02x') s += ", // " s += format(i, 'c') s += "\n" print(s) f.write(s) f.write("} \n") if __name__ == "__main__": main()
from typing import overload class Sample: def __init__(self): pass @overload def call(self, v: int) -> int: ... @overload def call(self, v: str) -> int: ... @overload def call(self, v: float) -> int: ... def call(self, v): if isinstance(v, float): return str(v) return int(v)
''' Created on May 28, 2013 @author: Yubin Bai First, if we want to reach the target in N moves, we have to have 1 + 2 + ... + N >= |X| + |Y|. Moreover, if we want to reach the target in N moves, the parity of the numbers 1 + 2 + ... + N and |X| + |Y| has to be the same. This is because the parity of the sum of the lengths of jumps we make in the North-South direction has to match the parity of |Y|, and the sum of lengths of West-East jumps has to match the parity of |X|. It turns out that if N satisfies these two conditions, it is possible to reach (X, Y) with N jumps. ''' def solve(x, y): N = 0 currSum = 0 while currSum < abs(x) + abs(y) or (currSum + x + y) % 2 == 1: N += 1 currSum += N result = "" while N > 0: if abs(x) > abs(y): if x > 0: result += 'E' x -= N else: result += 'W' x += N else: if y > 0: result += 'N' y -= N else: result += 'S' y += N N -= 1 return result[::-1] if __name__ == '__main__': # fInput = open('input.txt') fInput = open('input.txt') outFile = open('output.txt', 'w') numOfTests = int(fInput.readline()) for test in range(numOfTests): x, y = [int(x) for x in fInput.readline().strip().split()] result = solve(x, y) outFile.write("Case #%d: %s\n" % (test + 1, result)) fInput.close() outFile.close()
def push(stk,ele): stk.append(ele) eqn = "24+46+*" eqn = "90-34*/" eqn = "25*34+-" def postfix(eqn): stk = [] operator = ["+", "-", "/","*"] for ele in eqn: if ele not in operator: push(stk,ele) else: a = int(stk.pop()) b = int(stk.pop()) if ele=="+": push(stk,b+a) elif ele=="-": push(stk,b-a) elif ele=="*": push(stk,b*a) elif ele=="/": push(stk,b/a) else: print("Invalid Input") print(stk) postfix(eqn)
class Node: def __init__(self, data): self.data = data self.right = None self.left = None def insert(root,data): if root is None: root = Node(data) else: if root.data>data: if root.left == None: root.left = Node(data) else: insert(root.left,data) else: if root.right == None: root.right = Node(data) else: insert(root.right,data) root = Node(4) insert(root,5) insert(root,6) insert(root,7) insert(root,1) insert(root,2) insert(root,3) def kth_largest(root,k,count): if root: kth_largest(root.right, k,count) count[0]+=1 if count[0]==k: print(root.data) kth_largest(root.left,k,count) kth_largest(root,7,count=[0]) def kth_smallest(root,k,count): if root: kth_smallest(root.left, k,count) count[0]+=1 if count[0]==k: print(root.data) kth_smallest(root.right,k,count) kth_smallest(root,7,count=[0])
#GUESS THE NUMBER print("Guess the number") n = int(input()) i = 0 while(i<=9): i = i+1 if n<18 or n>18 : print("guess is wrong") print("number of guesses left",9-i) break elif n==18: print("You won") else: print("Game over")
"""(x1,y1)=(0,0) (x2,y2)=(2,3) (x3,y3)=(0,0) #Overlapping (x4,y4)=(1,2)""" (x1,y1)=(-3,-2) (x2,y2)=(2,4) (x3,y3)=(-5,-6) #Overlapping (x4,y4)=(4,6) """(x1,y1)=(0,0) (x2,y2)=(6,7) (x3,y3)=(8,9) # Not Overlapping (x4,y4)=(9,10) (x1,y1)=(-2,-1) (x2,y2)=(3,3) (x3,y3)=(-5,4) # Not Overlapping (x4,y4)=(-3,7) (x1,y1)=(-2,0) (x2,y2)=(1,2) (x3,y3)=(-4,-2) # Not Overlapping (x4,y4)=(-3,1)""" if (x2-x1)>(x4-x3) and (y2-y1)>(y4-y3): if x1<x3<x4 or y1<y3<y4: if x3>x2 or y3>y2: print("Not Overlapping") else: print("overlapping") elif x3<x4<x2 or y3<y4<y2: if x1>x4 or y1>y4: print("Not Overlapping") else: print("overlapping") else: if x3<x1<x4 or y3<y1<y4: if x1>x4 or y1>y4: print("Not Overlapping") else: print("Overlapping") elif x1<x2<x3 or y1<y2<y3 : if x3>x2 or y3>y2: print("Not Overlapping") else : print("Overlapping")
from matplotlib import pyplot as plt import numpy as np #Lineplot x = np.arange(1,11) print(x) y = 2*x print(y) z= 4*x print(z) plt.plot(x,y,color= "purple",linewidth=3,linestyle="--") plt.plot(x,z,color="yellow",linewidth=3,linestyle=":") plt.title("Line Plot") plt.xlabel("x-axis") plt.ylabel("y-axis") plt.grid(True) print(plt.show()) #Barplot students = {"Tanu":10,"Bhanu":20,"Chinu":30} Names = list(students.keys()) Marks = list(students.values()) plt.bar(Names,Marks,color="red") plt.title("Marks of Students") plt.xlabel("Name") plt.ylabel("Scores") plt.grid(True) print(plt.show()) # If we use plt.barh , then we get horizontal graph instead of vertical #Scatter-plot a = [2,6,7,9,3,0,3] b = [7,4,10,4,1,6,3] c = [0,9,8,7,6,5,4] plt.scatter(a,b) plt.scatter(a,c,color="yellow") plt.grid(True) print(plt.show()) #Histograms import pandas as pd iris = pd.read_csv("iris.csv") print(iris.head()) plt.hist(iris["Sepal.Length"],bins=25) print(plt.show()) #boxplots iris.boxplot(column="Petal.Length",by="Species") print(plt.show()) import seaborn as sns sns.boxplot(x = iris["Species"],y = iris["Petal.Width"]) plt.show() #Piechart fruits = ["apple","banana","guava","grapes"] cost = [40,60,80,100] plt.figure(figsize=(8,8)) plt.pie(cost,labels=fruits,autopct="%0.1f%%",shadow=True) plt.show()
#Import modules & libraries import requests from bs4 import BeautifulSoup import pandas from pandas import DataFrame # Building the Scraper function def web_scraper(url): r=requests.get(url) soup=BeautifulSoup(r.content,"lxml") title=[item.text for item in soup.find_all("title")] text = soup.find("div", class_= "PricesTxt").text print(text) # h2=[item.text for item in soup.find_all("h2")] scraped_content=[url,title,text] return scraped_content # Scraping a list of URLs and storing them in a DataFrame urls=["https://www.zap.co.il/model.aspx?modelid=1047644"] all_results=[] for url in urls: X=web_scraper(url) all_results.append(X) df = DataFrame(all_results,columns=["URL","Title","text"]) # export to excel df.to_excel("scraped_output.xlsx")
""" A simple program to check if a imputed string is a palindrome. Input: String, Output True/False """ def palindrome(Word): #Fuction to check if a string is a palindrome assuming all letters. if Word.lower() == Word[::-1].lower(): return True return False def has_number(word): #Function to check for numbers in the input string. return any(letter.isdigit() for letter in word) def main(): """Main function sets a variable no_number that indicates if a string has a number to false, then prompts for input and checks if it contains a number. If the input contains a number it then re prompts for input, otherwise it sets the no_number variable to true and runs the palindrome function. """ no_number = False test = input("Enter a word:") while not no_number: if has_number(test): print("Word has number!") test = input("Enter a word:") else: no_number = True print(palindrome(test)) if __name__ == '__main__': main()
import math def binarySearch(arr, l, r, x): while l <= r: mid = l + (r - l) // 2; # Check if x is present at mid if arr[mid] == x: return mid # If x is greater, ignore left half elif arr[mid] < x: l = mid + 1 else: r = mid - 1 return -1 # Driver Code arr = [ 2, 3, 4, 10, 40 ] x = 10 # Function call result = binarySearch(arr, 0, len(arr)-1, x) n=int(input()) beg1=1 end1=n beg2=1 end2=n prev=0 flag=0 ar=[] for i in range(1000000): ar.append(i+1) l=0 r=len(ar)-1 inp1=input() # for i in range(300): # print(math.floor((beg1+end1)/2),flush=True) # # print(beg1,end1) # inp1=input() # if inp1==prev or inp1=='E': # if inp1=='G': # beg1=math.ceil((beg1+end1)/2) # elif inp1=='L': # end1=math.floor((beg1+end1)/2) # else: # flag=1 # exit() # prev=inp1 # if flag==0: # print(0//0)
def dist(a,b,c): return abs(a-b)+abs(b-c)+abs(c-a) q=int(input()) while q: q-=1 ar=list(map(int,input().split())) ar.sort() if ar[0]==ar[1]==ar[2]: print(0) elif ar[0]==ar[1]: if ar[2]-1==ar[0]: print(dist(ar[0],ar[0],ar[2]-1)) else: print(dist(ar[0]+1,ar[0]+1,ar[2]-1)) elif ar[1]==ar[2]: if ar[0]+1==ar[1]: print(dist(ar[0]+1,ar[1],ar[2])) else: print(dist(ar[0]+1,ar[1]-1,ar[2]-1)) else: print(dist(ar[0]+1,ar[1],ar[2]-1))
def is_v(c): v=['A','O','Y','E','U','I','a','o','y','e','u','i'] return c in v s=input() new=[] for i in s: if not is_v(i): new.append('.') new.append(i.lower()) for i in new: print(i,sep='',end='') print()
import math n=int(input()) for i in range(1000001,1000000001): sq=(i*i) n=1000000000000000000 print(i,math.floor(n/sq))
import numpy as np A= np.array([[1,1],[2,2],[3,3]]) #one way to initialize numpy array print(A) print(A.shape) # print shape (dimension) of the matrix print(A.T) # print Transpose of A print(np.sum(A)) # print sum of all the elements of A print(np.power(A,2)) # square each element print(np.mean(A)) # average of all the elements in A print(np.std(A)) # standard deviation of all the elements in A B=np.array([[1,2],[3,4],[5,6]]) print(B*A) # print elementwise multiplication of A and B print(np.dot(A,B.T)) # print dot product of A and B transpose print(np.cross(A,B)) # print cross product of A and B print(np.eye(5)) # print identity matrix of size 5,5 print(np.zeros((4,1))) # Initialize a 4x1 vector with all values 0 print(np.ones((4,1))) # Initialize a 4x1 vector with all values as 1
# individual tree node class class Node(object): def __init__(self, key): self.left = None self.right = None self.value = key """ Depth First Traversals """ """ Inorder traversal usage: for Binary Search Trees, it gives nodes in non-decreasing order. To get nodes of BTS in non-decreasing order, a variation of inorder traversal where inorder traversal is reversed. """ def inorder(root, _callback): if root: inorder(root.left, _callback) _callback(root.value) inorder(root.right, _callback) """ Postorder traversal usage: to delete a tree, get postfix expression of an expression tree """ def postorder(root, _callback): if root: postorder(root.left, _callback) postorder(root.right, _callback) _callback(root.value) """ Preorder traversal usage: used to create a copy of the tree; get prefix expression of an expression tree. """ def preorder(root, _callback): if root: _callback(root.value) preorder(root.left, _callback) preorder(root.right, _callback) """ Breadth First or Level Order Traversal aka Level Order Binary Tree Traversal """ """ Level Order Traversal Method 1: Time Complexity: O(n^2) in worse case O(n) for a skewed tree where n is the number of nodes Call Stack Space Complexity: O(n) for worst case. O(n) space for a skewed tree O(logn) space for a balanced tree """ # level order traversal of tree def level_order_1(root, _callback): h = get_height(root) for i in range(1, h+1): given_level_call(root, i, _callback) def given_level_call(root, level, _callback): if root is None: return if level == 1: _callback(root.value) elif level > 1: given_level_call(root.left, level-1, _callback) given_level_call(root.right, level-1, _callback) # calculate the heigth of a tree--the number of nodes along the longest path starting from root node all the way to the leaf node that it is the farthest def get_height(node): if node is None: return 0 left_height = get_height(node.left) right_height = get_height(node.right) if left_height > right_height: return left_height + 1 else: return right_height + 1 """ Level Order Traversal Method 2: Using Queue For each node, the first node is visited and then it's child nodes are put in a FIFO Queue Time Complexity: O(n) where n is number of nodes in the binary tree Space Complexity: O(n) where n is number of nodes in the binary tree """ from Queue import Queue def level_order_2(root, _callback): if root is None: return q = Queue() q.enqueue(root) while q.getSize() > 0: node = q.dequeue() _callback(node.value) if node.left is not None: q.enqueue(node.left) if node.right is not None: q.enqueue(node.right) root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) def simple_print(value): print(value, end=" ") # 1 2 4 5 3 print("preorder:") preorder(root, simple_print) print() # 4 2 5 1 3 print("inorder:") inorder(root, simple_print) print() # 4 5 2 3 1 print("postorder:") postorder(root, simple_print) print() print() root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) # 1 2 3 4 5 print("level_order_1: ") level_order_1(root, simple_print) print() # 1 2 3 4 5 print("level_order_2: ") level_order_2(root, simple_print) print()
""" Queue An ordered list in which insertions are done at one end (rear) and deletions are done at other end (front) -- First In First Out (FIFO) or Last In Last Out (LILO). Example uses: CPU scheduling; Disk Scheduling Max. size of the queue must be defined prior to init. Time Complexities: enqueue(): O(1) dequeue(): O(1) isEmpty(): O(1) getSize(): O(1) """ class Queue(object): def __init__(self, limit=10): self.queue = [] self.front = None self.rear = None self.limit = limit self.size = 0 def isEmpty(self): return self.size <= 0 def isFull(self): return self.size >= self.limit def enqueue(self, data): if self.isFull(): return -1 else: self.queue.append(data) if self.front is None: self.front = self.rear = 0 else: self.rear = self.size self.size += 1 def dequeue(self): if self.isEmpty(): return None item = self.queue.pop(0) self.size -= 1 if self.size == 0: self.front = self.rear = 0 else: self.rear = self.size - 1 return item def getSize(self): return self.size def __str__(self): if len(self.queue) == 0: return "Empty Queue!" return ' '.join([str(s) for s in self.queue])
""" Print Binary Tree Print a binary tree in an m*n 2D string array following these rules: * The row number m should be equal to the height of the given binary tree. * The column number n should always be an odd number. * The root node's value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don't need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don't need to leave space for both of them. * Each unused space should contain an empty string "". * Print the subtrees following the same rules. Example 1: Input: 1 / 2 Output: [["", "1", ""], ["2", "", ""]] Example 2: Input: 1 / \ 2 3 \ 4 Output: [["", "", "", "1", "", "", ""], ["", "2", "", "", "", "3", ""], ["", "", "4", "", "", "", ""]] Example 3: Input: 1 / \ 2 5 / 3 / 4 Output: [["", "", "", "", "", "", "", "1", "", "", "", "", "", "", ""] ["", "", "", "2", "", "", "", "", "", "", "", "5", "", "", ""] ["", "3", "", "", "", "", "", "", "", "", "", "", "", "", ""] ["4", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]] Note: The height of binary tree is in the range of [1, 10]. """ from typing import List from math import floor from util import TreeNode as TreeNode def printTree(root: TreeNode) -> List[List[str]]: m = get_height(root) # n defined by m n = 2**m - 1 # odd number requirement arr = [["" for i in range(n)] for j in range(m)] middle = (n+1)/2 node_depth_pos = [(root, 1, middle)] for n, d, p in node_depth_pos: if n is not None: node_depth_pos.append((n.left, d+1, floor(p-middle/(2**d)))) node_depth_pos.append((n.right, d+1, floor(p+middle/(2**d)))) arr[d-1][int(p)-1] = str(n.data) return arr def get_height(root: TreeNode): if root is None: return 0 return max(get_height(root.left), get_height(root.right)) + 1 from util import Testing as t tests = t.Testing("Print Binary Tree") #Input: # 1 # / # 2 output = [["", "1", ""],["2", "", ""]] tree = TreeNode.TreeNode(1) tree.left = TreeNode.TreeNode(2) tests.addTest(output, printTree, tree) #Input: # 1 # / \ # 2 3 # \ # 4 output = [["", "", "", "1", "", "", ""], ["", "2", "", "", "", "3", ""], ["", "", "4", "", "", "", ""]] tree = TreeNode.TreeNode(1) tree.left = TreeNode.TreeNode(2) tree.left.right = TreeNode.TreeNode(4) tree.right = TreeNode.TreeNode(3) tests.addTest(output, printTree, tree) #Input: # 1 # / \ # 2 5 # / # 3 # / #4 output = [["", "", "", "", "", "", "", "1", "", "", "", "", "", "", ""], ["", "", "", "2", "", "", "", "", "", "", "", "5", "", "", ""], ["", "3", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["4", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]] tree = TreeNode.TreeNode(1) tree.left = TreeNode.TreeNode(2) tree.right = TreeNode.TreeNode(5) tree.left.left = TreeNode.TreeNode(3) tree.left.left.left = TreeNode.TreeNode(4) tests.addTest(output, printTree, tree) tests.run()
import math import random from astar import AStar class ShortestPath: def __init__(self, start, tasks, costs): self.tasks = tasks self.start = start self.costs = costs super().__init__() def path_cost(self, paths): i = 0 costs = 0 current_position = self.start for path in paths: cost = AStar( current_position[0], # x current_position[1], # y current_position[2], # direction path['coordinates'][0], path['coordinates'][1], self.costs ).process(show_cost=True) i += 1 costs += cost[0] current_position = ( cost[1][-1][0], cost[1][-1][1], cost[1][-1][2], ) return costs def crossover_cost(self, crossover): i = 0 costs = 0 current_position = self.start for path in crossover: cost = AStar( current_position[0], # x current_position[1], # y current_position[2], # direction path['coordinates'][0], path['coordinates'][1], self.costs ).process(show_cost=True) i += 1 costs += cost[0] current_position = ( cost[1][-1][0], cost[1][-1][1], cost[1][-1][2], ) return costs def mutate(self, path): key1 = random.randint(0, len(path) - 1) key2 = random.randint(0, len(path) - 1) while key2 == key1: key2 = random.randint(0, len(path) - 1) temp = path[key1] path[key1] = path[key2] path[key2] = temp return path def sort(self, population): return sorted(population, key=lambda x: x[0]) def get_shortest_path(self): tasks = self.tasks.copy() iteration_number = int(math.ceil(len(tasks) / 2)) crossover_number = int(math.ceil(len(tasks) / 3)) population = [] for l in range(len(tasks)): temp_tasks = random.sample(tasks, len(tasks)) population.append( (self.path_cost(temp_tasks), temp_tasks) ) population_length = len(population) for _ in range(iteration_number): used_keys = [] for _ in range(crossover_number): key1 = random.randint(0, len(population) - 1) while key1 in used_keys: key1 = random.randint(0, len(population) - 1) used_keys.append(key1) key2 = random.randint(0, len(population) - 1) while key2 in used_keys: key2 = random.randint(0, len(population) - 1) used_keys.append(key2) cross1 = (population[key1][0], population[key1][1]) cross2 = (population[key2][0], population[key2][1]) crossover = [] for i in range(iteration_number): crossover.append(cross1[1][i]) for elem in cross2[1]: if elem not in crossover: crossover.append(elem) population.append( (self.path_cost(crossover), crossover) ) mutation_key = random.randint(0, len(population) - 1) mutation_result = self.mutate(population[mutation_key][1]) population[mutation_key] = ( self.path_cost(mutation_result), mutation_result ) population = self.sort(population)[:population_length] return population[0][1]
print("How many time I have left If I live until 90 years old?") age = input("What is your current age? ") age = int(age) years_until_90 = 90 months_until_90 = years_until_90 * 12 weeks_until_90 = years_until_90 * 52 days_until_90 = years_until_90 * 365 current_age = age current_month = age * 12 current_weeks_lived = age * 52 current_days_lived = age * 365 #Days, weeks, years reminder year_remind = years_until_90 - current_age month_remind = months_until_90 - current_month weeks_remind = weeks_until_90 - current_weeks_lived days_remind = days_until_90 - current_days_lived print("------------------------------------------") print(f"You have {days_remind} days, {weeks_remind} weeks, {month_remind} months, and {year_remind} years left.")
import numpy class Solver(object): r"""Abstract Hamiltonian solver object. Implementations of Hamiltonian solvers should inherit from this object and define the method :py:meth:`step`. ``step`` defines how the implemented method performs a single time step of size `h`. Attributes ---------- None Methods ------- solve Contents -------- """ def __init__(self): pass def __repr__(self): return 'Abstract Hamiltonian solver.' def step(self, H, pn, qn, h): r"""Perform a single time step of the solver. Parameters ---------- H : Hamiltonian pn, qn : arrays The Hamiltonian and a solution at some time. h : double The size of the time step to take. Returns ------- array, array The values of `p` and `q` after a step of size `h`. .. note:: This method must be implemented in subclasses. """ raise NotImplementedError('Implement the single-step algorithm.') def solve(self, H, p0, q0, t): r"""Solve for `p(t)` and `q(t)` with the Hamiltonian `H`. Parameters ---------- H : Hamiltonian p0 : array q0 : array The initial condition at time ``t0 = t[0]``. t : double or array The times at which to compute `p(t)` and `q(t)`. Returns ------- arrays Return the arrays, :math:`p(t), q(t)` for the given `t`. """ t = numpy.array(t) N = len(t) d = H.dim() # initialize the solution arrays p = numpy.zeros((N,d)) q = numpy.zeros((N,d)) p[0,:] = p0 q[0,:] = q0 # step for each time appearing in the array for n in range(1,N): h = t[n] - t[n-1] p[n], q[n] = self.step(H, p[n-1], q[n-1], h) return p, q
x = 5 b = 10 def set_y(y): # you can reference b that outter scope here # but cannot reassign it because it not local scope # if you do it (b = 10) it wiil new assign local function scope b # that is not the same as b outside it called shadow or name hiding # description is below a = b print('inner a is', a) # if we use global y here # will error because parameter y in set_y(y) will always win global global x # Python doesn't have variable declarations, so it has to figure out the scope of variables itself. # It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local. # x += 1 x = y y = x # can defind global z in function without defind in outter function before # and can be reference global z outside function as well. global z z = 99 print('inner x', x) print('inner y', y) print('x before set', x) set_y(10) print('x after set', x) print('z is ', z) while x < 6: print(x) x += 1 print('Outter x', x)
# Import pandas import pandas as pd # Read 'Bronze.csv' into a DataFrame: bronze bronze = pd.read_csv('Bronze.csv') # Read 'Silver.csv' into a DataFrame: silver silver = pd.read_csv('Silver.csv') # Read 'Gold.csv' into a DataFrame: gold gold = pd.read_csv('Gold.csv') # Print the first five rows of gold print(gold.head()) # Import pandas import pandas as pd # Create the list of file names: filenames filenames = ['Gold.csv', 'Silver.csv', 'Bronze.csv'] # Create the list of three DataFrames: dataframes dataframes = [] for file in filenames: dataframes.append(pd.read_csv(file)) # Print top 5 rows of 1st DataFrame in dataframes print(dataframes[0].head()) # Use list comprehensive dataframes2 = [pd.read_csv(file) for file in filenames] print(dataframes2[0].head())
""" This is function in helpers package """ # use docstring with extract_lower_sorted.__doc__ # use doctest with python3 -m doctest src/helpers_pack/helpers.py def extract_lower_sorted(name): # intent doctest to fail # correct is ['a', 'c', 'd', 'f'] """ Here is description of extrack lower with sorted and have test >>> extract_lower_sorted('BcdEfaG') ['a', 'c', 'd', 'f', 'x'] """ return list(sorted(filter(str.islower, name))) def extract_upper_sorted_reversed(name): return list(sorted(filter(str.isupper, name), reverse=True))
import pdb import json import requests import numpy as np from scipy.spatial import distance def los_to_earth(position, pointing): """Find the intersection of a pointing vector with the Earth Finds the intersection of a pointing vector u and starting point s with the WGS-84 geoid Args: position (np.array): length 3 array defining the starting point location(s) in meters pointing (np.array): length 3 array defining the pointing vector(s) (must be a unit vector) Returns: np.array: length 3 defining the point(s) of intersection with the surface of the Earth in meters """ a = 6371008.7714 b = 6371008.7714 c = 6356752.314245 x = position[0] y = position[1] z = position[2] u = pointing[0] v = pointing[1] w = pointing[2] pdb.set_trace() value = -a**2*b**2*w*z - a**2*c**2*v*y - b**2*c**2*u*x radical = a**2*b**2*w**2 + a**2*c**2*v**2 - a**2*v**2*z**2 + 2*a**2*v*w*y*z - a**2*w**2*y**2 + b**2*c**2*u**2 - b**2*u**2*z**2 + 2*b**2*u*w*x*z - b**2*w**2*x**2 - c**2*u**2*y**2 + 2*c**2*u*v*x*y - c**2*v**2*x**2 magnitude = a**2*b**2*w**2 + a**2*c**2*v**2 + b**2*c**2*u**2 if radical < 0: raise ValueError("The Line-of-Sight vector does not point toward the Earth") d = (value - a*b*c*np.sqrt(radical)) / magnitude if d < 0: raise ValueError("The Line-of-Sight vector does not point toward the Earth") return np.array([ x + d * u, y + d * v, z + d * w, ]) pdb.set_trace() val_45555 = requests.get("http://localhost:5000/sat/position/45555") val_44760 = requests.get("http://localhost:5000/sat/position/44760") l1=np.array(val_45555.json()['pos_eci']) l2=np.array(val_44760.json()['pos_eci']) v = (l1-l2) n = np.linalg.norm(v) v=v/n for d in range(0,6000,10): l3=l2+d*v dist=distance.euclidean(l3,l1) if dist > dist_old: print(dist_old) sys.exit(-1) s="{0},{1},{2}".format(l3,l1,dist) print(s) pdb.set_trace() los_to_earth(l1,v)
# search if an e-mail address is in a string: import re input = input("enter a string") m = re.search('[^@]+@[^@]+\.[^@]+',input) if m: print("String found.") else: print("No String found.")
import re na = input("Enter a string:") res = re.findall(r"python",na) print(res) print(len(res)) print("=================================================================") if res == None: print("match not found") else: print("match found:",res) print(len(res)) print("that's it")
# -*- coding: UTF-8 -*- li = ["a", "b", "mpilgrim", "z", "example"] print li print li[1] li.append("new") print li li.insert(2, "new") print li li.extend(["two", "elements"]) print li print li.index("example") print "c" in li print "example" in li li.remove("a") print li li.remove("new") # 删除首次出现的一个值 print li print li.pop() # pop 会做两件事: 删除 list 的最后一个元素, 然后返回删除元素的值。 print li li = li + ['example', 'new'] print li li += ['two'] print li li = [1, 2] * 3 print li params = {"server": "mpilgrim", "database": "master", "uid": "sa", "pwd": "secret"} print ["%s=%s" % (k, v) for k, v in params.items()] print ";<-->;".join(["%s=%s" % (k, v) for k, v in params.items()]) li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret'] print li s = ";".join(li) print s print s.split(";") print s.split(";", 1) li = [1, 9, 8, 4] li.sort() print li print [elem * 2 for elem in li] li = [elem * 2 for elem in li] print li params = {"server": "mpilgrim", "database": "master", "uid": "sa", "pwd": "secret"} print params.keys() print params.values() print params.items() print [k for k, v in params.items()] print [v for k, v in params.items()] print ['%s?%s' %(k, v) for k, v in params.items()] print ["%s=%s" % (k, v) for k, v in params.items()] # list过滤 li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"] print li print [elem for elem in li if len(elem) > 1] print [elem for elem in li if len(elem) == 1] print [elem for elem in li if elem != "b"] print [elem for elem in li if li.count(elem) == 1]
#!/usr/bin/python # -*- coding: UTF-8 -*- """ 题目:有5个人坐在一起, 问第五个人多少岁?他说比第4个人大2岁。 问第4个人岁数,他说比第3个人大2岁。 问第三个人,又说比第2人大两岁。 问第2个人,说比第一个人大两岁。 最后问第一个人,他说是10岁。 请问第五个人多大? 程序分析:利用递归的方法,递归分为回推和递推两个阶段。要想知道第五个人岁数,需知道第四人的岁数,依次类推,推到第一人(10岁),再往回推。 """ def age(n): if n == 1: c = 10 else: c = age(n - 1) + 2 return c print age(5)
import csv import re from geocoder.fuzzymatching import find_match from geocoder.preprocessing import extended_capwords class Addresses: """Collection of address points to geocode. Since this class belongs to a group of piped generators, it conducts the preprocessing of text data on the fly. As argument(s) pass either: – a column name containing a full address (e.g. address='address') – or column names with street and number (e.g. street='street', number='number') Args: source_data (generator): an iterator containing source data. address (str): col name in a CSV file containing address street (str, otpional): col name in a CSV file containing street number (str): col name in a CSV file containing number Yields: address (str): Address point to be geocoded. """ def __init__(self, source_data, **params): self._addresses = source_data self._address = params.get('address') self._street = params.get('street') self._number = params.get('number') def __iter__(self): """Iterator protocol, also conducts on the fly text processing.""" for row in self._addresses: if self._address: address = getattr(row, self._address) elif self._street and self._number: address = f'{getattr(row, self._street)}\ {getattr(row, self._number)}' else: raise ValueError("You must provide either address " "or street and number as arguments.") address = self._capitalize(address) address = self._truncate_street_prefix(address) address = self._truncate_address_details(address) if self._valid_address(address): address = address else: address = '' yield address def __repr__(self): return (f'{self.__class__.__name__} class') def _valid_address(self, address: str) -> str: """Check if the address contains any digits and at least 3 letters. Make sure none digit at the address beggining is counted as relevant (common case like "1 Maja" street). """ return any(char.isdigit() for char in address[1:])\ and sum(int(char.isalpha()) for char in address) >= 3 def _capitalize(self, address: str) -> str: """Capitalize words excluding indicated expressions""" exceptions = [ 'go', 'i', 'II', 'III', ] return extended_capwords(address, exceptions) def _truncate_street_prefix(self, address: str) -> str: """Remove prefixes indicating street""" outcome = address.replace('Ulica ', '')\ .replace('Ul. ', '')\ .replace('Ul ', '') return outcome def _get_separators(self): """"Helper function to build a string with separators. They are Polish-specific, they refer to short names of flats, rooms, buildings etc., and have been collected from case studies. """ return '|'.join([ '/', ' Lokal\\. ', ' Lok\\. ', ' Lok\\.', ' Lok ', '\\.lok\\.', '\\.lok', ' M\\. ', ' M\\.', ' M ', '\\.m\\.', '\\.m', 'M\\d', '\\-.{1,2}$', ' Bud\\.', ]) def _truncate_address_details(self, address: str) -> str: """Remove trailing parts of the address, e.g. a flat number""" return re.split(self._get_separators(), address)[0].strip() class Coordinates: """Collection of coordinate points used for geocoding. Args: source_data (generator): a generator with source data street (str): street name variable name (default is 'street') number (str): facility number variable name (default is 'number') lat (str): latitude variable name (default is 'lat') lon (str): longitude variable name (default is 'lon') Attributes: coordinates (dict): a collection of coordinate points. """ def __init__(self, source_data, street='street', number='number', lat='lat', lon='lon'): self.coordinates = self._preprocess_data(source_data, street, number, lat, lon) def _preprocess_data(self, source_data, street, number, lat, lon): output = {} for row in source_data: street_name = getattr(row, street) street_name = self._truncate_square_prefix(street_name) num = getattr(row, number).lower() address_point = f'{street_name} {num}' lat_lon = (getattr(row, lat), getattr(row, lon)) output[address_point] = lat_lon return output def _truncate_square_prefix(self, address: str) -> str: """ Abbreviate 'square' in the address to keep the source data consistent. """ return address.replace('Pl.', 'Plac') def geocode(addresses, coordinates, fuzzy_set, output_file): successful = 0 missing = 0 with open(output_file, 'w') as file: csv_writer = csv.writer(file) csv_writer.writerow(['original_address', 'match', 'coordinates']) for address in addresses: try: # try exact match with preprocessing and prefix removal result = coordinates.coordinates[address] output = [address, address, result] successful += 1 except KeyError: try: # (https://pypi.org/project/fuzzy-match/) match = find_match(address, fuzzy_set, return_top_match=True) result = coordinates.coordinates[match] output = [address, match, result] successful += 1 except (KeyError, TypeError): output = [address, '', 'Missing or wrong address – no match found'] missing += 1 csv_writer.writerow(output) return successful, missing
day=int(input("Day:")) pop= int(input("Population:")) i=int(0) pr=int(input("%:"))/100 print ("День Популяция") while i<day: print(i, " ",round(pop,5)) i+=1 pop=pop*(1+pr)
count = 0 while True: word = input("Enter a word. please type 'quit' to stop: ") count += 1 print(count) if word == "quit": break else: continue
import random while True: first_roll = random.randint(1,6) print(f"Your first roll and point value is: {first_roll}") count = 0 while True: next_roll = random.randint(1,6) print(f"Your next roll is: {next_roll}") count += 1 if next_roll == first_roll: print(f"It took {count} times to get your point again.") break else: continue answer = input("Do you want to play again (Y/N): ") if answer == "Y": continue else: break
while True: percentage = int(input("Enter a percentage: ")) if 100 >= percentage >= 0: print("Thank you") break else: print("Invalid percentage") continue
import string vowels = "aeiou" def isLetter(c): return (c in string.ascii_letters) def isVowel(c): result = (c in vowels) if len(c) != 1: for l in c[1:]: result = result and (l in vowels) return result def isConsonant(c): result = (c[0] in string.ascii_letters) and (c[0] not in vowels) if len(c) != 1: for l in c[1:]: result = result and (l in string.ascii_letters) and (l not in vowels) return result def syllablize(s): cur_syllable = "" syllables = [] n = len(s) i = 0 while i < n: c = s[i] if cur_syllable != "": if i < n-1 and not isLetter(s[i+1]): cur_syllable += c elif isVowel(c): if isConsonant(cur_syllable) or isVowel(cur_syllable[-1]): cur_syllable += c else: syllables.append(cur_syllable) cur_syllable = c elif isConsonant(c): # syllable must end with a vowel if cur_syllable == "" or isVowel(cur_syllable[-1]) and (i < n -1 and (not isVowel(s[i+1]) and s[i+1] != 'y')) or cur_syllable[-1] == c: cur_syllable += c elif isLetter(c): if cur_syllable[-1] in "nmrl" and i < n-1 and s[i+1] in 'edsh' and i < n-2 and not isLetter(s[i+2]): cur_syllable += c cur_syllable += s[i+1] i += 1 elif c == 'h' and cur_syllable[-1] in "stcpwg": cur_syllable += c # elif c == 't' and cur_syllable[-1] in "srnm" and i == n-1: # cur_syllable += c elif c == 'r' and isConsonant(cur_syllable[-1]): cur_syllable += c elif (c == 'r' and i < n-3 and s[i+1] == "e" and s[i+2] in "ds" and not isLetter(s[i+3])): cur_syllable += c cur_syllable += s[i+1] cur_syllable += s[i+2] i += 2 elif (c == 'r' and i < n-2 and s[i+1] == "e" and not isLetter(s[i+2])): cur_syllable += c cur_syllable += s[i+1] i += 1 elif cur_syllable[-1] == 's' and ( (i < n-1 and not isLetter(s[i+1])) or ( i > 1 and not isLetter(s[i-2])) ) : cur_syllable += c else: syllables.append(cur_syllable) cur_syllable = c else: if cur_syllable != "": syllables.append(cur_syllable) cur_syllable = "" elif isLetter(c): cur_syllable = c i += 1 return syllables def formatPrint(s, x = 10): i = 0 j = 0 n = len(s) while i < n: if j == 10: print(s[i]) j = 0 else: print(s[i], end=" ") j += 1 i += 1 s = "The Axis advance halted in 1942 when Japan lost the critical Battle of Midway, near Hawaii, and Germany was defeated in North Africa and then, decisively, at Stalingrad in the Soviet Union. In 1943, with a series of German defeats on the Eastern Front, the Allied invasion of Sicily and the Allied invasion of Italy which brought about Italian surrender, and Allied victories in the Pacific, the Axis lost the initiative and undertook strategic retreat on all fronts. In 1944, the Western Allies invaded German-occupied France, while the Soviet Union regained all of its territorial losses and invaded Germany and its allies. During 1944 and 1945 the Japanese suffered major reverses in mainland Asia in South Central China and Burma, while the Allies crippled the Japanese Navy and captured key Western Pacific islands." formatPrint(syllablize(s.lower()))
import time class TimeStamp(): def __init__(self): """A timestamp class Time string is accurate to the seconds. """ self.seconds_since_epoch = time.time() struct = time.localtime(self.seconds_since_epoch) self.time_str = time.strftime("%Y%m%d-%H%M%S", struct) def __str__(self): return self.time_str def elapsed(self): """Time elapsed in seconds since creation of this instance """ return time.time() - self.seconds_since_epoch
import random, bisect, math # library implementing a random variable # TODO: absorb testing.py random.seed(1) EPSILON = 10**-3 # permissible distance from 1 ITERS = 10**6 # iterations for emprical expected value ### normalization and verification methods def norm(l: list, f: float=None) -> list: """ Normalizes a list into a pmf by dividing by its sum. """ s = sum(l) if f is None else f return [x/s for x in l] def norm_cmf(l: list) -> list: """ Normalizes a list into a cmf by dividing by its max. """ return norm(l, max(l)) def nonneg(l: list) -> bool: """ Whether all the values in a list are positive. """ return all(map(lambda x: x >= 0, l)) def diff(x: float, y: float, tol: float=EPSILON) -> bool: """ Whether two numbers are sufficiently close. """ return abs(x - y) < tol def pmf(l: list, tol: float=EPSILON) -> bool: """ Whether a list can be interpreted as a pmf. """ return nonneg(l) and diff(sum(l), 1, tol) def cmf(l: list, tol: float=EPSILON) -> bool: """ Whether a list can be interpreted as a cmf. """ return nonneg(l) and l == sorted(l) and diff(l[-1], 1, tol) ### random variable def query(prefix: list, i: int, j: int) -> float: """ Finds the sum of a list between two indexes. """ return prefix[j + 1] - prefix[i] def prefix_sum(l: list) -> list: """ Returns the prefix sum of l. """ prefix = [0]*(len(l) + 1) for i in range(len(l)): prefix[i + 1] = prefix[i] + l[i] return prefix class RandomVariable: """ A random variable. """ def __init__(self, X: list, p: list, name: str="rv", is_cmf: bool=False, normalize: bool=False) -> None: p = (norm_cmf if is_cmf else norm)(p) if normalize else p self.X, self.p, self.name = X, p, name # list of values, probabilities if isinstance(X, RandomVariable): # inherit attributes for efficiency for attr in ["__len__", "__iter__", "__getitem__", "D"]: setattr(self, attr, getattr(X, attr)) else: self.D = {x: i for i, x in enumerate(X)} # value to index assert sorted(X) == list(X), "support set must be sorted" if is_cmf: assert len(X) == len(p) - 1, "values not the same length as cmf" assert cmf(p), "not a valid cmf" self.p, self.F = [p[i + 1] - p[i] for i in range(len(X))], p else: assert len(X) == len(p), "values not the same length as pmf" assert pmf(p), "not a valid pmf" self.F = prefix_sum(p) # cmf self.ev = prefix_sum([x*p for x, p in zip(self, self.p)]) ### Python "magic" class methods def __repr__(self) -> str: return f"RandomVariable({self.X}, {self.p})" def __str__(self) -> str: return f"RandomVariable {self.name}: \n\ mean = {self.E():.3f} +/- {self.std():.3f} (std)" def __len__(self) -> int: return len(self.X) def __iter__(self): return self.X.__iter__() def __getitem__(self, i: int) -> float: return self.X[i] def __call__(self, k: float) -> float: return self.pmf(k) ### properties intrinsic to a random variable def pmf(self, u: float) -> float: """ Finds the pmf at a value in/not in the underlying r.v. """ return self.p[self.D[u]] if u in self.D else 0 def cmf(self, u: float) -> float: """ Finds the cmf at a value in/not in the underlying r.v. """ # use F if u is in the range of the r.v., otherwise binary search return self.F[self.D[u] + 1] if u in self.D else \ self.F[bisect.bisect(self.X, u)] ### transformations def transform(self, f): """ Returns a new random variable transformed by a given function. """ freq = {} for x in self: y = f(x) freq[y] = freq.get(y, 0) + self.pmf(x) return RandomVariable(*map(list, zip(*sorted(freq.items())))) def map(self, f): """ Returns a new random variable with probabilities given by f. """ return RandomVariable(self, list(map(f, self))) ### probability theory statistics def E(self, f=lambda x: x) -> float: """ Expected value of a pmf represented by a list. """ return sum(f(x)*p for x, p in zip(self, self.p)) def Var(self) -> float: """ Var[X] = E[(x - u)^2] = E[X^2] - E[x]^2. """ return self.E(lambda x: x*x) - self.E()**2 def std(self) -> float: """ sigma^2 = Var[x] so sigma = standard deviation = sqrt(Var[X]). """ return math.sqrt(self.Var()) def range(self) -> float: """ Maximum element minus the minimum element. """ return self[-1] - self[0] ### miscellaneous def capped(self, u: float) -> float: """ Returns self.E(lambda x: max(x, u)) in O(log n). """ i = bisect.bisect(self, u) return u*self.F[i] + query(self.ev, i, len(self.X) - 1) ### sampling def sample(self) -> float: """ Samples a value from a random variable. """ return self[bisect.bisect(self.F, random.random()) - 1] def E(rv: RandomVariable, iters: int=ITERS) -> float: """ Expected value by repeatedly sampling a random variable. """ f = rv.sample if hasattr(rv, "sample") else rv return sum(f() for _ in range(iters))/iters if __name__ == "__main__": X = [ 1, 5, 10, 15, 16, 20, 30, 35, 50, 100] p = [0.05, 0.08, 0.1, 0.12, 0.17, 0.22, 0.1, 0.1, 0.05, 0.01] rv = RandomVariable(X, p) print(rv, rv(10)) print(len(rv), min(rv), max(rv), sum(rv)) print(sum(x*x for x in rv)) print(rv[1]) print(rv.E(), rv.Var(), rv.std(), rv.range()) print(E(rv), rv.sample(), rv.sample(), rv.sample()) X = [ -2, -1, 1, 2, 3] p = [0.1, 0.2, 0.5, 0.1, 0.1] rv = RandomVariable(X, p) print(repr(rv.transform(lambda x: x*x)))
def readfile(): li=[] file_name="UProducts.csv" file=open(file_name,"r") for line in file.readlines(): line li.append(line.split(",")) file.close() li.sort() return li def crate_alphabet_list(): master_list=[] for temp in range(0,25): master_list.append([]) return master_list def index(temp_string): return ord(temp_string) - ord("A") def insert_master_list(): file_list=readfile() master_list=crate_alphabet_list() print(master_list) for line in range(0,len(file_list)): char=file_list[line][0][0] unicode_num=index(char) master_list[unicode_num].append(file_list[line]) print(master_list) for temp in range(0,len(master_list)): master_list[temp].sort() return master_list master_list=insert_master_list() search=input("Enter full name which you want to search ") temp_num=index(search[0]) master_list[temp_num] for a in range(0,len(master_list[temp_num])): if search in master_list[temp_num][a]: print('the position of what you want t search is %i in [%s] list'% (a+1,search[0]) )
""" Write a Python script to convert Fahrenheit to Celsius and Celsius to Fahrenheit. Celcius Formula: Celsius = (Fahrenheit - 32) / (9 / 5) Fahrenheit Formula: Fahrenheit = Celsius * 9 / 5 + 32 Prompt the user to enter a Fahrenheit / Celsius value and then perform the calculations. """ def fahrenheit_to_celsius(): fahrenheit=int(input("Enter the Fahrenheit :")) celsius =(fahrenheit-32) /(9/5) print('celsius is ',celsius) def celsius_to_fahrenheit(): celsius=int(input("Enter the Celsius :")) fahrenheit =celsius*9/5+32 print('fahrenheit is ',fahrenheit) fahrenheit_to_celsius() celsius_to_fahrenheit()
x,y = input().split() x,y=int(x),int(y) x = x ^ y y = x ^ y x = x ^ y print(x,y)
number=int(input()) result=1 for i in range(1,number+1): result=result*i print (result)
from tkinter import * from turtle import * from PIL import Image, ImageTk, ImageFilter import time import random bullets=[] class Ball: def __init__(self, canvas, size, color, x, y, xspeed, yspeed): self.x = x self.y = y self.color = color self.size = size self.xspeed = xspeed #1초에 x-dir으로 움직이는 속도 self.yspeed = yspeed self.canvas = canvas self.id = canvas.create_oval(x, y, x+size, y+size, fill=color) def move(self): self.canvas.move(self.id, self.xspeed, self.yspeed) (x1, y1, x2, y2) = self.canvas.coords(self.id) #현재 위치 반환 (self.x, self.y) = (x1, y1) if x1 <=0 or x2 >= w: self.xspeed = -self.xspeed if y1 <=0 or y2 >= h: self.yspeed = -self.yspeed def coord_location(self): (x1, y1, x2, y2) = self.canvas.coords(self.id) #현재 위치 반환 (self.x, self.y) = (x1, y1) def fire(event): missle = Ball(canvas, 10, "red",10,300,20,0) bullets.append(missle) # create window & canvas w = 800 h = 400 window = Tk() canvas = Canvas(window, width=w, height=h) canvas.pack() canvas.bind("<Button-1>", fire) img = PhotoImage(file="car.gif") # shooter object img = img.subsample(5, 5) canvas.create_image(10,300,anchor=NW, image=img) ballT = Ball(canvas, 40,"red",500,200,0,5)# target ball timer=0 # practice3: # need to update on handling collision of bullets and ballT while True: for b in bullets: b.move() b.coord_location if (b.x + b.size) >= w: canvas.delete(b.id) bullets.remove(b) ballT.move() ballT.coord_location if ((b.x >= ballT.x-ballT.size and b.x <= ballT.x+ballT.size) or \ (b.y >= ballT.y-ballT.size and b.y <= ballT.y+ballT.size)): print("targeted!!") canvas.delete(b.id) bullets.remove(b) canvas.delete(ballT.id) bullets.remove(ballT) window.update() time.sleep(0.03) timer+=1 if timer>=500: window.destroy() print("timeout!!") break; # practice2: # try randomly creating n개의 balls and bouncing them randomly color_list=["red","orange","yellow","green","blue","purple","navy","black"] ball_list=[] timer=0 for i in range(100): color = random.choice(color_list) size = random.randint(1,50) x=random.randint(1,w) y=random.randint(1,h) xspeed=random.randint(5,20) yspeed=random.randint(5,20) ball_list.append(Ball(canvas, size, color, x, y, xspeed, yspeed)) while True: for ball in ball_list: ball.move() window.update() time.sleep(0.03) timer+=1 if timer>=300: window.destroy() break; # practice1: # practice creating and printing ball information ballS = Ball(30,"green",-100,0,10,0) ballT = Ball(canvas, 30,"red",0,0,10,0) print("target ball") print(ballT.color) print(ballT.size) print(ballT.x) print(ballT.y) print("shooting ball") print(ballS.color) print(ballS.size) print(ballS.x) print(ballS.y)
""" What is the most interesting/funny/cool thing(s) about Python that you learned from this class or from somewhere else. You can use code or a short paragraph to illustrate it. """ """ I find lambdas, or anonymous functions, to be really useful when attempting complex functions on large lists of data, or functions that require other functions. For example, I used a lambda expression to sort dictionary values by their keys. Here is an example: Suppose we have a dictionary where each key, a name, has a value that is an integer, an age. E.g. names = { 'bob': 50 'sally': 28 'tim': 15 } How would we sort this by their age? One method is to use lambdas, as follows: sorted_names = sorted(names.items(), key = lamda kv: kv[1]) Lamdas allow us to use a short function when necessary without defining them, hence an "anonymous" function. A common use for anonymous functions are when you use a function like map() of filter(). However, you can usually accomplish the same thing using list comprehenseion, which is another cool thing you can do in python! E.g. filter = [x for x in list if x > 0] With list comprehension, we don't have to always write a for loop to accomplish something. It makes the code quite elegent and easy to understand. By the way, here is a joke I saw on reddit a while back for a sorting algorithm: In Stalin_sort, you iterate down a list of elements checking if they're in order. If they are out of order they get elmintaed. By the end you have a sorted list. """
__all__ = ["Natural"] def remove_zeros(s): while s[0] == '0': s.pop(0) return s class Natural(): # _dig_n - количество разрядов в числе # _number - натуральное число, представленое в виде перевёрнутого массива цифр (начиная с младших разрядов) def __init__(self, n: str = None): if not n: self._number = [0] self._dig_n = 1 elif not Natural.isNatural(n): raise Exception("number passed to \"Natural\" class constructor is invalid") # Число состоит из нулей elif n == "0" * len(n): self._number = [0] self._dig_n = 1 else: # Убираем все нули n = remove_zeros(n) self._number = [int(i) for i in n[::-1]] self._dig_n = len(self._number) def __str__(self): if self._dig_n != 0: # Перевод списка в строку return ''.join([str(i) for i in reversed(self._number)]) else: return "0" @staticmethod def isNatural(s): for i in s: if not ('0' <= i and i <= '9'): return False return True def __gt__(self, num): '''Перегрузка оператора ">". Выполнил и оформил Шабров Иван''' # Если количетсво разрядов self больше num if self._dig_n > num._dig_n: return True # Если количество разрядов self меньше num elif self._dig_n < num._dig_n: return False # Если количество разрядов одинаковое else: # Поочередно сравниваем разряды каждого числа for i in range(-1, -(self._dig_n + 1), -1): if self._number[i] > num._number[i]: return True elif self._number[i] < num._number[i]: return False return False def __eq__(self, num): '''Перегрузка оператора "==". Выполнила и оформила Реброва Юлия''' # Если количество разрядов не совпадает if self._dig_n != num._dig_n: return False # Последовательно проверяем каждый разряд for i in range(num._dig_n): if self._number[i] != num._number[i]: return False return True def __lt__(self, num): '''Перегрузка оператора "<". Оформил Шабров Иван''' # Если количетсво разрядов self меньше num if self._dig_n < num._dig_n: return True # Если количетсво разрядов self больше num elif self._dig_n > num._dig_n: return False else: # Поочередно сравниваем разряды каждого числа for i in range(-1, -(self._dig_n + 1), -1): if self._number[i] < num._number[i]: return True elif self._number[i] > num._number[i]: return False return False '''МОДУЛИ NATURAL''' def compare(self, num): '''Модуль N-1 COM_NN_D. Выполнил и оформил Шабров Иван''' if self > num: return 2 elif self < num: return 1 else: return 0 def is_zero(self): '''Модуль N-2 NZER_N_B. Выполнила и оформила Реброва Юлия''' if self == Natural("0"): return True else: return False def increment(self): '''Модуль N-3 ADD_1N_N. Выполнил и оформил Проскуряк Влад''' res = Natural(str(self)) # Если число единиц не превысит 9, то прибавление 1 и окончание модуля if (res._number[0] + 1) < 10: res._number[0] = res._number[0] + 1 else: i = 0 # Прибавление 1 и в случае необходимости поднятие по разрядам while (i < res._dig_n) and ((res._number[i] + 1) == 10): res._number[i] = 0 i = i + 1 # Прибавление к высшему разряду единицу или добавление нового разряда if (i < res._dig_n): res._number[i] = res._number[i] + 1 else: res._dig_n = res._dig_n + 1 res._number.append(1) return res def __add__(self, num): '''Модуль ADD_NN_N. Выполнил и оформил Жексенгалиев Адиль''' res = Natural() # Находим наименьшее количество разрядов среди self и num if self.compare(num) == 1: res._dig_n = num._dig_n n = self._dig_n else: res._dig_n = self._dig_n n = num._dig_n # Добавляем нули в искомое число res._number = [0 for i in range(res._dig_n)] # Складываем числа до n - наименьшего количества разрядов i = 0 while i < n: # Получаем цифру i-того разряда x = res._number[i] + self._number[i] + num._number[i] # Если после сложения получилось число, а не цифра if x >= 10: res._number[i] = x - 10 # Если x - последний разряд, то расширяем массив чисел if (i == res._dig_n - 1): res._number.append(0) res._dig_n += 1 # Прибавляем единицу к следующему разряду res._number[i + 1] += 1 # Если х - цифра else: res._number[i] += self._number[i] + num._number[i] i += 1 # Для случая когда числа имеют разные разряды j = 0 # m - количество разрядов, не добавленных в искомое число m = abs(self._dig_n - num._dig_n) compare = self.compare(num) while j < m: # Если self больше num if compare == 2: res._number[j + i] += self._number[j + i] # Если num больше self else: res._number[j + i] += num._number[j + i] # Если цифра равна 10, то приравниваем её к нулю if res._number[j + i] == 10: res._number[j + i] = 0 # Если складывается последний разряд if (j + i == res._dig_n - 1): res._dig_n += 1 res._number.append(0) # Следующая цифра увелчиивается на 1 res._number[j + i + 1] += 1 j = j + 1 return res def __sub__(self, num): '''Модуль N-5 SUB_NN_N. Выполнил и оформил Солодков Никита''' t = self.compare(num) # Если self больше num if t == 2: big = self less = num n = num._dig_n m = self._dig_n # Если self меньше num, то вычитание нельзя произвести elif t == 1: raise Exception("unable to substitute greater natural number from less natural number") # Если числа равны else: return Natural("0") res = Natural() res._dig_n = big._dig_n res._number = [0 for i in range(big._dig_n)] # Вычитаем, начиная со старшего разряда i = m - 1 while i > n - 1: res._number[i] = big._number[i] i -= 1 # Вычитаем ненулевые разряды while i >= 0: x = big._number[i] - less._number[i] # Если цифра меньше 0 if x < 0: # Поиск разряда у которого можно "занять" единицу j = i + 1 while res._number[j] == 0: j += 1 # "Занимаем" единицу res._number[j] -= 1 n = i # Вычитаем единицу из нулевых разрядов z = j - 1 while z > n - 1: if res._number[z] == 0: res._number[z] = 9 z -= 1 res._number[i] = x + 10 else: res._number[i] = x i -= 1 # Удаляем незначащие нули i = m - 1 while res._number[i] == 0: res._dig_n -= 1 del res._number[i] i -= 1 return res def mul_d(self, digit: int): '''Модуль N-6 MUL_ND_N. Выполнил и оформил Цыганков Дмитрий''' # Проверка цифры if digit < 0: raise Exception("unable to multiple a natural number by a negative digit") elif digit > 10: raise Exception("digit cannot be greater than 10") # Проверка на ноль if self.is_zero() or digit == 0: return Natural("0") # self_c - искомое число # temp - остаток после умножения разряда на число. self_c = Natural(str(self)) temp = 0 for j in range(self_c._dig_n): # Если после предыдущего шага есть остаток if temp != 0: # Если умножение очередной цифры числа оказалось больше 10 if self_c._number[j] * digit + temp >= 10: temp_n = self_c._number[j] self_c._number[j] = (self_c._number[j] * digit + temp) % 10 temp = (temp_n * digit + temp) // 10 else: self_c._number[j] = self_c._number[j] * digit + temp temp = 0 # Если умножение очередной цифры числа оказалось больше 10 elif self_c._number[j] * digit >= 10: temp_n = self_c._number[j] self_c._number[j] = (self_c._number[j] * digit) % 10 temp = (temp_n * digit) // 10 else: self_c._number[j] = self_c._number[j] * digit temp = 0 # Если на последнем шаге остался остаток, то записываем его в 1 позицию if temp != 0: self_c._number.insert(self_c._dig_n, temp) self_c._dig_n += 1 return self_c def mul_k(self, tenpow: int): '''Модуль N-7 MUL_Nk_N. Выполнил и оформил Цыганков Дмитрий''' # Проверка на неотрицательность if tenpow < 0: raise Exception("unable to raise a natural number to a negative power") # Проверка на ноль if self.is_zero(): return Natural("0") self_c = Natural(str(self)) # Добавляем ноль tenpow раз for i in range(tenpow): self_c._number.insert(i, 0) self_c._dig_n += 1 return self_c def __mul__(self, x): '''Модуль N-8 MUL_NN_N. Выполнил и оформил Трибунский Алексей''' res = Natural("0") # Проходим по всем цифрам второго множителя for i in range(x._dig_n): # К res прибавляем первый множитель, умноженный на цифру второго множителя и на 10^i res += self.mul_d(x._number[i]).mul_k(i) return res def sub_dn(self, dig, num): '''Модуль N-9 SUB_NDN_N. Выполнила и оформила Реброва Юлия''' # Проверка цифры if dig < 0: raise Exception("unable to multiple a natural number by a negative digit") elif dig > 9: raise Exception("digit cannot be greater than 9") c = num.mul_d(dig) if self.compare(c) != 1: return self - c else: raise Exception("unable to substitute greater natural number from less natural number") def div_dk(self, num): '''Модуль N-10 DIV_NN_Dk. Выполнил и оформил Щусь Максим''' # Проверка на ноль if self.is_zero(): return 0, 0 elif num.is_zero(): raise Exception("unable to divide natural number by zero") if self.compare(num) == 0: return 1, 0 n1 = Natural(str(self)) n2 = Natural(str(num)) # k - первая цифра деления k = 0 if n1.compare(n2) == 1: less = n1 greater = n2 else: less = n2 greater = n1 # Номер позиции первой цифры от деления greater на less n3 = less while greater.compare(n3) == 2: k += 1 n3 = less.mul_k(k) k -= 1 n3 = less.mul_k(k) less = n3 # Находим цифру деления greater на less dig = 1 while greater.compare(n3) == 2: dig += 1 n3 = less.mul_d(dig) # Если n3 стало больше greater, то уменьшаем цифру деления на 1 if greater.compare(n3) != 0: dig -= 1 # Если оказалось, что цифра равна 10 if dig == 10: # Увеличиваем номер позиции цифра на 1, dig присваиваем 1 dig = 1 k += 1 return dig, k def __truediv__(self, num): '''Модуль N-11 DIV_NN_N. Выполнила и оформила Показацкая Арина''' # Проверка на ноль if self.is_zero(): return Natural("0") elif num.is_zero(): raise Exception("unable to divide natural number by zero") n1 = Natural(str(self)) n2 = Natural(str(num)) res = Natural() # Количество разрядов в результирующем числе res._dig_n = n1.div_dk(n2)[1] + 1 res._number = [0 for i in range(res._dig_n)] while n1.compare(n2) != 1: # Очередная цифра результата и номер позиции этой цифры a, b = n1.div_dk(n2) res._number[b] = a # Делитель, умноженный на 10 в степени b c = n2.mul_k(b) n1 = n1.sub_dn(a, c) # Удаляем нули после деления c = res._dig_n - 1 while c > 0 and res._number[c] == 0: res._number.pop(c) res._dig_n -= 1 c -= 1 return res def __mod__(self, num): '''Модуль N-12 MOD_NN_N. Выполнил и оформил Проскуряк Влад''' # Проверка на ноль if num.is_zero(): raise Exception("unable to find modulo by zero") res = Natural(str(self)) if self.compare(num) != 1: i = res / num # Частное от деления res = res - i * num # Вычитаем из делимого произведение частного на делитель и получаем остаток return res def gcf(self, num): '''Модуль N-13 GCF_NN_N. Выполнил и оформил Шабров Иван''' # Проверка на ноль if self.is_zero() and num.is_zero(): raise Exception("gcf of both zeros is undefined") n1 = Natural(str(self)) n2 = Natural(str(num)) # Алгоритм Евклида while (not n1.is_zero()) and (not n2.is_zero()): if n1.compare(n2) == 2: n1 = n1 % n2 else: n2 = n2 % n1 return n1 + n2 def lcm(self, num): '''Модуль N-14 LCM_NN_N. Выполнил и оформил Жексенгалиев Адиль''' # Проверка на ноль if self.is_zero(): if num.is_zero(): raise Exception("lcm of both zeros is undefined") else: raise Exception("lcm of a zero and a number is undefined") gcf = self.gcf(num) return (self * num) / gcf
#!/bin/env python #Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. # #You may assume that each input would have exactly one solution, and you may not use the same element twice. # #You can return the answer in any order. # #Example 1: #Input: nums = [2,7,11,15], target = 9 #Output: [0,1] #Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. # #Example 2: #Input: nums = [3,2,4], target = 6 #Output: [1,2] # #Example 3: #Input: nums = [3,3], target = 6 #Output: [0,1] class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ # Slower and less memory # Runtime: 6576 ms, faster than 8.81% of Python online submissions for Two Sum. # Memory Usage: 14.2 MB, less than 87.07% of Python online submissions for Two Sum. # for i,a in enumerate(nums): # diff = target - a # for j, b in enumerate(nums): # if i == j: # continue # if b == diff: # return [i, j] # Faster and more memory # Runtime: 61 ms, faster than 73.95% of Python online submissions for Two Sum. # Memory Usage: 14.8 MB, less than 5.36% of Python online submissions for Two Sum. # indexes = # { # 5: [1,2,3] # } indexes = {} for i, v in enumerate(nums): if v in indexes: index_list = indexes[v] index_list.append(i) else: indexes[v] = [i] diff = target - v if diff in indexes: diff_indexes = indexes[diff] for j in diff_indexes: if i == j: continue return [i,j]
def isValid(s): left_to_right = { "(": ")", "{": "}", "[": "]", } stack = [] for c in s: if c in left_to_right: stack.append(c) else: if len(stack) > 0: previous = stack.pop() if left_to_right[previous] != c: return False else: return False return len(stack) == 0 data = "{}[]()(){}" r = isValid(data) print(r)