text
stringlengths
37
1.41M
from tkinter import * def get_selected_row(): pass win=Tk() win.wm_title("My routine database") l1=Label(win, text="Date") l1.grid(row=0, column=0) l2=Label(win, text="Earnings") l2.grid(row=0, column=2) l3=Label(win, text="Exercise") l3.grid(row=1, column=0) l4=Label(win, text="Study") l4.grid(row=1, column=2) l5=Label(win, text="Diet") l5.grid(row=2, column=0) l6=Label(win, text="Python") l6.grid(row=2, column=2) date_text=StringVar() e1=Entry(win, textvariable=date_text) e1.grid(row=0, column=1) earnings_text=StringVar() e2=Entry(win, textvariable=earnings_text) e2.grid(row=0, column=3) exercise_text=StringVar() e3=Entry(win, textvariable=exercise_text) e3.grid(row=1, column=1) study_text=StringVar() e4=Entry(win, textvariable=study_text) e4.grid(row=1, column=3) diet_text=StringVar() e5=Entry(win, textvariable=diet_text) e5.grid(row=2, column=1) python_text=StringVar() e6=Entry(win, textvariable=python_text) e6.grid(row=2, column=3) list=Listbox(win, height=8, width=35) list.grid(row=3, column=0, rowspan=9, columnspan=2) sb=Scrollbar(win) sb.grid(row=3, column=2, rowspan=9) list.bind("<<ListboxSelect>>",get_selected_row) b1=Button(win, text="ADD", width=12, pady=5) b1.grid(row=3, column=3) b2=Button(win, text="Search", width=12, pady=5) b2.grid(row=4, column=3) b3=Button(win, text="Delete date", width=12, pady=5) b3.grid(row=5, column=3) b4=Button(win, text="View All", width=12, pady=5) b4.grid(row=6, column=3) b5=Button(win, text="Close", width=12, pady=5, command=win.destroy) b5.grid(row=7, column=3) win.mainloop()
import random from timeit import default_timer def Randomized_hiring_assistant(list,fees): cost=int(0) best=0 num=int() for i in range(0,len(list)): num=list[i] if num>best: best=num cost+=fees return (best,cost,list) def Randomize_in_place(list,fees): for i in range(0,len(list)): index=random.randint(0,len(list)-1) list[i],list[index]=list[index],list[i] return Randomized_hiring_assistant(list,fees) def main(): start=default_timer() print('Enter the cost of hiring of employment agency : ',end='') fees=int(input()) print('Enter the no. of assistant : ',end='') n=int(input()) a=input('Enter the list of assistants : ') list=[int(s) for s in a.split()] best,cost,list=Randomize_in_place(list,fees) elapsed=default_timer()-start print(f'The candidate with best qualification is {best}.\nThe cost of hiring is Rs {cost}.\nThe randomized list is : {list}\nThe time taken to execute is {elapsed:.2f} second.') main() """ Output- Worstcase input Enter the cost of hiring of employment agency : 100 Enter the no. of assistant : 10 Enter the list of assistants : 1 2 3 4 5 6 7 8 9 10 The candidate with best qualification is 10. The cost of hiring is Rs 400. The randomized list is : [7, 5, 4, 2, 6, 8, 9, 1, 10, 3] The time taken to execute is 6.66 second. Bestcase input Enter the cost of hiring of employment agency : 100 Enter the no. of assistant : 10 Enter the list of assistants : 10 9 8 7 6 5 4 3 2 1 The candidate with best qualification is 10. The cost of hiring is Rs 400. The randomized list is : [5, 8, 7, 3, 1, 9, 2, 4, 10, 6] The time taken to execute is 15.15 second. Average case input Enter the cost of hiring of employment agency : 100 Enter the no. of assistant : 10 Enter the list of assistants : 1 2 3 4 10 5 6 7 8 9 The candidate with best qualification is 10. The cost of hiring is Rs 200. The randomized list is : [9, 8, 6, 5, 7, 1, 2, 10, 4, 3] The time taken to execute is 14.43 second. """
class node: def __init__(self,value=0,next=None): self.value=value self.next=next class queue(node): def __init__(self,head=None,tail=None): self.head=node() self.tail=node() self.length=0 # operations on a queue. # 1) Queue_empty() # 2) Enqueue() # 3) Dequeue() # All these operations take O(1) n time. def Queue_empty(self): if self.length>=1: return False else: return True def Enqueue(self,value): tempnode=node(value) self.length+=1 if self.length==1: self.head=tempnode self.tail.next=tempnode self.tail=tempnode def Dequeue(self): if self.length==0: print("Error : Queue underflow.") return tempnode=self.head self.head=self.head.next self.length-=1 return tempnode.value def main(): a=queue() print(f'Is the queue empty : {a.Queue_empty()}') a.Enqueue('apple') a.Enqueue('mango') a.Enqueue('grapes') a.Enqueue('banana') a.Enqueue('orange') print(f'Is the queue empty : {a.Queue_empty()}') while a.Queue_empty()!=True: print(a.Dequeue()) print(f'Is the queue empty : {a.Queue_empty()}') main() """ Output : Is the queue empty : True Is the queue empty : False apple mango grapes banana orange Is the queue empty : True """
from timeit import default_timer def Matrix_multiplication(A,B): m3=[] for i in range(0,len(A)): v=[0]*len(B[0]) for j in range(0,len(B[0])): v[j]=0 for k in range(0,len(B)): v[j]+=int(A[i][k])*int(B[k][j]) m3.append(v) return m3 def main(): start=default_timer() print("Enter the order of first matrix : ") r1,c1=map(int,input().split()) print("Enter the order of second matrix : ") r2,c2=map(int,input().split()) if c1!=r2: print("error: Incorrect order!!\nCan't multiply matrices") else: A=[] B=[] print('Enter the first matrix : ') for i in range(0,r1): v=[] v=input().split() A.append(v) print('Enter the second matrix : ') for i in range(0,r2): v=[] v=input().split() B.append(v) C=Matrix_multiplication(A,B) print(f'The order of the resultant matirx is {r1}X{c2}\nThe resultant matrix is : ') for i in range(0,r1): for j in range(0,c2): print(C[i][j],end=' ') print() stop=default_timer() elapsed=stop-start print(f'Time taken to execute {elapsed:.2f} seconds') main() """ Output- Testcase 1 Enter the order of first matrix : 3 3 Enter the order of second matrix : 3 4 Enter the first matrix : 1 2 3 4 5 6 7 8 9 Enter the second matrix : 1 2 3 4 5 6 7 8 9 10 11 12 The order of the resultant matirx is 3X4 The resultant matrix is : 38 44 50 56 83 98 113 128 128 152 176 200 Time taken to execute 23.06 seconds Testcase 2 Enter the order of first matrix : 3 4 Enter the order of second matrix : 2 3 error: Incorrect order!! Can't multiply matrices Time taken to execute 6.37 seconds """
from random import choice, random, seed seed(1211) # arbitrary seed for testing class Board: def __init__(self, size=4, start=(0, 0), pit_rate=0.1, gold_loc=None, wumpus_loc=None, n_wumpus=1): """ The board is represented as a list of lists. Most placings are either random or intended to be specified by the user. I wanted to also handle a non-square board, but did not get to implementing it. :param size: board size NXN matrix, default is 4. :param start: starting location. Default is 0,0, which is top left. :param pit_rate: likelihood of an unoccupied space to become a pit. :param gold_loc: the gold's starting location. Random if None. :param wumpus_loc: the Wumpus starting location. Random if None. The Wumpus doesn't move in this implementation :( :param n_wumpus: theoretically, could have more than one wumpus. """ self.size, self.start, self.agent_location, self.pit_rate, self.gold_loc,\ self.wumpus_loc, self.n_wumpus = size, start, start, pit_rate,\ gold_loc, wumpus_loc, n_wumpus self.board = self.generate_board(size, start, gold_loc) self.pit_locations = [] self.generate_pits(pit_rate) self.add_wumpus(wumpus_loc) self.breezes = {} self.stenches = {} self.breezes_and_stench(self.pit_locations, self.wumpus_loc) return def generate_board(self, size, start, gold_loc): """ :returns a list of lists of size n empty locations are 0s, agent is A, and gold is g""" # create nXn matrix board = [[0 for i in range(size)] for j in range(size)] # gold appears at random location, or at a specified one. # this should handle errors, but for now left to rely on the user. # theoretically the gold could be in the starting square, but for ease of implementation, it isn't while gold_loc is None: x, y = choice(range(size)), choice(range(size)) if [x, y] != start: gold_loc = (x, y) board[gold_loc[0]][gold_loc[1]] = "g" self.gold_loc = gold_loc # place the agent at the chosen start location board[start[0]][start[1]] = "A" return board def generate_pits(self, pit_rate): # for each unoccupied square, generate random floating point in range 0-1 # if it is smaller than the pit-rate, the room becomes a pit. for i in range(self.size): for j in range(self.size): if self.board[i][j] == 0 and random() <= pit_rate: self.board[i][j] = "p" self.pit_locations.append((i, j)) return def add_wumpus(self, wumpus_loc): # randomize an unoccupied square, place wumpus, unless a location is specified # not currently implementing multiple wumpusi while wumpus_loc is None: x, y = choice(range(self.size)), choice(range(self.size)) if self.board[x][y] == 0: wumpus_loc = (x, y) self.board[wumpus_loc[0]][wumpus_loc[1]] = "w" self.wumpus_loc = wumpus_loc return def breezes_and_stench(self, pit_locations, wumpus_loc): # will be used for perceiving stenches and breezes for pit in pit_locations: for room in self.adjacent(pit): self.breezes[room] = True for room in self.adjacent(wumpus_loc): self.stenches[room] = True return @staticmethod def adjacent(loc): """ checks for adjacency of rooms. Does not care for the borders of the board, though. Decided to handle that in each call, although would make sense to do here instead. :param loc: the room to check for adjacency. :return: all adjacent rooms as a list of tuples [(X,Y),...] """ return [(loc[0] + 1, loc[1]), (loc[0] - 1, loc[1]), (loc[0], loc[1] + 1), (loc[0], loc[1] - 1)]
# Weather App that provides you the temperature and timezone details of a city on a click from tkinter import * import requests import json root = Tk() root.title("Weather App") root.iconbitmap('disneyland.ico') root.geometry("600x200") root.configure(background="White") api_p1 = "https://api.weatherbit.io/v2.0/current?city=" api_p2 = ",IN&key=" #Add your own key here def submit(): try: api_rq = requests.get(api_p1+ent.get()+api_p2) api = json.loads(api_rq.content) ap = api["data"] mylbl1 = Label(root, background="White", padx=70, text="City : " + str(ap[0]['city_name']), font=("Helvetica", 20)) mylbl1.pack() mylbl2 = Label(root, background="White", padx=3, text="TimeZone : " + str(ap[0]['timezone']), font=("Helvetica", 20)) mylbl2.pack() mylbl3 = Label(root, background="White", padx=5, text="Temperature : " + str(ap[0]['temp']) + " deg C", font=("Helvetica", 20)) mylbl3.pack() except Exception as e: api = "Error" mylbl = Label(root, background="SkyBlue", padx=70, text="Enter City Name : ", font=("Helvetica", 20)) mylbl.pack() ent = Entry(root, background="White", borderwidth=3, font=("Helvetica", 20)) ent.pack() btn = Button(root, text="Search", font=("Helvetica", 20), command=submit) btn.pack() root.mainloop()
from re import match def check_if_can_do_without_palette(dictionary): if "Figures" in dictionary: figures = dictionary["Figures"] for elem in figures: if "color" in elem: if not match("[a-z]+", elem["color"]) and not match("\(\d{1,3},\d{1,3},\d{1,3}\)", elem["color"]) and \ not match("#[0-9,a-f]{6}", elem["color"]): return False elif match("[a-z]+", elem["color"]): if elem["color"] not in dictionary["Palette"]: return False return True def validate_screen(dictionary): screen = dictionary["Screen"] if "width" not in screen or "height" not in screen or "bg_color" not in screen: return False if "fg_color" not in screen: if "Figures" in dictionary: for elem in dictionary["Figures"]: if "color" not in elem: return False if screen["width"] < 1 or screen["height"] < 0: return False if not match("[a-z]+", screen["bg_color"]) and not match("\(\d{1,3},\d{1,3},\d{1,3}\)", elem["bg_color"]) and \ not match("#[0-9,a-f]{6}", elem["bg_color"]): return False if not match("[a-z]+", screen["fg_color"]) and not match("\(\d{1,3},\d{1,3},\d{1,3}\)", elem["fg_color"]) and \ not match("#[0-9,a-f]{6}", elem["fg_color"]): return False return True def validate_figure(figure): if "type" not in figure: return False if figure["type"] == "point": if "x" not in figure or "y" not in figure: return False if figure["x"] < 0 or figure["y"] < 0: return False return True elif figure["type"] == "polygon": if "points" not in figure: return False for lista in figure["points"]: if len(lista) is not 2: return False for elem in lista: if elem < 0: return False return True elif figure["type"] == "rectangle": if "x" not in figure or "y" not in figure or "width" not in figure or "height" not in figure: return False if figure["x"] < 0 or figure["y"] < 0 or figure["width"] < 1 or figure["height"] < 0: return False return True elif figure["type"] == "square": if "x" not in figure or "y" not in figure or "size" not in figure: return False if figure["x"] < 0 or figure["y"] < 0 or figure["size"] < 0: return False return True elif figure["type"] == "circle": if "x" not in figure or "y" not in figure or "radius" not in figure: return False if figure["x"] < 0 or figure["y"] < 0 or figure["radius"] < 1: return False return True else: return False
from numpy import array, sqrt, ones, Float import _regress def bistats(x, y): """ Basic statistics summarizing a bivariate distribution. xbar, xstd, ybar, ystd, covar, rho = bistats(x,y) xbar, ybar are the sample means xstd, ystd are the sample standard deviations (with 1/n rather than 1/(n-1) factors in the variance sum) covar is the covariance rho is Pearson's linear correlation coefficient """ if len(x) != len(y): raise ValueError, 'x, y length mismatch!' if len(x) < 2: raise ValueError, 'Need at least n=2!' xbar, xstd, ybar, ystd, covar, rho, ierr = _regress.datstt(x,y) if ierr == 0: raise ValueError, 'Input data has zero Sum(x-xbar)(y-ybar)!' xstd = sqrt(xstd) ystd = sqrt(ystd) return xbar, xstd, ybar, ystd, covar, rho class BiStats(object): """ Basic statistics summarizing a bivariate distribution. b = BiStats(x, y, nocopy=None) creates an object with these attributes: xbar, ybar = sample means xstd, ystd = sample standard deviations (with 1/n rather than 1/(n-1) factors in the variance sum) covar = covariance rho = Pearson's linear correlation coefficient The input data is copied to x, y attributes, unless nocopy is True, in which case the x, y attributes are references to the original data. """ def __init__(self, x, y, nocopy=None): if len(x) != len(y): raise ValueError, 'x, y length mismatch!' if len(x) < 2: raise ValueError, 'Need at least n=2!' # Handle copying first so the datstt call doesn't duplicate # any needed conversion of a sequence to an array. if nocopy: self.x = x self.y = y else: try: self.x = x.copy() self.y = y.copy() except AttributeError: self.x, self.y = array(x), array(y) self.xbar, self.xstd, self.ybar, self.ystd, \ self.covar, self.rho, error = _regress.datstt(self.x, self.y) if error == 0: raise ValueError, 'Input data has zero Sum(x-xbar)(y-ybar)!' self.xstd = sqrt(self.xstd) self.ystd = sqrt(self.ystd) class LinRegResult(object): """ Results of a bivariate linear regression calculation. Basic attributes: method = String identifying regression method slope = Slope of regression line inter = Intercept of regression line serr = Standard error for slope ierr = Standard error for intercept x, y = Copies of data vectors used for calculation xerr, yerr = Copies of x, y errors used for calculation (if passed) """ def __init__(self, method, slope, inter, serr, ierr, x, y, xerr=None, yerr=None): self.method = method self.slope = slope self.inter = inter self.serr = serr self.ierr = ierr self.x, self.y = x, y self.npts = len(self.x) if xerr is None: self.xmin, self.xmax = min(x), max(x) else: self.xmin, self.xmax = min(x-xerr), max(x+xerr) if yerr is None: self.ymin, self.ymax = min(y), max(y) else: self.ymin, self.ymax = min(y-yerr), max(y+yerr) def wlss(x, y, yerr): """ Perform weighted least squares with scatter for fitting a line to y vs. x data, where the y measurements have known measurement errors (yerr) but also additional (homoscedastic) intrinsic scatter. yerr may be a scalar for constant (homoscedastic) measurement error, or an array for (heteroscedastic) errors that vary from datum to datum. Returns a LinRegResult object with an additional attribute: scat = Standard deviation of the intrinsic scatter yerr = Copy of y errors used for calculation """ npts = len(x) # Make a vector of yerr values if yerr is a scalar. try: if len(yerr) != npts: raise ValueError, 'x, yerr length mismatch!' except TypeError: yerr = yerr * ones(npts, Float) # Check input sizes. if len(y) != npts: raise ValueError, 'x, y length mismatch!' if npts < 2: raise ValueError, 'Need npts >= 2!' # _regress.wlss alters x, y (but not yerr) so copy them twice. try: x, y = x.copy(), y.copy() except AttributeError: x, y = array(x), array(y) x2, y2 = x.copy(), y.copy() # Handle copying yerr here so the wlss call doesn't duplicate # any needed conversion of a sequence to an array. try: yerr = yerr.copy() except AttributeError: yerr = array(yerr) inter, ierr, slope, serr, scat, error = _regress.wlss(x2, y2, yerr) if error == 0: raise ValueError, 'Input data has zero Sum(x-xbar)(y-ybar)!' x, y = x.copy(), y.copy() result = LinRegResult('wlss', slope, inter, sqrt(serr), sqrt(ierr),\ x, y, yerr=yerr) # Add extra attribute. result.scat = sqrt(scat) return result class BCES(object): """ BCES: Bivariate, Correlated Errors and Scatter Perform four linear regressions for cases where both variables are subject to known errors, and there is intrinsic scatter. Errors may be correlated or uncorrelated, and may be homoscedastic or heteroscedastic, i.e. the same or different for each datum. Results are available as four LinRegResult objects, stored as attributes: yonx = Ordinary least squares for (y|x) xony = Ordinary least squares for (x|y) bisect = Ordinary least squares bisector orthog = Orthogonal least squares """ def __init__(self, x, xerr, y, yerr, covar): npts = len(x) # Make a vector of err values if scalars are provided. # If a vector is provided, copy it. try: if len(xerr) != npts: raise ValueError, 'x, xerr length mismatch!' try: xerr = xerr.copy() except AttributeError: xerr = array(xerr) except TypeError: xerr = xerr * ones(npts, Float) try: if len(yerr) != npts: raise ValueError, 'x, yerr length mismatch!' try: yerr = yerr.copy() except AttributeError: yerr = array(yerr) except TypeError: yerr = yerr * ones(npts, Float) try: if len(covar) != npts: raise ValueError, 'x, covar length mismatch!' try: covar = covar.copy() except AttributeError: covar = array(covar) except TypeError: covar = covar * ones(npts, Float) # Check input sizes. if len(y) != npts: raise ValueError, 'x, y length mismatch!' if npts < 2: raise ValueError, 'Need npts >= 2!' # Handle copying x, y here so the bess call doesn't duplicate # any needed conversion of a sequence to an array. try: x, y = x.copy(), y.copy() except AttributeError: x, y = array(x), array(y) # Do the regressions. inter, slope, ierr, serr, serr_IFAB = \ _regress.bess(x, xerr, y, yerr, covar) # Store results. ierr, serr, serr_IFAB = sqrt(ierr), sqrt(serr), sqrt(serr_IFAB) self.yonx = LinRegResult('BCES-yonx', slope[0], inter[0], serr[0], ierr[0], x, y, xerr, yerr) self.xony = LinRegResult('BCES-xony', slope[1], inter[1], serr[1], ierr[1], x, y, xerr, yerr) self.bisect = LinRegResult('BCES-bisect', slope[2], inter[2], serr[2], ierr[2], x, y, xerr, yerr) self.bisect.serr_IFAB = serr_IFAB[2] self.orthog = LinRegResult('BCES-orthog', slope[3], inter[3], serr[3], ierr[3], x, y, xerr, yerr) self.orthog.serr_IFAB = serr_IFAB[3] class SixLin(object): """ SixLin: Six bivariate linear regressions Perform six linear regressions for bivariate data without known errors. Results are available as six LinRegResult objects, stored as attributes: yonx = Ordinary least squares for (y|x) xony = Ordinary least squares for (x|y) bisect = Ordinary least squares bisector orthog = Orthogonal least squares orthog = Orthogonal least squares rma = Reduced major axis mols = Mean ordinary least squares """ def __init__(self, x, y): npts = len(x) # Check input sizes. if len(y) != npts: raise ValueError, 'x, y length mismatch!' if npts < 2: raise ValueError, 'Need npts >= 2!' # Handle copying x, y here so the sixlin call doesn't duplicate # any needed conversion of a sequence to an array. try: x, y = x.copy(), y.copy() except AttributeError: x, y = array(x), array(y) # sixlin alters x, y so copy them twice. try: x, y = x.copy(), y.copy() except AttributeError: x, y = array(x), array(y) x2, y2 = x.copy(), y.copy() # Do the regressions. inter, ierr, slope, serr, error = _regress.sixlin(x2, y2) if error == 0: raise ValueError, 'Input data has zero Sum(x-xbar)(y-ybar)!' # Store results. self.yonx = LinRegResult('SixLin-yonx', slope[0], inter[0], serr[0], ierr[0], x, y) self.xony = LinRegResult('SixLin-xony', slope[1], inter[1], serr[1], ierr[1], x, y) self.bisect = LinRegResult('SixLin-bisect', slope[2], inter[2], serr[2], ierr[2], x, y) self.orthog = LinRegResult('SixLin-orthog', slope[3], inter[3], serr[3], ierr[3], x, y) self.rma = LinRegResult('SixLin-rma', slope[4], inter[4], serr[4], ierr[4], x, y) self.mols = LinRegResult('SixLin-mols', slope[5], inter[5], serr[5], ierr[5], x, y)
n1 = float(input('Quantos reais você tem na sua carteira? ')) print('Você pode comprar {} dólares'.format(n1/3.27))
s = int(input('Salário do funcionário: ')) print('O salário aumentado é: {}'.format(s*1.15))
num = int(input('Escolha um número de 0 até 9999: ')) n= str(num) print('Unidades: {}'.format(n[3])) print('Dezenas: {}'.format(n[2])) print('Centenas: {}'.format(n[1])) print('Milhares: {}'.format(n[0]))
d = float(input('Quantos km é a viagem? ')) if d<=200: print('Sua viagem custará {} reais'.format(d*0.5)) else: print('Sua viagem custará {} reais'.format(d*0.45))
class Person: def __init__(self,name='', bdate='', gender=''): self.name=name self.bdate= bdate self.gender = gender def set(self,name='',bdate='', gender=''): self.name=name self.bdate= bdate self.gender = gender def get(self): return self.name,self.bdate,self.gender def show(self): print("Name : ",self.name) print("Birth date : ",self.bdate) print("Gender : ",self.gender)
import turtle as t import random import time def message(str_up, str_down): # 위아래로 메시지 출력 player.goto(0,100) player.write(str_up, False, "center", ("Arial", 20, "bold")) # Arial 폰트, 폰트 크기 20, 굵게, 가운데 정렬로 str_up 작성 player.goto(0,-100) player.write(str_down, False, "center", ("Arial", 15, "normal")) player.home() # 거북이 원점으로 이동 player.showturtle() def start(): # 게임 시작 playing = True player.clear() playing = play(playing) end(playing) def play(playing): # 게임 진행 max_time = time.time() + 20 # 최대 20초의 시간 제한 while playing: if time.time() > max_time: playing = False return playing player.showturtle() player.up() # 펜 들기 location = random.choice(location_list) player.goto(location) time.sleep(random.uniform(0.1, 1)) # 거북이가 나타나는 시간을 0.1초에서 1초 사이 랜덤으로 지연 def show_score(score): # 점수 출력 score_board.clear() score_board.color("white") score_board.goto(150, 150) score_board.pencolor("black") score_board.write("Score : %d" % score, False, "left", ("Arial", 13, "bold")) score_board.color("white") def right(): # 유저가 누른 방향키가 오른쪽이면 점수 획득 global score if player.position() == (200.00, 0.00): # 거북이의 위치가 오른쪽이면 player.hideturtle() score = score + 1 show_score(score) def left(): # 유저가 누른 방향키가 왼쪽이면 점수 획득 global score if player.position() == (-200.00, 0.00): # 거북이의 위치가 왼쪽이면 player.hideturtle() score = score + 1 show_score(score) def up(): # 유저가 누른 방향키가 위쪽이면 점수 획득 global score if player.position() == (0.00, 200.00): # 거북이의 위치가 위쪽이면 player.hideturtle() score = score + 1 show_score(score) def down(): # 유저가 누른 방향키가 아래쪽이면 점수 획득 global score if player.position() == (0.00, -200.00): # 거북이의 위치가 아래쪽이면 player.hideturtle() score = score + 1 show_score(score) def end(playing): # 게임 종료 global score if not playing: score_board.clear() text = "Score : %d" % score message("Game Over", text) # 게임 종료 화면으로 "Game Over"와 점수를 출력 score = 0 player = t.Turtle() # 거북이 객체 생성 player.shape("turtle") player.speed(0) player.up() screen = t.Screen() # screen 객체 생성 screen.title("Catch Turtle") # 그래픽 창 이름 지정 screen.setup(500, 500) # 창 크기 500*500으로 설정 score_board = t.Turtle() # 점수판 객체 생성 score_board.color("white") score_board.goto(150,150) score = 0 location_list = [(0,200), (0,-200), (200,0), (-200,0)] # 거북이의 위치(위, 아래, 오른쪽, 왼쪽) 리스트로 생성 screen.onkeypress(start, "space") # 스페이스 바를 누르면 start 함수 실행 screen.onkeypress(right, "Right") # 오른쪽 키를 누르면 right 함수 실행 screen.onkeypress(left, "Left") screen.onkeypress(up, "Up") screen.onkeypress(down, "Down") screen.listen() # 이 명령어를 실행시켜야 키 입력모드가 실행되어 입력된 키에 반응 message("Catch Turtle", "[Space]") # 게임 시작하기 전 첫 화면으로 "Catch Turtle"과 "[Space]"를 출력 input()
'''p.s.一定要在所有地雷上正確放上旗子才算勝利''' '''p.p.s.一局結束若輸入y以外則都當作n,結束遊戲''' #### set up #### import random import time parting = ' +---+---+---+---+---+---+---+---+---+' column = ['a','b','c','d','e','f','g','h','i'] row = ['1','2','3','4','5','6','7','8','9'] instruction = 'Enter the column followed by the row (ex: a5). To add or remove a flag, \nadd \'f\' to the cell (ex: a5f).' def show_table(): '''印出當下遊戲''' print(' a b c d e f g h i') for i in range(9): print(parting) print('',i+1,end = ' ') for j in r[i]: print('|',j,end = ' ') print('|') print(parting) print() def show_real(): '''印出實際分布''' print(' a b c d e f g h i') for i in range(9): print(parting) print('',i+1,end = ' ') for j in R[i]: print('|',j,end = ' ') print('|') print(parting) print() ####### game ####### while 1: #設定R是實際地雷和數字的表; r是顯示出來的部分 r1 = [' ',' ',' ',' ',' ',' ',' ',' ',' '] r2 = [' ',' ',' ',' ',' ',' ',' ',' ',' '] r3 = [' ',' ',' ',' ',' ',' ',' ',' ',' '] r4 = [' ',' ',' ',' ',' ',' ',' ',' ',' '] r5 = [' ',' ',' ',' ',' ',' ',' ',' ',' '] r6 = [' ',' ',' ',' ',' ',' ',' ',' ',' '] r7 = [' ',' ',' ',' ',' ',' ',' ',' ',' '] r8 = [' ',' ',' ',' ',' ',' ',' ',' ',' '] r9 = [' ',' ',' ',' ',' ',' ',' ',' ',' '] r = [r1, r2, r3, r4, r5, r6, r7, r8, r9] R = r[:] for i in range(9): R[i] = r[i][:] for i in range(9): for j in range(9): R[i][j] = 0 mine = 10 #剩下的地雷數 countmine = 0 #已創造的地雷數 show_table() print(instruction+'Type \'help\' to show this message again.') print() while 1: inp = input('Enter the cell (%s mines left): '%(mine)) #input的第一種可能:help if inp == 'help': show_table() print(instruction) print() #input的第二種可能:正確的選擇一個位置(如:a5) elif len(inp) == 2 and inp[0] in column and inp[1] in row: a = int(inp[1])-1 b = column.index(inp[0]) #第一次踩下 if countmine == 0 and r[a][b] == ' ': #開始計時 timestart = time.time() #隨機產生地雷(第一格的周圍八格不可以有地雷) while countmine < 10: (x,y) = (random.randint(0,8),random.randint(0,8)) wrongplace = 0 for i in range(-1,2): if wrongplace == 1: break for j in range(-1,2): if (x,y) == (a+i,b+j) or R[x][y] == 'X': wrongplace = 1 break if wrongplace == 0: R[x][y] = 'X' countmine +=1 for i in range(-1,2): for j in range(-1,2): if x+i >= 0 and x+i <= 8 and y+j >= 0 and y+j <= 8: if R[x+i][y+j] != 'X': R[x+i][y+j] += 1 #已經放旗子不能踩 if r[a][b] == 'F': show_table() print('There is a flag there.') print() #已經顯示出來 elif r[a][b] != ' ': show_table() print('That cell is already shown.') print() else: ##踩到地雷則輸了,結束遊戲 if R[a][b] == 'X': print('\nGame Over\n') show_real() break #不是地雷 else: #顯示該格,若為0,要一直複製到不為零的地方 if R[a][b] == 0: zeros = [(a,b)] #把所有周圍為0的位置都存進list #所有0周圍九宮格都顯示出來,且若為0的位置則再增加進list中再判斷 for (i,j) in zeros: for k in range(-1,2): for l in range(-1,2): if i+k >= 0 and i+k <= 8 and j+l >= 0 and j+l <= 8: if r[i+k][j+l] != 'F': r[i+k][j+l] = R[i+k][j+l] if R[i+k][j+l] == 0 and not (i+k,j+l) in zeros: zeros.append((i+k,j+l)) #不為0則僅顯示該格 else: r[a][b] = R[a][b] show_table() #input的第三種可能:正確選擇一格放旗子(如:a5f) elif len(inp) == 3 and inp[0] in column and inp[1] in row and inp[2] == 'f': a = int(inp[1])-1 b = column.index(inp[0]) #已經顯示出數字則不能放 if r[a][b] != 'F' and r[a][b] != ' ': show_table() print('Cannot put a flag there.') print() continue else: #還沒有旗子則放 if r[a][b] == ' ': r[a][b] = 'F' mine -= 1 #已有旗子則移除 elif r[a][b] == 'F': r[a][b] = ' ' mine += 1 ##判斷勝利 if mine == 0: judgeWin = 1 for i in range(9): for j in range(9): if r[i][j] == 'F': if R[i][j] != 'X': judgeWin = 0 break #勝利 if judgeWin == 1: #結束計時 timeend = time.time() time = int(timeend-timestart) minute = time//60 second = time%60 print('\nYou Win. It took you %d minutes and %d seconds.\n' %(minute,second)) show_real() break show_table() #input的第四種可能:錯誤 else: show_table() print('Invalid cell. Enter the column followed by the row (ex: a5). To add or \nremove a flag, add \'f\' to the cell (ex: a5f).') print() #結束一局,是否繼續玩 play = input('Play again? (y/n): ') if play == 'y': continue else: break
#替規函數概念:調用含數自身的行為 def factorial(n): if n == 1: return 1 else: return n*factorial(n-1) number = int(input('請輸入一個正整數:')) result = factorial(number) print('%d 的階層是: %d'%(number, result))
some_text = input('enter text') memory = '' for word in some_text.split(): if len(word) > len(memory): memory = word print(memory)
x = input() 1234 x '1234' list(x) ['1', '2', '3', '4'] x = list(x) x[0] '1' if int (x[0]) + int (x[1]) == int (x[2]) + int (x[3]): print('A happy ticket') else: print('Not a happy ticket') x = input() 100001 y = x[::-1] if int(x[0, 1, 2]) == int(x[3, 4, 5]): print('Palindrom') elif x == y print('Palindrom') else: print('Not a palindrom') import math print("Введите координаты точки и радиус круга") x_point = float(input("x = ")) y_point = float(input("y = ")) r_circle = float(input("R = ")) hypotenuse = math.sqrt(x_point ** 2 + y_point ** 2) if hypotenuse <= r_circle: print("Точка принадлежит кругу") else: print("Точка НЕ принадлежит кругу")
number = input('Put yor number ') counter = 0 for item in number: counter += int(item) print(f'Sum is {counter}')
num = int("5") for i in range(1,11): print(num, 'x', i,' = ' , num * i)
def element_concat_list(number1: int, number2: int, text: str) -> str: return text + str(number1 + number2) if __name__ == '__main__': result = element_concat_list(2, 3, 'sum is ') print(result)
print ("=============================================welcome to idk 74 puzzle===============================================") print("to start and get first clue tipe start") print("no space in soluion") start='what is full of holse but still holds water?' asponge='what gos up and never comes down?' yourage='i shave every day but my beard stays the same what am i' abarber='i have branchis but no fruit trunk or leaves what am i?' abank='the more of it is the less you see what is it' darkness='what cant talk but will reply when spoken to ' anecho='what is always in front of you but cant be be seen' thefuture='where can you find sities towns shops and streats but no people' amap='what belongs to you but other people use it more?' yourname='what has legs but cannot walk' achair='what has hands but cannot clap' aclock='what is the capital in France' theletterf='i can fill a room fut take up no space what am i?' light='what word is spelled wrong in the in the dictionary?' wrong=' what begins with an e an has only one letter' anenvelope='what has to be broken before you can use it?' anegg='after a train crashed every single person died who survived?' allthecouples='how can a lepord change its stpots' bymoveing='what brakes if you say its name' silence='what has an neck but no head' abottle='what is abank but has no money' abloodbank='what is easy to get into but hard to get out of' truble='if you dont keap me i will brake what am i?' apromice='i am not alive but i cam die what am i' abattery='what question can you not say yes to' areyouasleep='iam tall when i am young i am short when i am old what am i?' acandle='what has keys but cant open a lock' apiano='i am light as a fether but the strongest man cant hold me for mor than a minutes what am i?' air='what run but never walks' ariver='what can you cach but not throw ' acold='you bought me for diner but you never eat me' sliverware='what has four eyes but can no see' mississippi='how meney sides does a circle have ?' two='what is at the end of ranbow' theletterw='what two words added together has the most letters' postoffic='what has words but never speaks' abook='what building has the most stories' thelibrary='what five letter word becomes shorter when you add two letter to it' short='what has a head and a tail but no body' acoin='what begins with t ends with t and has t in it' ateapot='what can you hold with no armes or hands' yourbreth='what has four fingers and on thumb but isnt alive' aglove='what freezes when is heated up' acomputer='what get biger when more is taken away' ahole='what has one eye but can not see' aneedle='this is the end of the puzzle taanks for playing' credits='charlie'
""" Filename: blackjack.py Authors: Matt Matt's Coding by the Campfire Crew """ import random from simpleimage import SimpleImage #image = SimpleImage(filename) MIN_RANDOM = 1 MAX_RANDOM = 11 NUM_RANDOM = 3 def main(): # Let's get started with some liquid courage print("I still remember how to do a print statement!\nWhew - I deserve a drink!\n") # TODO: Hey Matt - how do we play Blackjack again? # type of suit suits = ["Spades", "Hearts", "Clubs", "Diamonds"] # suit value suits_value = {"Spades": "\u2664", "Hearts": "\u2661", "Clubs": "\u2667", "Diamonds": "\u2662"} # What cards do I have? player_cards = [] # Let's beat the dealer player_score = 0 # print("player_score is type ", type(player_score)) dealer_score = 0 # TODO: Let's bring the Las Vegas Welcome to Matt welcome_sign = SimpleImage('images/welcome_sign.png') welcome_sign.show() print("Welcome to Vegas! Let's play Blackjack!\n") # dealing a card to the player print("Here are two cards.") # player_card_one = input(random.randint(MIN_RANDOM, MAX_RANDOM)) player_card_one = random.randint(MIN_RANDOM, MAX_RANDOM) print("First card is ", str(player_card_one)) # print("card one is type: ", type(player_card_one)) # player_card_two = input(random.randint(MIN_RANDOM, MAX_RANDOM)) player_card_two = random.randint(MIN_RANDOM, MAX_RANDOM) print("Second card is ", str(player_card_two)) # print("card two is type: ", type(player_card_two)) player_card_value = player_card_one + player_card_two print("You have " + str(player_card_value) + "\n") # print("player_card_value is type: ", type(player_card_value)) # update the player score player_score += player_card_value # dealing a card to AI or dealer dealer_card_one = random.randint(MIN_RANDOM, MAX_RANDOM) dealer_card_two = random.randint(MIN_RANDOM, MAX_RANDOM) dealer_card_value = dealer_card_one + dealer_card_two # update the dealer score dealer_score += dealer_card_value # if player score is under 21, ask them if they want to hit or stand while player_score < 21: hit_choice = str(input("Would you like to hit or stand? ")) if hit_choice == 'hit': # if choice == 'hit' player_card = random.randint(MIN_RANDOM, MAX_RANDOM) print("Next card is " + str(player_card)) player_cards.append(player_card) player_card_value += player_card print("You have " + str(player_card_value)) if hit_choice == 'stand': print("You have " + str(player_card_value)) # elif choice == 'stand' # show both cards print("DEALER CARDS: ") # print_cards(dealer_cards[:-1], True) print("DEALER SCORE = ", dealer_score - dealer_card_value[-1].card_value) print() print("PLAYER CARDS: ") print_cards(player_cards, False) print("PLAYER SCORE = ", player_score) # Check for blackjack you_lose = SimpleImage('images/you_lose.png') you_lose.show() if player_score > 21 and total < 21: print("Sorry. You lose.") you_win = SimpleImage('images/you_win.png') you_win.show() if player_score == 21: print("YOU HAVE A BLACKJACK! YOU WIN") # Ask to play again play_again = input('Play again? "Yes" or "No"') == 'y' if play_again: return first_round if __name__ == '__main__': main()
import numpy as np import pandas as pd #Desafio3 # En la siguiente carpeta: inputEjemplos vas a encontrar un archivo llamado # CurrenciesRaw el cual no tiene encabezados y tiene campos erróneos. Lo que te solicitamos: # Eliminar las columnas que no tienen valores y/o están en cero. # Eliminar los campos que se encuentran repetidos # Eliminar la hora # Darle nombre significativos a los campos. # Redondear los campos a dos decimales. # Guardarlo como un CSV. def clean_file(fileToClean): """This function receives a csv file and generate a new cleaned one called "NewCurrenciesRaw.csv" """ data = pd.read_csv(fileToClean,sep='\t',header=None) #names=["country","datetrack","hour","country1","currency","datetrack1","dollarToLocal","no","localToDollar","nouo","site"]) #drop duplicates columns data = data.T.drop_duplicates().T #delete 0, "", o Nan columns data.replace(0, np.nan, inplace=True) data.replace("", np.nan, inplace=True) data.dropna(how='all', axis=1, inplace=True) #delete hour data.drop(2,axis="columns",inplace=True) #round off the numbers to two decimal places data = data.round(2) #name the columns data.rename(columns={0:"country",1:"datetrack",4:"currency",6:"dollarToLocal",8:"localToDollar",10:"site"},inplace=True) print(data.head()) #save as csv data.to_csv("NewCurrenciesRaw.csv",index=False) clean_file("currenciesRaw.csv")
#!/usr/bin/env python3 import numpy as np def diamond(n): def dims(n): return 2 * n - 1 nxn = dims(n) base = np.eye(nxn) bottom_left = base[0:n,0:n] # will be bottom left of result. right side will have dims one less than left bottom_right = base[n-1:, n:] bn = bottom_right.shape[0] lst_br = [] for i in range(0, bn): # reverse the ordering since the rows of bottom right are in the wrong order i2 = bn -1 - i lst_br.append(bottom_right[i2,:]) # now put them in a np array bottom_right = np.array(lst_br) top_left = base[bn:bn + (bn+1)//2, (bn+1)//2: bn + (bn )//2] bottom_right[:(bn+1)//2, :] lst_tl = [] for i in range(top_left.shape[0]): i2 = top_left.shape[0] - 1 - i lst_tl.append(top_left[i2,:]) top_left = np.array(lst_tl) # since bn is odd, // == / but gives an int # selecting the upper left square, since diamonds are symetric top_right = bottom_left[0:(bn+1)//2,:bn] top = np.concatenate((top_left, top_right), axis = 1) bottom = np.concatenate((bottom_left, bottom_right), axis = 1) #putting left and right side by side result = np.concatenate((top, bottom), axis = 0) return result def main(): print("\n", diamond(3)) if __name__ == "__main__": main() # pattern of input to diamond to output array size # f(n) = 2n -1 # 1 : 1 # 2 : 3 # 3 : 5 # 4 : 7
#!/usr/bin/env python3 import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import math from sklearn.decomposition import PCA def explained_variance(): f = os.path.dirname(os.path.realpath(__file__)) + "/data.tsv" df = pd.read_table(f, sep = '\t') # fit model and transform data pc = PCA(df.shape[1]) pc.fit(df) x = pc.transform(df) # # plots of data before and after change of basis # plt.plot(df.iloc[:,0], df.iloc[:,1], "o", c = "red", label = "Before") # plt.plot(x[:,0], x[:,1], "o", c = "blue", label = "After") # plt.legend() # plt.title("Before and After PCA") # plt.xlabel("First Variable") # plt.ylabel("Second Variable") # plt.show() return list(df.var()), list(pc.explained_variance_) def main(): v, ev = explained_variance() print("The variances are:", end = " ") for x in v: print("%0.3f" % x, end = " ") print() print("The explained variances after PCA are:", end = " ") for x in ev: print("%0.3f" % x, end = " ") print() sums = np.cumsum(ev) plt.plot([i for i in range(1, len(sums) + 1)], sums) plt.title("Cumulative Sums of the Explained Variance") plt.xlabel("Number of terms in the Cumulative Sum") plt.ylabel("Cumulative Explained Variance") plt.show() if __name__ == "__main__": main()
#!/usr/bin/env python3 import os import pandas as pd def municipalities_of_finland(): f = os.path.dirname(os.path.realpath(__file__)) df = pd.read_csv(f + "/municipal.tsv", sep = "\t", index_col = "Region 2018") return df["Akaa":"Äänekoski"] def swedish_and_foreigners(): df = municipalities_of_finland() sweed_bool = df['Share of Swedish-speakers of the population, %'] > 5 forn_bool = df['Share of foreign citizens of the population, %'] > 5 three_cols = df[['Population', 'Share of Swedish-speakers of the population, %', 'Share of foreign citizens of the population, %']] return three_cols[forn_bool & sweed_bool] def main(): df = swedish_and_foreigners() print(df.head()) if __name__ == "__main__": main() """ Write function swedish_and_foreigners that Reads the municipalities data set Takes the subset about municipalities (like in previous exercise) Further take a subset of rows that have proportion of Swedish speaking people and proportion of foreigners both above 5 % level From this data set take only columns about population, the proportions of Swedish speaking people and foreigners, that is three columns. The function should return this final DataFrame. Do you see some kind of correlation between the columns about Swedish speaking and foreign people? Do you see correlation between the columns about the population and the proportion of Swedish speaking people in this subset? """
#!/usr/bin/env python3 import math def solve_quadratic(a, b, c): discriminant = (b*b - 4 * a * c) if discriminant < 0: x1 = "complex number" else: x1 = -1 * b + math.sqrt(discriminant) x1 /= 2*a if discriminant < 0: x2 = "complex number" else: x2 = -1 * b - math.sqrt(discriminant) x2 /= 2*a return (x1, x2) def main(): print(solve_quadratic(1, -2, 5)) if __name__ == "__main__": main()
#!/usr/bin/env python3 def find_matching(L, pattern): lst = [] for i, v in enumerate(L): if pattern in v: lst.append(i) return lst def main(): find_matching(["sensitive", "engine", "rubbish", "comment"], "en") if __name__ == "__main__": main()
#!/usr/bin/python3 import numpy as np def meeting_lines(a1, b1, a2, b2): # a1 *= -1 # a2 *= -1 A = np.array([[-b1, 1],[-b2, 1]]) b = np.array([a1, a2]) return np.linalg.solve(A, b) def main(): a1=1 b1=4 a2=3 b2=2 x, y = meeting_lines(a1, b1, a2, b2) print(f"Lines meet at x={x} and y={y}") if __name__ == "__main__": main() """ https://math.stackexchange.com/questions/1348380/intersection-of-two-planes-how-to-represent-a-line y = a1*x + b1 y = a2*x + b2 1 = a1 + b1 1 = a2 + b2 """
#!/usr/bin/env python3 import os import pandas as pd def subsetting_with_loc(): f = os.path.dirname(os.path.realpath(__file__)) df = pd.read_csv(f + "/municipal.tsv", sep = "\t", index_col = "Region 2018") cols = ["Population", "Share of Swedish-speakers of the population, %", "Share of foreign citizens of the population, %"] return df["Akaa":"Äänekoski"].loc[:,cols] def main(): print(subsetting_with_loc().head()) return if __name__ == "__main__": main()
import math def splitCheck(total,partySize): if partySize <=1: raise ValueError("Not enough people. Go grab that hobo you saw down the street a moment ago.") cpp= math.ceil(total / partySize) return cpp try: totalDue= float(input("What did the end amount come to? ")) crewSize= float(input("how many people attended? ")) amountDue = splitCheck(totalDue,crewSize) except ValueError as err: print("Incorrect value, please try again.") print("({})".format(err)) else: print("The cost per person is:$", amountDue)
#!/usr/bin/env python3 # lesson-03.py - show a $30 withdrawal and a $15 deposit # # Learn: # the tedium of repetition balance = 100 print('Welcome to the bank.') print('Your balance is $%d.' % balance) print() amount = 10 print('Withdraw $%d.' % amount) balance -= amount print('Your balance is $%d.' % balance) print() amount = 20 print('Deposit $%d.' % amount) balance += amount print('Your balance is $%d.' % balance) print() amount = 30 print('Withdraw $%d.' % amount) balance -= amount print('Your balance is $%d.' % balance) print() amount = 15 print('Deposit $%d.' % amount) balance += amount print('Your balance is $%d.' % balance) print()
#!/usr/bin/env python3 # lesson-10.py - allow unlimited transactions # # Learn: # looping # break out of a loop # Boolean literal # single-branch conditional statement def showBalance(): global balance print('Your balance is $%d.' % balance) print() def withdrawal(amount): global balance print('Withdraw $%d.' % amount) balance -= amount showBalance() def deposit(amount): global balance print('Deposit $%d.' % amount) balance += amount showBalance() def main(): print('Welcome to the bank.') showBalance() while True: type = input('Enter d for deposit, w for withdrawal, or q to quit: ') if type == 'q': break amount = int(input('Enter amount: ')) if type == 'd': deposit(amount) else: withdrawal(amount) balance = 100 main()
#!/usr/bin/env python3 # lesson-21.py - create Account class with static balance member instead of passing around # # Learn: # class definition # static (class) members and access to them # variable and method members # another way to avoid globals import sys class Account: balance = None startingBalance = None transactions = [] def initBalance(balance): Account.balance = balance Account.startingBalance = balance def showBalance(): print('Your balance is $%d.' % Account.balance) print() def showTransactions(): balance = Account.startingBalance print(' op amount balance') print('-------- ------- -------') print(' %7d (starting)' % balance) for transaction in Account.transactions: [op, amount] = transaction if op == 'w': opLabel = 'withdraw' balance -= amount else: opLabel = 'deposit' balance += amount print('%-8s %7d %7d' % (opLabel, amount, balance)) print() def withdrawal(amount): if amount > Account.balance: print("Sorry, you don't have that much!") else: print('Withdraw $%d.' % amount) Account.balance -= amount Account.transactions.append(['w', amount]) Account.showBalance() def deposit(amount): print('Deposit $%d.' % amount) Account.balance += amount Account.transactions.append(['d', amount]) Account.showBalance() def getOperation(): op = input('Enter d for deposit, w for withdrawal, t for transactions, or q to quit: ') if op != 'q' and op != 'd' and op != 'w' and op != 't': print('Invalid operation. Please try again.') op = None return op def getAmount(): amount = None try: amount = int(input('Enter amount: ')) if amount <= 0: print('The amount must be positive.') amount = None except: print('Invalid amount. Please try again.') return amount def getStartingBalance(balance): if len(sys.argv) > 1: try: balance = int(sys.argv[1]) if balance < 0: print('The balance cannot be negative.') balance = None except: print('Invalid starting balance.') print('usage: %s [amount]' % sys.argv[0]) print('where amount is a starting balance dollar amount') balance = None return balance def processTransactions(): while True: amount = None op = getOperation() if op == 'q': break elif op == 't': Account.showTransactions() elif op is not None: amount = getAmount() if amount is None: pass elif op == 'd': Account.deposit(amount) else: Account.withdrawal(amount) def main(): balance = 100 balance = getStartingBalance(balance) if balance is not None: print('Welcome to the bank.') Account.initBalance(balance) Account.showBalance() processTransactions() main()
from abc import ABC, abstractmethod class Message(ABC): """ the abstract base class that serves at the input to both the encrypter and decrypter modules """ @abstractmethod def get_text(self): pass class PlaintextMessage(Message): def __init__(self, message_text): """ :param message_text: a byte String corresponding to the message text """ self.text = message_text def get_text(self): """ This method overrides the abstract method from the Message class so that all types of Messages have similar behavior and usage :return: the message text String """ return self.text class EncryptedMessage(Message): def __init__(self, key_ciphertext, message_ciphertext, initialization_vector=None, message_authentication_tag=None): """ Contains the encrypted ciphertext and the corresponding key which is itself encrypted :param key_ciphertext: a byte String that represents the encrypted keys :param message_ciphertext: a byte String that represents the encrypted message :param message_authentication_tag: a byte String that represents the message integrity tag """ self.key_ciphertext = key_ciphertext self._message_ciphertext = message_ciphertext self.message_authentication_tag = message_authentication_tag self.initialization_vector = initialization_vector def get_text(self): """ This method overrides the abstract method from the Message class so that all types of Messages have similar behavior and usage :return: the message text String """ return self._message_ciphertext # holds a message that has been hashed and its corresponding key class HashedMessage(Message): def __init__(self, hashed_text, key): """ Class contained a hashed message that can be used as an integrity tag :param hashed_text: a byte String containing the hashed text :param key: a byte String containing the key for the message authentication tag """ self._hashed_text = hashed_text self.key = key def get_text(self): """ This method overrides the abstract method from the Message class so that all types of Messages have similar behavior and usage :return: the message text String """ return self._hashed_text @abstractmethod def get_hashing_function(self): """ :return: a HashingAlgorithm object from the Cryptography library denoting the hashing function that was used """ pass class HMACHashedMessage(HashedMessage): def __init__(self, hashed_text, key, hashing_function): """ Defines HMAC integrity tag that has been hashed using the 'hashing_function' argument :param hashed_text: a byte String containing the hashed text :param key: a byte String containing the key for the message authentication tag :param hashing_function: a HashingAlgorithm object from the Cryptography library denoting the hashing function that was used """ HashedMessage.__init__(self, hashed_text, key) self._hashing_function = hashing_function def get_hashing_function(self): """ :return: a HsahingAlgorithm object from the Cryptography class """ return self._hashing_function
from cryptography.hazmat.primitives.ciphers.algorithms import AES from cryptography.hazmat.primitives.ciphers import Cipher, modes from cryptography.hazmat.backends import default_backend from os import urandom from cryptography.hazmat.primitives import padding from src.encrypter.encryptor import Encryptor class AESEncrypt(Encryptor): def encrypt(self, message_text, key=None): """ Encrypts a message using AES-256 bit :param message_text: a byte String containing the encoded message text :param key: (optional) a byte String representing an AES key. Must be 256 bits in length :return: a byte String containing the encrypted text, a byte String containing the AES key (respectively) """ if isinstance(message_text, str): message_text.encode("utf-8") elif not isinstance(message_text, bytes): # this also captures message_text == None raise TypeError("The argument 'message_text' is not of type 'bytes'") if key is None: key = self.get_key() elif not isinstance(key, bytes): raise TypeError("The argument 'key' is not of type 'bytes'") elif len(key) != 32: raise ValueError("The argument 'key' is not 256 bits in length") algorithm = AES(key) iv = self.get_iv() cipher = Cipher(algorithm, mode=modes.CBC(iv), backend=default_backend()) # .update() encrypts the message and .finalize() returns the encrypted data encrypted_text = cipher.encryptor().update(self.pad_data(message_text)) + cipher.encryptor().finalize() return encrypted_text, key, iv def get_key(self): """ Randomly generates a 256-bit AES key :return: a randomly generated byte String that is 32 bytes (or 256 bits) in length """ return urandom(32) def get_iv(self): """ Randomly generates an initial vector for the Cipher Block Chaining mode of encryption :return: a byte String that is 16 bytes (128-bits) in length """ return urandom(16) def pad_data(self, message): """ Pads the message if needed :param message: a byte String containing the non-encrypted message :return: a byte String that will be a multiple the AES 128-bit block size """ if message is None: message = "" elif isinstance(message, str): message.encode("utf-8") elif not isinstance(message, bytes): raise ValueError("The argument 'message' is not of type 'bytes'") # if the message is multiple of the 128-bit block size (16 bytes) then no padding is needed if len(message) % 16 == 0: return message else: padder = padding.PKCS7(128).padder() padded_data = padder.update(message) # returns the additional padded data padded_data += padder.finalize() # concatenates the padded data with the original data return padded_data
import urllib import json import datetime user_id = "" # Not needed api_id = "115d7627cf1dc308de3ae6111e2b33fd" zip_code = 30070 units = "imperial" def fetch_weather_data(zip_code): request_url = "http//api.openweathermap.org/data/2.5/weather?zip=" + str(zip_code) + "&units=" + units + "&appid=" + api_id try: url = urllib.urlopen(request_url) response = url.read().decode('utf-8') api_dict = json.loads(response) url.close() print_details(api_dict) except: print("Error: Could not fetch weather data. Check the API key and zip code.") def print_details(api_dict): location_name = api_dict["name"] current_temperature = api_dict["main"]["temp"] atmospheric_pressure = api_dict["main"]["pressure"] wind_speed = api_dict["wind"]["speed"] wind_direction = api_dict["wind"]["deg"] epoch_time = api_dict["dt"] formatted_date = datetime.datetime.fromtimestamp(epoch_time).strftime('%c') return_code = api_dict["cod"] if return_code == 200: #checks if the return code returns successful (200 is successful), and if not, it displays the error. print("Name: " + location_name) print("Current Temperature: " + str(current_temperature) + " degrees Fahrenheit") print("Atmospheric Pressure: " + str(atmospheric_pressure) + " hPa") print("Wind Speed: " + str(wind_speed) + " mph") print("Wind Direction: " + str(wind_direction)) print("Time of Report: " + formatted_date) else: print("Something went wrong.") if __name__ == "__main__": fetch_weather_data(zip_code)
import fileinput class Stack: def __init__(self, max_size): self.max = max_size self.items = [] def is_empty(self): return self.items == [] def push(self, item): if self.size() >= self.max: print('overflow') else: self.items.append(item) def pop(self): if self.is_empty(): print('underflow') else: print(self.items[-1]) self.items.pop() def peek(self): return self.items[len(self.items) - 1] def size(self): return len(self.items) def print(self): if self.size() > 0: print(*self.items, sep=" ") else: print('empty') bank = [] check = False for line in fileinput.input(): text = line.split('\n') bank += text while bank.count('') != 0: bank.remove('') if not bank: size = 0 i = int(0) while i < len(bank): if 'set_size' in bank[i]: if not check: check = True spl_text = bank[i].split() size = int(spl_text[1]) stack = Stack(size) else: print('error') i += 1 elif 'push' in bank[i]: if check: str_push = bank[i].split() if str_push[0] == 'push' and len(str_push) == 2: element = str_push[1] stack.push(element) else: print('error') else: print('error') i += 1 elif 'pop' in bank[i]: if check: if ' ' in bank[i]: print('error') elif bank[i] != 'pop': print('error') else: stack.pop() else: print('error') i += 1 elif 'print' in bank[i]: if check: if ' ' in bank[i]: print('error') elif bank[i] != 'print': print('error') else: stack.print() else: print('error') i += 1 else: print('error') i += 1
from random import * computerNumber = randint(1,10) # print "The correct number is: " + str(computerNumber) + ". This is for debugging purposes only -DELETE" playerGuess = raw_input("I have a number 1-10. Whats the number? ") if int(playerGuess) == computerNumber: print ("Correct!") if int(playerGuess) != computerNumber: print ("WRONGGGGGGGG!!!") # TODO Tell the user to guess higher or lower # TODO Keep asking until the answer is correct # BONUS TODO write using a while statement & then rewrite using a for loop
def StartOver(func): print("voulez-vous rejouer? (O/N)") answer = input() if (answer == "O" or answer == "o"): func() elif (answer == "N" or answer == "n"): print("Au revoir! ;)") return else: print("je n'ai pas compris votre réponse") func() #---------------------------------------------------------------------------------- def inputInt(msg,msgerr="❌ Veuillez saisir un nombre entier."): while True: try: return int(input(msg)) except: print(msgerr) #---------------------------------------------------------------------------------- def inputFloat(msg,msgerr="❌ Veuillez saisir un nombre entier ou décimal."): while True: try: return float(input(msg)) except: print(msgerr) #---------------------------------------------------------------------------------- def YorN(answer, func, modif, aff): if (answer == "O" or answer == "o"): StartOver(func) elif (answer == "N" or answer == "n"): modif() aff() else: print("je n'ai pas compris votre réponse") StartOver(func) #----------------------------------------------------------------------------------- def validInput(item, mynotes): while True: for i in range(0 <= item <= 20): return i else: print("📚 Désolée, mais une note doit être comprise entre 0 et 20 📚 \n") mynotes() #------------------------------------------------------------------------------------ def Answer(answer, liste): while True: if answer == 0 : print("d'accord! :p") break elif answer == 1 or answer == 2 or answer == 3 or answer == 4 or answer == 5 or answer == 6 or answer == 7 or answer == 8: print("---------------------------CONSIGNES DE MODIFICATIONS----------------------------------------------") print( "choix possibles des informations:", liste) print( "si vous n'entrez pas exactement l'une de ces valeurs lorsque l'information à modifier'vous sera demandé, une nouvelle ligne à la classe sera ajoutée") print( "il vous sera cependant possible de la supprimer! ^^ de ce fait il est également possible d'ajouter de nouvelles informations!") print( "-----------------------------------------------------------------------------------------------------") print() return answer else: print("(⊙_⊙)?...Je n'ai pas compris votre réponse") answer = inputInt("➢")
import sys sys.path.append('..') from PUtilitaires import StartOver from PUtilitaires import inputInt from PUtilitaires import inputFloat from PUtilitaires import inferior def rulesExo4(): print("Bonjour et bienvenu dans l'exo4!") #Hello and welcome in the fourth exercise! print("---------------------------FONCTION FACTORIELLE----------------------------------") #Factorial function print("après avoir choisit la valeur maximal de n ainsi que celle de x,") #after choosing the maximum value of n as well as that of x print("l'algorithme vous calculera la fonction e^x et sin(x)") #The algorithm will calculate the e^x and sin(x)'s function print("A vous de jouer! ;)") #Here you go! ;) print("----------------------------------------------------------------------------------") inputN() def inputN(): Nmax=inputInt("entrez la valeur Nmax:") #enter Nmax value inferior(Nmax, inputN) x= inputFloat("entrez la valeur de x:") #enter x value inferior(x, inputN) functions(Nmax, x) def functions(Nmax, x): e = 0 f=0 for n in range(0, Nmax+1): #n prend les valeurs de 0 à Nmax // n takes values from 0 to Nmax e += x**n/fact(n) #fonction e^x // e^x's function for m in range(0, Nmax+1): #m prend les valeurs de 0 à Nmax // m takes values from 0 to Nmax f += ((-1)**m) * (x**(2*m+1))/fact(2*m+1) print("fonction e^x:", round(e,5)) #afficher le résultat // display the result print("fonction sin(x):", round(f, 5)) StartOver(inputN) def fact(n): if n < 2: #factoriel de 0 et 1 = 1 // factorial of 0 and 1 = 1 return 1 else: #autrement //otherwhise return n * fact(n - 1) #factorielle de n = n * factorielle de n-1
# name = input("What is your Name? ") # print("My name is " + name + "!") print("Sum >") num1 = input("First Number : ") num2 = input("Second Number : ") num1 = int(num1) num2 = int(num2) print(num1 + num2) print(num1 - num2) print(num1 * num2) print(num1 / num2) print(num1 % num2) if(num1 % 2 == 0): print("num1 is even") else: print("num1 is odd")
file = open("input.txt", "r").read() # file = open("test.txt", "r").read() file = open("mitch.txt", "r").read() entries = file.split("\n") origin = None class planet: def __init__(self, name, orbits): self.name = name self.orbits = orbits def countOrbits(self): orbits = self.orbits count = 1 while orbits: count += 1 orbits = orbits.orbits return count planets = {} for entry in entries: things = entry.split(')') planets[things[1]] = planet(things[1], things[0]) for planet in planets.values(): if planet.orbits == 'COM': origin = planet planet.orbits = False else: planet.orbits = planets[planet.orbits] #find earliest shared def findShare(): current = planets['YOU'].orbits while current.orbits: dest = planets['SAN'].orbits while dest: if current.orbits == dest: return dest dest = dest.orbits current = current.orbits def distance(current, dest): count = 0 while current != dest: count += 1 current = current.orbits return count shared = findShare() # print(shared.name) # print(distance(planets['YOU'].orbits, shared)) # print(distance(planets['SAN'].orbits, shared)) print(distance(planets['YOU'].orbits, shared) + distance(planets['SAN'].orbits, shared)) for planet in planets: count = 0 for orbiting in planets.values(): if orbiting.orbits and orbiting.orbits.name == planet: count += 1 if count > 1: print(str(count) + ' orbit: ' + planet)
import array class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.last_node = None def insert(self, data): if self.last_node is None: #IF LAST NODE IS NULL SO NODE DATA INSIDE THE HEAD self.head = Node(data) self.last_node = self.head else: self.last_node.next = Node(data) self.last_node = self.last_node.next def print(self): current = self.head while current is not None: print(current.data, end=" ") current = current.next def search(self, element): current = self.head while current != None: if current.data == element: return True current = current.next return False def delete(self, element): current = self.head while current != None: if self.head.data == element: self.head = self.head.next break if current.data == element: self.last_node.next = current.next break self.last_node = current current = current.next def poll_first(self): self.last_node = self.head self.head = self.head.next return self.last_node.data def size_of_node(self): # it will return size of the node current = self.head size = 0 while current: size = size+1 current = current.next return size if __name__ == '__main__': arr = [] ll = LinkedList() fo = open("unorderlist.txt", "r") arr = fo.read() words = arr.strip().split(' ') fo.close() print("File Output: ") # inserting_into_list for i in words: ll.insert(i) ll.print() print() print("enter element to search in linked list") element = input() var = ll.search(element) if var: print("element found and removed from list") ll.delete(element) else: print("element not found") print(element, " is added to list") ll.insert(element) ll.print() node_size = ll.size_of_node() array = [] for i in range(node_size): array.append(ll.poll_first()) print() print(array) fo = open("unorderlist.txt", "w") for i in array: fo.write(i+" ") fo.close()
# importing necessary packages import pandas as pd import numpy as np import matplotlib.pyplot as plt # I followed the link below to learn how to read in the table of data from the website # https://towardsdatascience.com/web-scraping-html-tables-with-python-c9baba21059 url = 'https://questionnaire-148920.appspot.com/swe/data.html' tables = pd.read_html(url) data = tables[0] if (data.empty): raise Exception("Table was not read in correctly.") # removes null values and players with "no salary data" from dataframe num_players = len(data) data = data.dropna() data = data[data['Salary'] != "no salary data"] num_valid = len(data) # extracts corrected salary column from dataframe salary = data['Salary'] # I followed the answers at the link below to learn how to parse the salary data from strings with $ and , to floats # https://stackoverflow.com/questions/31521526/convert-currency-to-float-and-parentheses-indicate-negative-amounts/31521773 # converts currency values to floats salary = salary.replace('[\$,]','', regex=True).astype(float) # sorts salary values in descending order and selects the 125 largest values salary = salary.sort_values(ascending = False) top_125 = salary[0:125] offer = round(top_125.mean(), 2) print("\nQUALIFYING OFFER") print("The value of the qualifying offer is ${:,}".format(offer)) # head of the dataset and number of elements print("\nHEAD OF DATASET (CORRECTED FOR MISSING VALUES)") print(data.head(n = 5)) print("\nOf the {} players in the data, {} had valid salary data.".format(num_players, num_valid)) # five number summary and mean of the salaries print("\nFIVE NUMBER SUMMARY AND MEAN OF SALARY") print("Minimum Salary :: ${:,.2f}".format(salary.min())) print("Q1 Salary :: ${:,.2f}".format(np.percentile(salary, 25))) print("Median Salary :: ${:,.2f}".format(salary.median())) print("Mean Salary :: ${:,.2f}".format(salary.mean())) print("Q3 Salary :: ${:,.2f}".format(np.percentile(salary, 75))) print("Maximum Salary :: ${:,.2f}\n".format(salary.max())) # distribution of salaries # converting salaries to millions for sake of plot readability graphing_salary = salary / 1000000 plt.figure(figsize = (10, 5)) plt.title("Salary Distribution for All Players (Dollars in Millions)") plt.xlabel("Salary (in millions of dollars)") plt.ylabel("Frequency") plt.xticks(np.arange(0, 40, step = 2.5)) plt.hist(graphing_salary, bins = 15, color = "b") # distribution of the top 125 salaries for a closer look # converting salaries to millions for sake of plot readability graphing_top_125 = top_125 / 1000000 plt.figure(figsize = (8, 5)) plt.title("Distribution of the 125 Largest Salaries (Dollars in Millions)") plt.xlabel("Salary (in millions of dollars)") plt.ylabel("Frequency") plt.xticks(np.arange(0, 40, step = 2.5)) plt.hist(graphing_top_125, bins = 8, color = "r") plt.show()
from pyspark.sql import SparkSession from pyspark.ml.clustering import KMeans spark = SparkSession \ .builder \ .appName("DataFrameExample") \ .getOrCreate() # Loads data. dataset = spark.read.format("libsvm").load("sample_kmeans_data.txt") # Trains a k-means model. kmeans = KMeans().setK(2).setSeed(1) model = kmeans.fit(dataset) # Evaluate clustering by computing Within Set Sum of Squared Errors. wssse = model.computeCost(dataset) print("Within Set Sum of Squared Errors = " + str(wssse)) # Shows the result. centers = model.clusterCenters() print("Cluster Centers: ") for center in centers: print(center)
from datetime import date, timedelta from docx import Document import os DAYS = d = {'Mon': 0, 'Tue': 1, 'Wed': 2, 'Thu': 3, 'Fri': 4, 'Sat': 5, 'Sun': 6} days = 0 course_day = [] course_title = [] d1 = date.today() print(d1) starting_day = 0 def input_system(): global d1, course_day, course_title, days, starting_day # can we do like this?? d1_temp = input("Starting date (year month day) : ").split() d1 = date(int(d1_temp[0]), int(d1_temp[1]), int(d1_temp[2])) d2_temp = input("Ending date (year month day) : ").split() d2 = date(int(d2_temp[0]), int(d2_temp[1]), int(d2_temp[2])) days = (d2 - d1).days starting_day = d1.weekday() # this gives a day of specifc date nCourse = int(input("How many courses are you taking now : ")) course_day_temp = [] for i in range(nCourse): course_title.append(input("Course Name : ")) course_day_temp.append(input("Enter day of class occurrences \n(Mon Tue Wed Thu Fri Sat Sun)\n").split()) course_day.append([]) for j in range(len(course_day_temp[i])): course_day[i].append(DAYS[course_day_temp[i][j]]) def date_valid(course_day, day): # Keita for i in range(len(course_day)): if course_day[i] == day: return True return False def create_folder(course_title): if not os.path.exists(course_title): os.mkdir(course_title) def create_file(date, course_title): month_arr = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] suffix_date_dict = {0: "th", 1: "st", 2: "nd", 3: "rd", 4: "th"} suffix_date = suffix_date_dict[date.day % 10 if date.day % 10 < 4 else 4] document = Document() heading = str(month_arr[date.month - 1]) + " " + str(date.day) + suffix_date + " " + course_title document.add_paragraph(heading) document.save(course_title + "/" + heading + ".docx") WEEK = 7 input_system() for i in range(len(course_title)): create_folder(course_title[i]) for n in range(days): day = (starting_day + n) % WEEK for i in range(len(course_day)): if (date_valid(course_day[i], day)): print(course_title[i], end=" ") print(d1 + timedelta(n)) create_file(d1 + timedelta(n), course_title[i])
""" Your task is to write a function which returns the sum of following series upto nth term(parameter). Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +... Rules: You need to round the answer to 2 decimal places and return it as String. If the given value is 0 then it should return 0.00 You will only be given Natural Numbers as arguments. Examples: SeriesSum(1) => 1 = "1.00" SeriesSum(2) => 1 + 1/4 = "1.25" SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57" ***NOTE: each addition to the series is increasing by 1/(3n -2) """ def series_sum(x): c = 0 for n in range(0,x+1): if n >= 1: d = 1/(3*n-2) c += d return f'{c:.2f}'
idade = int(input("Digite sua idade: ")) if idade >= 18: print("Vc é maior de idade") elif idade == 0: print("vc ainda nao nasceu") else: print("Vc é menor de idade")
''' Simple function that takes a list square its elements and returns another list ''' def square(list_num): results = [] for i in list_num: results.append(i*i) return results list_num = range(1,10) sqr_list = square(list_num) print(sqr_list) ''' Modifying the code above to produce a Generator ''' def square(list_num): for i in list_num: yield i*i list_num = range(1,10) sqr_list = square(list_num) print(sqr_list) # prints the generator object reference print(next(sqr_list)) # because generators produce an iterator you can call next on the object print(next(sqr_list)) # Since sqr_list is an iterable you can use a for loop on them for i in sqr_list: print(i) # Create Generators from list comprehension ############################################# sqr_list = [ x * x for x in range(1,11)] # To convert a list comprehension to a generator just replace the [] by () sqr_list = ( x * x for x in range(1,11)) print(sqr_list) for i in sqr_list: print(i)
"""Problem: Created By: AJ Singh Date: April 13, 2021 Time: 12:20 AM MST Time Taken: Here are my problem-solving thoughts, and explanations of each solution I constructed. I did some rough work on paper before I started coding, and am sharing what I did here. +++++ General Ideas/First Thoughts +++++ +++++ Approach #1: Mathematical Approach +++++ +++++ Approach #2: Iterative Approach +++++ +++++ Analysis & Optimizations +++++ +++++ Final Comments +++++ Thank you for taking the time to read this preamble, and for looking at my code below. I hope you and your team are staying safe and healthy. - AJ """ def sum_square_difference(n): return int((n*(n+1)/2)**2 - n*(n+1)*(2*n+1)/6) if __name__ == "__main__": x = 10 target = 2640 result = sum_square_difference(x) assert result == target x = 100 print(sum_square_difference(x))
"""Problem: Given a string, return the longest palindromic substring. Created By: AJ Singh Date: April 7, 2021 Time: 1:20 PM MST Time Taken: 1 hour 13 minutes Here are my problem-solving thoughts, and explanations of each solution I constructed. I did some rough work on paper before I started coding, and am sharing what I did here. +++++ General Ideas/First Thoughts +++++ - Would it matter if the substring has even or odd length? - Can use two pointers, both will travel outwards - Would need to check if there is the same element repeated multiple times at the "center" of a substring. - So I can just use an iterative approach (this may be the brute-force/non-optimal solution though?). +++++ Assumptions +++++ - We will assume that substrings are *contiguous*. - We will take any punctuation, spaces, etc *into account*. +++++ Approach #1: Iterative Approach +++++ - We only need to iterate through the entire string once. - The two pointers will start at the same index. - Then we will determine if there is a contiguous substring of all similar elements (if any) - Then we will move the pointers simultaneously outwards - Can stop (and hence go to next string element) if the pointers go out-of-index (ie. the entire string is a palindrome) OR if two outer elements are non-equal. +++++ Analysis & Optimizations +++++ - The iterative approach has quadratic time complexity - The space complexity is O(r), where r is the length of the current longest substring. - I feel like there is a way to make this more optimal by taking into account the index in the string we are on, and the length of the current substring found so far. +++++ Final Comments +++++ Thank you for taking the time to read this preamble, and for looking at my code below. I hope you and your team are staying safe and healthy. - AJ """ import unittest class TestProgram(unittest.TestCase): def test_case_1(self): x = "xyzzyx" expected = "xyzzyx" result = longest_palindrome(x) self.assertEqual(result, expected) def test_case_2(self): x = "axyzzyx" expected = "xyzzyx" result = longest_palindrome(x) self.assertEqual(result, expected) def test_case_3(self): x = "xyzzyxa" expected = "xyzzyx" result = longest_palindrome(x) self.assertEqual(result, expected) def test_case_4(self): x = "xyzazyx" expected = "xyzazyx" result = longest_palindrome(x) self.assertEqual(result, expected) def test_case_5(self): x = "xyz" expected = "x" result = longest_palindrome(x) self.assertEqual(result, expected) def test_case_6(self): x = "a" expected = "a" result = longest_palindrome(x) self.assertEqual(result, expected) def test_case_7(self): x = "" expected = "" result = longest_palindrome(x) self.assertEqual(result, expected) def test_case_8(self): x = "aaa" expected = "aaa" result = longest_palindrome(x) self.assertEqual(result, expected) def longest_palindrome(string): if len(string) in {0, 1}: return string result = "" for index in range(len(string)): current_element = string[index] left_pointer = index right_pointer = index while right_pointer < len(string)-1: # Check if there is a contiguous substring of all-equal elements. if string[right_pointer + 1] == current_element: right_pointer += 1 else: break while left_pointer > 0 and right_pointer < len(string)-1: # Check if you're strictly inside the string. if string[left_pointer-1] == string[right_pointer+1]: # Move pointers outwards simultaneously. left_pointer -= 1 right_pointer += 1 else: break if len(string[left_pointer:right_pointer+1]) > len(result): result = string[left_pointer:right_pointer+1] if len(result) == len(string): break return result if __name__ == "__main__": # For manual testing. x = "xyzzzyx" print(longest_palindrome(x)) # For automatic testing. unittest.main()
"""Problem: Determine the sum of all primes less than or equal to n. Created By: AJ Singh Date: April 13, 2021 Time: 7:55 PM MST Time Taken: Here are my problem-solving thoughts, and explanations of each solution I constructed. I did some rough work on paper before I started coding, and am sharing what I did here. +++++ General Ideas/First Thoughts +++++ +++++ Approach #1: Mathematical Approach +++++ +++++ Approach #2: Iterative Approach +++++ +++++ Analysis & Optimizations +++++ +++++ Final Comments +++++ Thank you for taking the time to read this preamble, and for looking at my code below. I hope you and your team are staying safe and healthy. - AJ """ from math import sqrt def sum_of_primes(n): primes = [2] test = 3 while test <= n: if all(test % prime != 0 for prime in primes if prime < int(sqrt(test)) + 1): primes.append(test) test += 2 return sum(primes) if __name__ == "__main__": x = 10 print(f"The sum of primes up to {x} is: {sum_of_primes(x)}")
import numpy as np from datetime import datetime x=int(input('숫자 얼마까지 덧셈을 할까요? ')) #print("\n") score = 0 ts=datetime.now() for i in range(10): a=np.random.randint(1,x+1) b=np.random.randint(1,x+1) #print("%2d + %2d = %2d" %(a,b,a+b)) y=input("%2d) %2d + %2d = " %(i+1,a,b)) if int(y) == (a+b): score = score +10 print("Excellent ! %2d + %2d = %2d\n" %(a,b,a+b)) else: print("Think again ! %2d + %2d = %2d\n" %(a,b,a+b)) te=datetime.now()-ts print ("\n Your score is %d \n"%(score)) print ("It took %d minutes %d seconds \n\n"%(te.seconds//60, te.seconds%60))
Casos = int(input()) for i in range(Casos): Comida = float(input()) Dias = 0 while Comida > 1: Comida /= 2 Dias += 1 print("{:d} dias".format(Dias))
Pares = 0 for i in range(5): Num = int(input()) if Num % 2 == 0: Pares += 1 print("{:d} valores pares".format(Pares))
def to_roman(Number): Roman_Numbers = {1 : 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD', 500: 'D',900: 'CM',1000: 'M'} Temp_num = [x for x in str(Number)] Result = '' Numbers = dict.keys(Roman_Numbers) print() if Number > 99: Temp_num[0] += '00' Temp_num[1] += '0' elif Number <= 99: Temp_num[0] += '0' Temp_num = [int(i) for i in Temp_num] for N in Temp_num: if N in Numbers: Result += Roman_Numbers[N] else: for X in range(len(Numbers)): if Numbers[X] < N and N < Numbers[X+1]: print(N-Roman_Numbers[Numbers[X]]) to_roman(int(input()))
Casos = int(input()) for i in range(Casos): Jogo = input() if int(Jogo[0]) != int(Jogo[2]): if Jogo[1].islower(): print(int(Jogo[0])+int(Jogo[2])) continue else: print(int(Jogo[2])-int(Jogo[0])) else: print(int(Jogo[0])*int(Jogo[2]))
goal_number = 100 def check_number(x): if x == goal_number : print("congratulations. You won, Your number is right") elif goal_number < x: print("the number is lower") else: print("the number is higher") programm_running = True while(programm_running): inp = input("guess the number: ") inp = int(inp) check_number(inp) ''' Explain 1. Explain game: Set a number that someone guess 2. Define your Iteration - "Your number is {}" '''
# making edits wooooo def output(days): initial_infected = 7 reproduction_rate = 1.2 population = 39740 tuition = 9972 total = calc_total_infected(days, initial_infected, reproduction_rate) percentage = total / population print(f"total num infected: {total}") print(f"percentage of students infected: {percentage}") if days<= 14 : print(f"Total num withdrew: {total}") print(f"amount temple loses: {total * tuition}") def calc_total_infected(days, iniyisl_infected, reproduction_rate): if days==0: return initial_infected return reproduction_rate * calc_total_infected(days-1, inital_infected, reproduction_rate) temp = "y" while temp == "y" user_input - input("Enter an amouny of days") output(int(user_input)) temp = input("Do you want to keep going [y/n]")
number = int(input('please enter number : ')) checkingType = int(input('please select cheking type 1 - with for loop , 2 - with minimum symbols ')) def t2(n): return sum([int(k) for k in str(n)]) if __name__ == "__main__": if checkingType == 1 : result = 0 while number > 0 : result += number % 10 number //= 10 print(result) elif checkingType == 2 : print(t2(number)) else : print('wrong inputs') #FIXED
import pandas as pd import numpy as np row = ['Person1','Person2','Person3'] data = [['Vlad','Harutyunyan',50,'Armenia'],['Vlad','Harutyunyan',30,'Armenia'],['Vlad','Harutyunyan',20,'Armenia']] col = ['Name','Surname','Age','Country'] df = pd.DataFrame(data=data,index=row,columns=col) print(df) c1 = df.reset_index() #indexation , inplace=true for saving result print(c1) c2 = df.reset_index(level=0) print(c2) c3 = c1.drop([0,2]) print(c3) print(df.shape) print(c2[c2['Age'] < 30]) df['Country'].replace({'Armenia':'Arm'},inplace=True) print(df)
#!/usr/bin/env python3 """This program can tell you who loves who by the sentences it read either from file or from prompted text. Multiline input is supported """ import argparse import sys def get_argparser(): """Builds and returns a suitable argparser""" parser = argparse.ArgumentParser(description='') parser.add_argument('-f', '--file', nargs=1, type=str, help='Read info from file') parser.add_argument('-l', '--line', nargs='+', type=str, help='Read info from promted sentence') parser.add_argument('-d', '--describe', action='store_true', help='Get list of all people program\ knows something about') parser.add_argument('-q', '--question', nargs='+', type=str, help='Ask a program abouta certain person\ in form `Who likes X`, `Whom loves X`,\ `X hates` or simply `X`') parser.add_argument('-e', '--exit', action='store_true', help='exit the program') return parser class RelationsGraph(object): """Graph with Names as vertices and direcnted edges of 3 types: loves/likes/hates """ def __init__(self, graph_dict=None): """Initializes graph with a dict given or sets it empty by default Args: graph_dict: { name : { action : list(str) } } """ if graph_dict is None: self.__dict = {} else: self.__dict = graph_dict def add_edge(self, atom): """Adds edge from atomic expression Args: atom (list[string]): [subject, action, object] """ if atom[0] not in self.__dict: self.__dict[atom[0]] = {atom[1]: [atom[2]]} elif atom[1] not in self.__dict[atom[0]]: self.__dict[atom[0]][atom[1]] = [atom[2]] else: self.__dict[atom[0]][atom[1]] += [atom[2]] def __optional_passive(self, action, reverse): """If reverse == True, transformes a verb to passive voice""" if reverse: return "is {}d by".format(action[:-1]) else: return action def __smart_commas(self, arr): """Converts list(str) to a single string with formatting: [A, B, C] -> 'A, B and C' """ if len(arr) > 1: return ', '.join(arr[:-1]) + ' and ' + arr[-1] else: return arr[0] def get_list_of_people(self): """Returns list of vertices""" return list(self.__dict.keys()) def describe_persons_action(self, person, action, reverse=False, short=False): """Describes one persons's attitude Args: person (string): person's name action (string): loves/likes/hates reverse (bool): special option to interract with reverse graph short (bool): option to ommit the subject Returns: string: verbalization of persons attitude """ if person not in self.__dict: return "No information on {}".format(person) if action not in self.__dict[person]: if reverse: return "No information on who {} {}".format(action, person) else: return "No information on whom {} {}".format(person, action) objects_str = self.__smart_commas(self.__dict[person][action]) lemmas = [person, self.__optional_passive(action, reverse), objects_str] if short: lemmas = lemmas[1:] output_line = ' '.join(lemmas) return output_line.strip() def describe_person(self, person, reverse=False): """Describes all persons's attitudes Args: person (string): person's name Returns: string: verbalization of persons all attitudes """ if person not in self.__dict: return '' actions = list(self.__dict[person].keys()) descriptions = [self.describe_persons_action(person, action, reverse, True) for action in actions] output_line = person + ' ' + self.__smart_commas(descriptions) return output_line def parse_statement(statement): """Converts a complex statement into list of atomic statements Args: statement (string): a complex statement Returns: list(list(str)): a list of atomic structures [subject, action, object] """ if not len(statement): return [] simple_text = statement.rstrip('.') for word in (',', 'and', 'but'): simple_text = simple_text.replace(word, '') lemmas = [x.strip() for x in simple_text.split(' ') if len(x.strip())] actions = ['loves', 'likes', 'hates'] cur_subject = lemmas[0] cur_action = lemmas[1] atoms = [] for i in range(2, len(lemmas)): if lemmas[i] not in actions: atoms.append([cur_subject, cur_action, lemmas[i]]) else: cur_action = lemmas[i] return atoms def update_graphs_with_statement(statement, graph, reverse_graph): """Update graphs with edges derived from the statement Args: graph (Graph): relations graph reverse_graph (Graph): inverted relations graph statement (str): statement to analyze """ atoms = [] for sentence in statement.split('.'): atoms += parse_statement(sentence) for atom in atoms: graph.add_edge(atom) reverse_graph.add_edge(atom[::-1]) def update_graphs_from_file(filename, graph, reverse_graph): """Update graphs with edges derived from the statements from the file Args: graph (Graph): relations graph reverse_graph (Graph): inverted relations graph filename (str): file with statements to analyze """ with open(filename, 'r') as infile: for line in infile.readlines(): update_graphs_with_statement(line.strip(), graph, reverse_graph) def answer_question(question, graph, reverse_graph): """Derives subject and action from the question and gives a verbal answer """ lemmas = [x.strip() for x in question.strip().split(' ') if x.strip() != ''] if lemmas[0].lower() == 'whom': if lemmas[1] in ['loves', 'hates', 'likes']: action = lemmas[1] person = lemmas[2] else: action = lemmas[2] person = lemmas[1] print(graph.describe_persons_action(person, action)) elif lemmas[0].lower() == 'who': if lemmas[1] in ['loves', 'hates', 'likes']: action = lemmas[1] person = lemmas[2] else: action = lemmas[2] person = lemmas[1] print(reverse_graph.describe_persons_action(person, action, True)) elif len(lemmas) == 2: action = lemmas[1] person = lemmas[0] print(graph.describe_persons_action(person, action)) elif len(lemmas) == 1: forward = graph.describe_person(lemmas[0]) backward = reverse_graph.describe_person(lemmas[0], True) if len(forward) == 0 and len(backward) == 0: print("No information on {}.".format(lemmas[0])) elif forward == '' or backward == '': print(forward + backward + '.') else: print('. '.join([forward, backward]) + '.') else: print("The question is unclear. Try --help") def process_input(arg_parser, graph, reverse_graph): """Waits for multiple inputs and processes them""" args = arg_parser.parse_args() process_args(args, graph, reverse_graph) while True: line = input() args = arg_parser.parse_args([line]) process_args(args, graph, reverse_graph) def process_args(args, graph, reverse_graph): """Converts inputs into graph operations""" if args.file: filename = args.file[0].strip() update_graphs_from_file(filename, graph, reverse_graph) if args.line: statement = ' '.join(args.line).strip() update_graphs_with_statement(statement, graph, reverse_graph) if args.question: question = ' '.join(args.question).strip() answer_question(question, graph, reverse_graph) if args.describe: print("All Subjects: " + ', '.join(graph.get_list_of_people())) print("All Objects: " + ', '.join(reverse_graph.get_list_of_people())) if args.exit: sys.exit(0) def main(): parser = get_argparser() graph = RelationsGraph() reverse_graph = RelationsGraph() process_input(parser, graph, reverse_graph) if __name__ == "__main__": main()
"""pygame package will allow access to the Sprite class.""" import pygame class Player: """Creates a character which is controllered by a player.""" def __init__(self, group, image, x, y, tile_size): """Constructor method for Player class. Defines an image and position.""" self.x = x self.y = y self.sprite = pygame.sprite.Sprite(group) self.image_left = image self.image_right = pygame.transform.flip(image, True, False) self.sprite.image = self.image_right self.sprite.rect = image.get_rect(x = x * tile_size, y = y * tile_size) self.tile_size = tile_size self.move_counter = 0 def setPosition(self, x, y): """Set the player's co-ordinates.""" self.x = x self.y = y self.sprite.rect = self.sprite.image.get_rect(x = x * self.tile_size, y = y * self.tile_size) def moveLeft(self): """Move the player to the left and increase the move counter.""" self.setPosition(self.x - 1, self.y) self.move_counter += 1 def moveRight(self): """Move the player to the right and increase the move counter.""" self.setPosition(self.x + 1, self.y) self.move_counter += 1 def moveUp(self): """Move the player up and increase the move counter.""" self.setPosition(self.x, self.y - 1) self.move_counter += 1 def moveDown(self): """Move the player down and increase the move counter.""" self.setPosition(self.x, self.y + 1) self.move_counter += 1 def turnLeft(self): """Turn the player to the left.""" self.sprite.image = self.image_left def turnRight(self): """Turn the player to the right.""" self.sprite.image = self.image_right def getX(self): """Returns the player's X co-ordinate.""" return self.x def getY(self): """Returns the player's Y co-ordinate.""" return self.y def getMoveCounter(self): """Returns the player's move counter.""" return self.move_counter
#Exercise Question 3: Given a list slice it into a 3 equal chunks and rever each list #Origigal list [11, 45, 8, 23, 14, 12, 78, 45, 89] # Chunk 1 [11, 45, 8] #After reversing it [8, 45, 11] #Chunk 2 [23, 14, 12] #After reversing it [12, 14, 23] # Chunk 3 [78, 45, 89] #After reversing it [89, 45, 78] import sys #%%%%%%%%%%%%%%%%%first solution%%%%%%%%%%%%%%%%%%%%%%% #sList=[11, 45, 8, 23, 14, 12, 78, 45, 89] #L1=[] #L2=[] #L3=[] #for i in sList[0:3]: # L1.append(i) # L1.reverse() #print(L1) #for j in sList[3:6]: # L2.append(j) # L2.reverse() #print(L2) #for k in sList[6:9]: # L3.append(k) # L3.reverse() #print(L3) #%%%%%%%%%%%%%%%%%second solution%%%%%%%%%%%%%%%%%%%%%%%% sList=[11, 45, 8, 23, 14, 12, 78, 45, 89] length=len(sList) chunksize=int(length/3) start=0 end=chunksize for i in range(1,4,1): indexes=slice(start,end,1) listchunk=sList[indexes] print("after reversing it: ", list(reversed(listchunk))) start=end if(i!=2): end+=chunksize else: end+=length-chunksize
import sys import math import matplotlib.pyplot as plt ##def histogram(items): # for n in items: # output='' # times=n # while times>0: # output+='@' # times-=1 # print(output) #histogram([9,2,4,5,3]) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Write a Python program to concatenate all elements in a list into a string and return it #def concatenate(lisst): # stringg='' # for n in lisst: # stringg+=n #print(stringg) #ll=input("enter the list of letters: ") #lisst=ll.split(",") #concatenate(lisst) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Write a Python program to print all even numbers from a given numbers list in the same order and stop the printing if any numbers that come after 237 in the sequence. #numbers = [ # 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, # 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, # 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, # 958,743, 527 # ] #def printing(numbers): # for n in numbers: # if n==237: # print(n) # break; # elif (n%2==0): # print(n) #numbers = [386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958,743, 527] #printing(numbers) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2. #def colorlist(tset): #color_list_1 = set(["White", "Black", "Red"]) #color_list_2 = set(["Red", "Green"]) # for n in color_list_1: # if n not in color_list_2: # tset.append(n) #tset=set() #print(color_list_1.difference(color_list_2)) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Write a Python program to compute the greatest common divisor (GCD) of two positive integers. #def gcd(x, y): # gcd = 1 # if x % y == 0: # return y # for k in range(int(y / 2), 0, -1): # if x % k == 0 and y % k == 0: # gcd = k # break # return gcd #print(gcd(12, 17)) #print(gcd(4, 6)) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Write a Python program to get the least common multiple (LCM) of two positive integers. #def lcd(x,y): # if x>y: # z=x # else: # z=y # while(True): # if (z%x==0 and z%y==0): # lcd=z # return lcd #z+=1 #print(lcd(4,6)) #print(lcd(15,17)) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Write a Python program to sum of three given integers. However, if two values are equal sum will be zero #x=int(input("enter a n1")) #y=int(input("enter a n2")) #z=int(input("enter a n3")) #k=0 #if (x==y or x==z or y==z): # k=x+y+z # k=0 # print(k) #else: # print(x+y+z) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Write a Python program to sum of two given integers. However, if the sum is between 15 to 20 it will return 20. #def summ(x,y): # z=x+y # if z in range (15,20): # sum=20 # return sum # else: # return z #x=int(input("enter a number: ")) #y=int(input("enter a number: ")) #print(summ(x,y)) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Write a Python program that will return true if the two given integer values are equal or their sum or difference is 5 def values(x,y): z=x+y k=x-y if (x==y or z==5 or k==5): return True x=int(input("enter a number: ")) y=int(input("enter a number: ")) print(values(x,y))
import sys def multiplication_or_sum(num1, num2): product= num1*num2 if (product>1000): return product else: return num1+num2 num1= int (input ("enter first number")) num2= int (input ("enter second number")) result= multiplication_or_sum(num1, num2) print("the result: ", result)
#Question 4: Pick a random charcter from a given String import sys import random sst= "sevilay" CHAR= random.choice(sst) print("random character form text: ", CHAR)
import sys import random #Write a Python program to check the sum of three elements (each from an array) from three arrays is equal to a target value. Print all those three-element combinations. #Sample data: #/* #X = [10, 20, 20, 20] #Y = [10, 20, 30, 40] #Z = [10, 30, 40, 20] target = 70 #*/ hit=[] X = [10, 20, 20, 20] Y = [10, 20, 30, 40] Z = [10, 30, 40, 20] for i in X: for j in Y: for k in Z: #l=i+j+k if (i+j+k)==target and (i,j,k) not in hit: hit.append((i,j,k)) print(set(hit)) result=[] for i in range(40): A=[1,2,3] random.shuffle(A) if A not in result: result.append(A) print(result) X = [1,2,3] result=[] for a in X: for b in X: for c in X: if (a+b+c)==sum(X) and a!=b!=c: perm=(a,b,c) result.append(perm) print(result)
import sys import os, platform #Write a Python program to find the operating system name, platform and platform release date. print("the opersating system name") print(os.name) print("the platform system") print(platform.system()) print("the platform release") print(platform.release()) print(isinstance(25,int) or (isinstance("25",str))) print(isinstance([25],int)) print(isinstance(["25"],str)) print(isinstance("25",str) or (isinstance("25",str))) #Write a Python program to test if a variable is a list or tuple or a set. x=('tuple', False, 3.2,1) if type(x) is list: print("the variable is a list") elif type(x) is set: print("the variable is a set") elif type(x) is tuple: print("the variable is a tuple") else: print("Neither a list or tuple or set")
import sys # Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. # ss=[] for i in range(2000,3200): if (i%7)==0 and (i%5)!=0: ss.append(str(i)) print (','.join(ss))
import sys import json print("enter the integer values") x,y=map(int,input().split()) print("the integer values is ", x,y) #Write a Python program to print a variable without spaces between values. x="30" v=json.dumps(x) print("the variable of x",v) y=3 print('the value of x "{}"'.format(y))
import re #Write a Python program to find the substrings within a string. #Sample text :'Python exercises, PHP exercises, C# exercises' #Pattern :'exercises' #Write a Python program to abbreviate 'Road' as 'Rd.' in a given string. text= 'Everything will be fine soon 1234 Read and it is goining to be nice 12' pattern="Read" z=re.search(pattern, text) print(z.group(0)) patt="Read" s=re.sub("R\w+","Rd\.",patt) print(s) # Write a Python program to separate and print the numbers and their position of a given string. #text= 'Everything will be fine soon 1234 and it is goining to be nice 12' #for element in re.finditer("\d+",text): # print(element.group(0)) # print("Index Position= ", element.start()) #Write a Python program to find all words starting with 'a' or 'e' in a given string. #text= 'Everything awill be afine soon 1234 and it is goining to be nice 12' #m=re.findall("ae\w+", text) #print(m) #Write a Python program to separate and print the numbers of a given string. #text= 'Everything will be fine soon 1234 and it is goining to be nice 12' #result=re.split("\d+",text) #for element in result: # print(element) #Write a Python program to match if two words from a list of words starting with letter 'P' # Sample strings. #words = ["Python PHP", "Java JavaScript", "c c++"] #for w in words: # m = re.match("(P\w+)\W(P\w+)", w) # # Check for success # if m: # print(m.groups()) #Write a Python program to convert a date of yyyy-mm-dd format to dd-mm-yyyy format. #def subst(url): # return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\\3-\\2-\\1', url) #url='2016-09-02' #print(subst(url)) #Write a Python program to extract year, month and date from a an url. #def findDate(url): # return re.findall(r'\d{4}/\d{1,2}/\d{1,2}',url) #url= "https://www.washingtonpost.com/news/football-insider/wp/2016/09/02/odell-beckhams-fame-rests-on-one-stupid-little-ball-josh-norman-tells-author/" #print(findDate(url)) #Write a Python program to replace whitespaces with an underscore and vice versa. #text='Ali_albazi has four cats' #match= re.sub(r'[_]', ' ', text) #print(match) #match= text.replace(' ', '_') #print(match) #text='Python exercises, PHP exercises, C# exercises' #pattern = 'exercises' #Write a Python program to find the occurrence and position of the substrings within a string. #for match in re.finditer(pattern,text): #s=match.start() #e=match.end() #print('Found "%s" at %d:%d' % (text[s:e], s, e))
#! python 3 import re #1-What is the function that creates Regex objects? ##regexObject=re.compile(r'blabla') #2-2. Why are raw strings often used when creating Regex objects? #3. What does the search() method return? retrun first much of values #4. How do you get the actual strings that match the pattern from a Match object? regexObject=re.compile(r'abc'), regexObject.findall.text(adeabc) #5. In the regex created from r'(\d\d\d)-(\d\d\d-\d\d\d\d)' , what does group 0 cover? Group 1 ? Group 2 ?group0=the whole numbers, group1= area code, group2=actual number #6. Parentheses and periods have specific meanings in regular expression syntax. How would you specify that you want a regex to match actual parentheses and period characters? \) \. #7. The findall() method returns a list of strings or a list of tuples of strings. What makes it return one or the other? by puting question mark #What does the | character signify in regular expressions?it is for choose between two options numRegex = re.compile(r'\d+') , what will numRegex.sub('X', '12 drummers, 11 pipers, five rings, 3 hens')
#Exercise Question 5: Given a string input Count all lower case, upper case, digits, and special symbols #input_str = "P@#yn26at^&i5ve" #Total counts of chars, digits,and symbols Chars = 8 Digits = 3 Symbol = 4 import sys inputStr="P@#yn26at^&i5ve" sml=0 cap=0 digit=0 say=0 for char in inputStr: if char.islower(): sml+=1 elif char.isupper(): cap+=1 elif char.isdigit(): digit+=1 else: say+=1 print("loweChar= ", sml, "upperChar= ", cap, "number of digits= ", digit, "nmbers: ", say)
#!/usr/bin/python # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ import sys import re """Baby Names exercise Define the extract_names() function below and change main() to call it. For writing regex, it's nice to include a copy of the target text for inspiration. Here's what the html looks like in the baby.html files: ... <h3 align="center">Popularity in 1990</h3> .... <tr align="right"><td>1</td><td>Michael</td><td>Jessica</td> <tr align="right"><td>2</td><td>Christopher</td><td>Ashley</td> <tr align="right"><td>3</td><td>Matthew</td><td>Brittany</td> ... Suggested milestones for incremental development: -Extract the year and print it -Extract the names and rank numbers and just print them -Get the names data into a dict and print it -Build the [year, 'name rank', ... ] list and print it -Fix main() to use the extract_names list """ def extract_names(filename): """ Given a file name for baby.html, returns a list starting with the year string followed by the name-rank strings in alphabetical order. ['2006', 'Aaliyah 91', Aaron 57', 'Abagail 895', ' ...] """ # open the file f = open(filename, 'r') # create an empty dictionary dict = {} # give year more scope year = 0 # iterate over the file's lines (runs in O(n) where n is the number of lines in the file) for line in f: # match h3 line h3 = re.search(r'h3[^/]+' ,line) # can you match anything up to a string, not just a char (^\w)? if h3: year = (re.search(r'\d\d\d\d', h3.group())).group() # find year else: names = re.findall('<td>\w+', line) # find all occurences of <td> if names: rank = str((names[0]))[4:] # use slices to jump over tags boy = str((names[1]))[4:] girl = str((names[2]))[4:] # if either of these keys are already in the dictionary, don't put them in again if boy in dict.keys(): dict[girl] = rank elif girl in dict.keys(): dict[boy] = rank else: dict[boy] = rank dict[girl] = rank # close file f.close() # get the items out of the dict; returns list of tuples (O(m) in the worst case where m is the number of things in the dictionary) items = dict.items() # create empty list expanded = [] # for each list item (rank, (boy's name, girl's name)) (O(m)) for i in items: name, rank = i # match on tuple expanded.append(name + ' ' + rank) # put name and rank into list # sort list (O(nlogn)) sorted_list = sorted(expanded) # concatenate year onto list sorted_with_year = [year] + sorted_list # return list (total complexity = 2*O(m) + O(n) + O(nlogn) -> O(nlogn) which should be the bound since I'm sorting) return sorted_with_year def main(): # This command-line parsing code is provided. # Make a list of command line arguments, omitting the [0] element # which is the script itself. args = sys.argv[1:] if not args: print 'usage: [--summaryfile] file [file ...]' sys.exit(1) # Notice the summary flag and remove it from args if it is present. summary = False if args[0] == '--summaryfile': summary = True del args[0] # For each filename, get the names, then either print the text output # or write it to a summary file output = extract_names(args[0]) if summary: if len(args) != 2: print 'Please give me an output file.' return else: f = open(args[1], 'w') for i in range (len(output)): f.write(str(output[i]) + '\n') f.close else: for i in range (len(output)): print output[i] if __name__ == '__main__': main()
#!/usr/bin/python def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) # 5 -> (fib(4) + fib(3)) -> (fib(3) + fib(2) | fib(2) + fib(1)) | (fib(2) + fib(1) | ) # 5 ( 3 + 2 ) ( 2 + 1) + ( 1 + 1 ) def main(): print fib(7) if __name__=='__main__': main()
#!/usr/bin/python # A. match_ends # Given a list of strings, return the count of the number of # strings where the string length is 2 or more and the first # and last chars of the string are the same. # Note: python does not have a ++ operator, but += works. def match_ends(words): size = 0 for word in words: if len(word) >= 2 and word[0].lower() == word[-1].lower(): size = size + 1 return size def main(): l = ['Mary', 'Anna', 'Mike', 'Miriam', 'Matt'] print str(match_ends(l)) if __name__=='__main__': main()
#!/usr/bin/python # create a list. Lists are simply collections of things. They're denoted in brackets with separating commas a = [1,2,3,4,5,6,7,8,9,10] # define a count function def count(b): # define a variable that you'll be updating as you sum up the ints in the list counter = 0 # loop through list. Notice how this is different from what we did in class. Here, I'm passing the # count() function a variable, namely b. b is just a list of values, though. So, instead of doing: # # for i in range (0, 6): # # I instead say, # # for num in b: # # In the first iteration of this num == 1, then in the second iteration num == 2, continuing all the way # up until there are no more numbers in b. # # This kind of for-loop is a bit easier in case you don't know how many items are in the list, for example. # for num in b: counter = counter + num # return the value in counter here (be careful of indentation!) return counter def main(): # run your count function passing it an argument sum = count(a) # conditional if sum > 20: print 'You have: ' + str(sum) + '. Nice!' else: print 'lame' if __name__ == '__main__': main()
#!/usr/bin/python import re def learning_dict(): normal_d = {} # open dictionary f = open('small_dict.txt', 'r') words = f.read().split() # put into dictionary for word in words: normal_d[word.lower()] = None h = open('small_string.txt', 'r') # make a list of words from holy_grail.txt hg = h.read().split() # number of mispelled words count = 0 incorrect_d = {} added = {} for l in hg: # add regular expression to deal with periods match = re.search(r'[\"]*(\w+)[\".!,?,/]*', l) if match: l = match.group(1) # turn all words in string to lower case to match dictionary if l.lower() not in normal_d: if l.lower() not in incorrect_d: incorrect_d[l.lower()] = 1 count = count + 1 elif incorrect_d.get(l.lower()) == 1: incorrect_d[l.lower()] = 2 count = count + 1 else: incorrect_d.pop(l.lower()) count = count - 2 normal_d[l.lower()] = None added[l.lower()] = None print added print incorrect_d print count def main(): learning_dict() if __name__=='__main__': main()
#!/usr/bin/python # # Question 0 # # You remember yesterday how we wrote that little program, I think we called # it count. Basically what it did was declare a list of natural numbers then # summed them from 1 to n. # # So, for example, if we hardcoded the list [1,2,3,4,5] and then called # count(), we get back 15. # # Well, hardcoding values like the above isn't cool. For Question 1, take in # a value from the user via the command line (by using argv) making sure to # check the length of argv. Then generate a list of n numbers. Each number, though, # should be ODD (so the list will look like [1, 3, 5, 7, ..., n]). # # Dynamically generate this list, perhaps using something like the append function we used # today, and then sum up all the terms in the list. You should find that your sum == n^2. # # For this problem you should write a function, square(n) that will (1) generate the list # of numbers and (2) sum them up. You should, as well, make your own main() function, as this # will be what passes the cmd-line argument back to square(n) # # Your program should function from the cmd line like this: # # ./square [nothing] # prints error message # ./square 2 # 4 # ./square 3 # 9 # ./square 25 # 625 # # def square(n): # TODO def main(): # TODO if __name__:'__main__': main()
#!/usr/bin/python # A. match_ends # Given a list of strings, return the count of the number of # strings where the string length is 2 or more and the first # and last chars of the string are the same. # Note: python does not have a ++ operator, but += works. def match_ends(words):
#!/usr/bin/env python3 user = input("What is your name?").strip() icecream = ["flavors", "salty"] icecream.append(99) print(f"{icecream[-1]} {icecream[0]}, and {user} chooses to be {icecream[1]}.")
a = int(input("Enter a Number: ")) b = int(input("Enter a Number: ")) c = int(input("Enter a Number: ")) s = (a+b+c)/2 area=(s*(s-a)*(s-b)*(s-c))** 2 print(area)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 21 10:40:34 2020 Exercise Bank account Make a class that represents a bank account. Create four methods named set_details, display, withdraw and deposit. In the set_details method, create two instance variables : name and balance. The default value for balance should be zero. In the display method, display the values of these two instance variables. Both the methods withdraw and deposit have amount as parameter. Inside withdraw, subtract the amount from balance and inside deposit, add the amount to the balance. Create two instances of this class and call the methods on those instances. @author: sindy """ class BankAccount(): def __init__(self, name, balance): self.name = name self.balance = balance def set_details(self): return self.name, self.balance def display(self): return f"{self.name} has a balance of {self.balance}" def withdraw(self, amount_withdraw): self.balance -= amount_withdraw def deposit(self, amount_deposit): self.balance += amount_deposit client1 = BankAccount("Becky", 3200) client2 = BankAccount("Ben", 4254) print(client1.set_details()) print(client1.display()) client1.withdraw(200) print(f"you have a new balance of {client1.balance}") client1.deposit(500) print(f"you have a new balance of {client1.balance}") print(client2.set_details()) print(client2.display()) client2.withdraw(1224.05) print(f"you have a new balance of {client2.balance}") client2.deposit(225) print(f"you have a new balance of {client2.balance}") #class BankAccount(): # def set_details(self, name, balance=0): # self.name = name # self.balance = balance # # def display(self): # return f"{self.name} has a balance of {self.balance}" # # def withdraw(self, amount_withdraw): # self.balance -= amount_withdraw # # def deposit(self, amount_deposit): # self.balance += amount_deposit
import requests print('Please enter a date of your choice with this format => YYYY-MM-DD :') date=input() print('Please enter one or multiple cryptocurrency symbols "separated with comma please" :') symbol=input() print('Please enter your preferred target currency :') trgt=input() api='4976d29d2ffb43259ac94f12ff54646d' url = 'http://api.coinlayer.com/date? access_key = 4976d29d2ffb43259ac94f12ff54646d &symbols = symbol &target=trgt' params = {'access_key': api, 'YYYY-MM-DD': 'date','symbols': symbol,'target': trgt} r = requests.get('https://api.coinlayer.com/date', params = params) convcoin = r.json() print (convcoin)
import random class Shark(): def __init__(self,parent=None): self.life=1 self.x = random.randrange(0,18,1) self.y = random.randrange(0,15,1) self.position = [self.x,self.y] self.old_position=[None,None] self.step=0 self.hunger=9 def move(self): self.hunger-=1 self.h=random.randrange(1,5,1) if self.position[0] != None and self.position[1] != None: self.old_position[0]=self.position[0] self.old_position[1]=self.position[1] #print('очистил',self.old_position[0]) #print('очистил',self.old_position[1]) if self.h==1 and self.position[0]>0: self.position[0] = self.position[0]+(-1) elif self.h==2 and self.position[1]<20: self.position[1] = self.position[1]+(1) elif self.h==3 and self.position[0]<18: self.position[0] = self.position[0]+(1) elif self.h==4 and self.position[1]>0: self.position[1] = self.position[1]+(-1) self.step+=1 if self.h==1 and self.position[0]==0: self.position[0]=17 elif self.h ==3 and self.position[0]==18: self.position[0]=0 if self.h == 4 and self.position[1]==0: self.position[1]=20 elif self.h == 2 and self.position[1]==20: self.position[1]=0 def __del__(self): class_name = self.__class__.__name__ print('{} уничтожен'.format(class_name)) """ all_shark=[] x=Shark() y=Shark() all_shark.append(x) #all_shark.append(y) print(len(all_shark)) for i in range (9): x.move() """
#escreva uma função recursiva que imprima de um numero x até um número y. n = int(input("informe o número a ser exibido: ")) def exibir(n): if (n<=n and n>=0): print(n) return exibir(n-1) exibir(n)
# 并发和并行一直是很容易混淆的概念,并发通常指的是有多个任务需要同时进行。并行则是同一个时刻有多个任务执行。用上课来举例就是, # 并发情况下是一个老师在同一个时间段辅助不同的人功课。并行是好几个老师同时辅助多个学生功课。简而言之就是一个人同时吃三个馒头还是 # 三个人同时分别吃一个的情况,吃一个馒头算一个任务。 # asyncio 实现并发,就需要多个协程来完成,每当有任务阻塞的时候就await, 然后其他的协程继续工作。创建多个协程的列表,然后将这些协程注册到事件循环中。 import asyncio import time now = lambda : time.time() async def do_some_work(x): print("Waiting: ", x) await asyncio.sleep(x) return 'Done after {}s'.format(x) start = now() coroutine1 = do_some_work(1) coroutine2 = do_some_work(2) coroutine3 = do_some_work(4) tasks = [ asyncio.ensure_future(coroutine1), asyncio.ensure_future(coroutine2), asyncio.ensure_future(coroutine3) ] loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks)) # 总时间为4s左右,4s的阻塞时间,足够前面两个协程执行完成。如果是同步顺序的任务,则至少需要7s, 此时我们使用asyncio实现了并发。 # asyncio.wait(tasks) 也可以使用asyncio.gather(*tasks), 前者接收一个task列表,后者接收一堆task. for task in tasks: print("Task ret: ", task.result()) print('Time: ', now() - start) # Waiting: 1 # Waiting: 2 # Waiting: 4 # Task ret: Done after 1s # Task ret: Done after 2s # Task ret: Done after 4s # Time: 4.002778053283691
# coding:utf-8 # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ # 反转一个链表。 # pre 指向前一个值,没有为Null. # cur 指向当前值,就是要操作的值。 # next 指向当前值的next. if not head: return pre, cur = None, head while cur != None: next = cur.next cur.next = pre pre = cur cur = next return pre
i = input("请输入起始值") e = input("") sum = 0 i = int(input("请输入起始值")) sum = int(input("请输入终止值")) elif i > sun print("起始值不能大于终止值") while i < 1000000000000000001: print(i) sum+=i i+=1#i = i+1 print(sum)
''' str = "baimingrui" for i in str: print(i) ''' i = 0 j = len(str) while i < j: print(str[i]) i+1
def test2(a): a+=a print(a) ''' x = [1,2] test2(x) print(x) ''' def test3(a): a = a+a print(a) x = [1,2] test3(x) print(x)
import random import time print('欢迎使用QQ'.center(50,'*')) print('请先注册你的QQ号'.center(50,' ')) while True: a = input('请输入你要注册的QQ号:') b = input('请输入你要注册QQ号的密码:') #判断是否输入正确 if len(a) == 11 and a.startswith('1') == True and len(b)>=6: print('输入正确') break #如果输入正确,结束本次循环 else: print('输入有误,请重新输入') print('正在给你发送验证码...'.center(50,' ')) c = random.randint(1000,9999) time.sleep(3) print('你的验证码为%d'%c) while True: f =int(input('请输入你的验证码:')) if f == c : print('注册成功') break else : print('验证码输入有误,请重新输入') print('请登录QQ'.center(50,'-')) while True: d = input('请输入你的QQ号') e = input('请输入你的QQ密码') if d == a and b == e: print('登陆成功') break else : print('登录失败,请重新登录') print('*'*50) #注册登录完成,进入选择功能 list=[] #定义空列表 def gn(): #功能函数 print('1:添加好友'.center(50,' ')) print('2:查找好友'.center(50,' ')) print('3:修改好友'.center(50,' ')) print('4:删除好友'.center(50,' ')) print('5:显示全部好友及信息'.center(50,' ')) print('6:退出系统'.center(50,' ')) def xz():#选择功能 while True: a = int(input('请选择功能')) if a == 1: add() #调用添加函数 print('-'*50) if a == 2: find() #调用查找函数 print('-'*50) if a == 3: xg() #调用修改函数 print('-'*50) if a == 4: sc() #调用删除函数 print('-'*50) if a == 5: xs() #调用显示全部内容函数 print('-'*50) if a == 6: print('退出成功,欢迎下次使用'.center(50,'*')) break def add():#添加 l = {} while True: b = input('请输入要添加好友姓名') #判断添加名字是否符合以下条件,符合结束循环,否则重新输入 if len(b) <=4: break else: print('输入有误,请重新输入') while True: c = input('请输入要添加好友的手机号') #判断添加手机号是否符合以下条件,符合结束循环,否则重新输入 if len(c) ==11 and c.startswith('1'): break else: print('输入有误,请重新输入') while True: d = input('请输入要添加好友的地址') #判断添加地址是否符合以下条件,符合结束循环,否则重新输入 if len(d) <=6: break else: print('输入有误,请重新输入') #把内容添加到字典 l['b']=b l['c']=c l['d']=d list.append(l) #添加到列表 print('添加成功') def find():#查找 b1 = input('请输入你要查找的姓名') flag = False #假设里面没有要查找的名字 for i in list: #把字典从列表里遍历出来 if i['b'] == b1: #如果我要查找的名字在字典里,打印内容 print('姓名:%s\n微信号:%s\n地址:%s'%(i['b'],i['c'],i['d'])) flag = True #表示找到了 break if flag == False: print('没有你要查找的姓名') def xg():#修改 b2 = input('请输入要修改的名字') flag = False #假设里面没有要修改的名字 for i in list: while True: if i['b'] == b2: flag = True print('1:请输入要修改的名字') print('2:请输入要修改的手机号') print('3:请输入要修改的地址') print('4:退出修改系统') j = int(input('请选择要修改的功能')) if j == 1: b = input('请输入新的名字') i['b'] = b print('修改成功') break elif j == 2: c = input('请输入新的手机号') i['c'] = c print('修改成功') break elif j == 3: d = input('请输入新的地址') i['d'] = d print('修改成功') break elif j == 4: print('退出成功') break elif flag == False: print('没有要修改的名字') break def sc():#删除 b3 = input('请输入你要删除的名字') for i in list: for position,i in enumerate(list): list.pop(position) #删除字典所在列表的索引值 print('删除成功') def xs():#显示所有内容 print('名字\t手机号\t\t地址') for i in list: print(i['b']+'\t'+i['c']+'\t'+i['d']) gn() #调用功能函数 xz() #调用选则功能函数
import time import datetime class Timer(object): def __init__(self): self.start = 0 self.for_start = 0 self.end = 0 self.for_end = 0 self.pause = 1 def began(self): self.start = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) def get(self, how): self.end = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) self.for_start = datetime.datetime.strptime(self.start, '%Y-%m-%d %H:%M:%S') self.for_end = datetime.datetime.strptime(self.end, '%Y-%m-%d %H:%M:%S') second = (self.for_end - self.for_start).seconds if how == 'second': return str(second) elif how == 'minute': return '%d:%d' % (second // 60, second % 60)
class Calculadora(object): def __init__(self,marca_param ): self.marca = marca_param def sumar(self,numero1,numero2): resultado = numero1 + numero2 return resultado def restar(self,numero1,numero2): resultado = numero1 - numero2 return resultado def multiplicar(self,numero1,numero2): resultado = numero1 * numero2 return resultado casio = Calculadora ("casio") print casio.sumar(3,4)
"""This timer module provides stop watch functionality for measuring how long loops / methods take to execute. """ import time class Timer(object): """Timer for making ad-hoc timing measurements""" def __init__(self, verbose=False): self.verbose = verbose self.secs = 0 self.msecs = 0 self.start = 0 self.end = 0 def __enter__(self): self.start = time.time() return self def __exit__(self, *args): self.end = time.time() self.secs = self.end - self.start self.msecs = self.secs * 1000 # millisecs if self.verbose: print('elapsed time: {:f} ms'.format(self.msecs)) def main(): """Example of how timer is used""" with Timer() as my_timer: # Do some time consuming work here pass print('elapsed time is {} ms'.format(my_timer.msecs)) if __name__ == "__main__": main()
def binary_search(arr, left, right, x): if left <= right: middle = left + (right -left) // 2 if arr[middle] == x: return middle elif arr[middle] < x: return binary_search(arr, middle + 1, right, x) else: return binary_search(arr, left, middle - 1, x) else: return -1 arr = [4,5,6,7,8,9,10] x = 10 res = binary_search(arr,0,len(arr)-1,x) if res != -1: print('Item found at: ' + str(res + 1)) else: print('Item not found')
class StackNode: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.head = None def push(self, data): node = StackNode(data) node.next = self.head self.head = node def is_empty(self): return self.head is None def peek(self): if self.is_empty(): raise Exception('Stack is empty!') return self.head.data def pop(self): if self.is_empty(): raise Exception('Stack is empty!') temp = self.head self.head = temp.next def traverse(self): temp = self.head while temp: print(temp.data) temp = temp.next def get_length_iterative(self): length = 0 temp = self.head while temp: length = length + 1 temp = temp.next return length def get_length_recursive(self, head): if head is None: return 0 return 1 + self.get_length_recursive(head.next) s = Stack() s.push(2) s.push(4) s.push(6) s.traverse()