text
stringlengths
37
1.41M
first_number = input("What is the first number to add? ") first_number = int(first_number) second_number = input("What is the second number to add?") second_number = int(second_number)
#!/usr/bin/env python # coding: utf8 import rospy from std_msgs.msg import Int32,String import sys import tty # --------------------------------------------------------------- def questions(): # node name rospy.init_node('questions_keyboard') pub=rospy.Publisher('questions_keyboard',String,queue_size=10) r = rospy.Rate(10) # show questions print ' ************************' print ' QUESTIONS ' print ' ************************' print ' 01-How many rooms are not occupied?' print ' 02-How many suites did you find until now?' print ' 03-Is it more probable to find people in the corridors or inside the rooms?' print ' 04-If you want to find a computer, to which type of room do you go to?' print ' 05-What is the number of the closest single room?' print ' 06-How can you go from the current room to the elevator?' print ' 07-How many books do you estimate to find in the next 2 minutes?' print ' 08-What is the probability of finding a table in a room without books but that has at least one chair?' print ' 09-How many different types of objects have you discovered until now?' print ' 10-Which objects were discovered in the current room until now?' print ' 11-What is the number of the room that contains more objects?' print ' 12-What is the number of the room that contains the mysterious object?' tty.setcbreak(sys.stdin) while not rospy.is_shutdown(): # read from keyboard k=sys.stdin.read(2) if int(k) < 1 or int(k) >12: continue pub.publish(k) #print 'Asked question: ' , k # --------------------------------------------------------------- if __name__ == '__main__': questions()
def filter_sort(items): lst = [] for item in items: if isinstance(item, str): lst.append(item) return lst.sort() items = [1,2,'a','c','a'] print(filter_sort(items))
# Project: PoW Solution Generation Module # Author: Jonathan Kenney # imports from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes # main program def main(): # init vars target = 0 message = b'' s = '0'.encode('utf-8') # start solution counter at '0' # fetch target from file and convert to integer with open('./data/target.txt', 'r') as f: target = int(f.read(), 16) f.close() # fetch message from file and encode with open('./data/input.txt', 'r') as f: message = f.read().encode('utf-8') f.close() # check the base hash value digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest.update(message + s) # check if this digest has solved the puzzle solved = int(digest.finalize().hex(), 16) < target # loop and increment solution by 1 until puzzle is solved tries = 1 while solved == False: digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) tries += 1 s = str(int(s.decode('utf-8')) + 1).encode('utf-8') digest.update(message + s) solved = int(digest.finalize().hex(), 16) < target # decode the solution s = s.decode() # print out the solution and number of tries, then write solution to file print('Solution: %s' % s) print('Num tries: %d' % tries) with open('./data/solution.txt', 'w') as f: f.write(s) f.close() # main boilerplate if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """ Spyder Editor Author: Chul Lee """ from math import * import scipy as sci import numpy as np #import plot.matplotlib as plt import sympy as sym from sympy.physics.mechanics import dynamicsymbols """Question 1""" t,u,v,w =sym.symbols('t u v w') #declares t u v w as symbols for differentiation #t,u,v,w sym.init_printing(use_unicode=True) var=['t','u','v','w'] #z = [1.1,2,0.9,1] #initial guess #t=z[0] #u=z[1] #v=z[2] #w=z[3] #vec = [0,0,0,0] #sets up vector #vec[0]=t**4+u**4-1 #vec[1]=t**2-u**2+1 #vec[2]=v**4+w**4-1 #vec[3]=v**2-w**2+1 #print(vec[0],vec[1],vec[2],vec[3]) """uses functions as itself of symbols rather than using given numerical values""" f1=t**4+u**4-1 f2=t**2-u**2+1 f3=v**4+w**4-1 f4=v**2-w**2+1 def part_der(f,l): """given an input function f and a list of variables l, returns the the list of partial derivative functions Input: f : function l: list of variables Output: list of partially derived functions """ # print(f) der = [] #empty list which derived functions will be appended onto for i in l: a=sym.diff(f,i) der.append(a) return der df1 = part_der (f1,var) # df2 = part_der (f2,var) df3 = part_der (f3,var) df4 = part_der (f4,var) #df1 = part_der (vec[0],var) # #df2 = part_der (vec[1],var) #df3 = part_der (vec[2],var) #df4 = part_der (vec[3],var) #for i in df1: # print(i.subs(t,5.)) J = sym.Matrix([df1,df2,df3,df4]) #jacobian matrix print("jacobian is: ",J) x0 = sym.Matrix([1,1,1,1]) #initial guess of x0 #def value_apply(func,sym, num): # """applies numerical values to a function""" # for sym,num in enumerate(num): # sym =num def sub_num_df(func,t,u,v,w): """subs numerical values of t, u, v and w onto each partially derived functions in a row in outputted jacobian matrix.""" mat = [] #empty list, numerical values of each function will be added tn = float(t) #prevents confusion caused by multiple variables stemming from same name un = float(u) vn = float(v) wn = float(w) for i in func: if i == 0: mat.append(0) else: mat.append(i.subs({'t':tn,'u':un,'v':vn,'w':wn})) # print(mat) return mat df1n = sub_num_df(df1,x0[0],x0[1],x0[2],x0[3]) df2n = sub_num_df(df2,x0[0],x0[1],x0[2],x0[3]) df3n = sub_num_df(df3,x0[0],x0[1],x0[2],x0[3]) df4n = sub_num_df(df4,x0[0],x0[1],x0[2],x0[3]) Jn = sym.Matrix([df1n,df2n,df3n,df4n]) #Jacobian matrix with numerical value print("Jn = ",Jn) def sub_num_f(func,t,u,v,w): """subs numerical values of t, u, v and w onto each vectors in a row in outputted jacobian matrix.""" mat = [] #empty list, numerical values of each function will be added tn = float(t) #prevents confusion caused by multiple variables stemming from same name un = float(u) vn = float(v) wn = float(w) f = func.subs({'t':tn,'u':un,'v':vn,'w':wn}) print(type(f)) mat.append(f) # print(mat) return mat f1n = sub_num_f(f1,x0[0],x0[1],x0[2],x0[3]) f2n = sub_num_f(f2,x0[0],x0[1],x0[2],x0[3]) f3n = sub_num_f(f3,x0[0],x0[1],x0[2],x0[3]) f4n = sub_num_f(f4,x0[0],x0[1],x0[2],x0[3]) f_x0 = sym.Matrix([f1n,f2n,f3n,f4n]) print("f_x0 = ",f_x0) #print(np.array(f_x0.np.shape)) x1 = x0 - Jn.T*f_x0 print("after newton's method, J1 is: ",x1)
# MECH3750: Semester 2, 2018 # author: Travis Mitchell # Part II: Parabolic PDE example # Solving the diffusion equation with finite difference # df/dt=D*d2f/dx^2 by finite difference # with the Dirichlet boundary conditions: f=0 at x=0 and f=0 at x=xb import math import numpy as np import matplotlib import matplotlib.pyplot as plt # the fundamental solution function def FI(D,x,t) : ff=np.exp(-np.array(x)**2/4.0/D/t)/np.sqrt(4.0*D*np.pi*t) return(np.matrix(ff).transpose()) #### STEP 1: DISCRETISATION #### # define the system and parameters required to discretise # n=100 # n+1 is the number of grid points D=1.0 # diffusion coefficient cfl=0.4 # CFL number xa=0.0 # domain limits [xa,xb] xb=1.0 t0=0.00 # initial time tf=0.1 # the final time x0=0.6; # Here we calculate dx and use our CFL criterion to # # define a time step that will suit our stability # # requirements. # dx=xb/n dt=dx*dx*cfl/D x=np.array(range(0,n+1))*dx + xa #### STEP 2: INITIALISATION #### # You may have a discrete set of points or a fn describing this # # Here we will use the a shifted fundamental solution for this # # You could code in here though a dirac delta function for e.g # f0=FI(D,x-x0,t0+0.0025) print(f0) #### STEP 3: RUN #### ### For the diffusion equation we can formulate as: ### ### Implicit, explicit, Crank-Nicolson ### ### Here I will show you explicit, it is your job ### ### to code in the rest ### ## The explicit scheme is given by: ## ## f(i,jp1) = cfl* (f(ip1,j) - 2f(i,j) + f(im1,j)) + f(i,j) ## Finite difference using matrices ## S = (1 - 2*cfl) * np.eye(x.size) + np.diag(cfl*np.ones(x.size-1),1) + np.diag(cfl*np.ones(x.size-1),-1) # Re-construct first and last row for B.C. S[0,:] = 0; S[0,0] = 1 S[-1,:]= 0; S[-1,-1]=1 print(S) # Set I.C. and B.C. t = t0 f = f0 f[0] = 0; f[-1] = 0 # Dirichlet B.C. equal to 0 iter = 0 while t<tf: f=S*f # finite difference -- step by step t=t+dt iter=iter+1 if iter%100 == 0: fig = plt.figure() print([iter,t,tf]) plt.clf() plt.plot(x,f0,'r-',x,f,'b-') plt.draw() plt.waitforbuttonpress(0) plt.close(fig)
m=int(input("Enter the month: ")) d=int(input("Enter the day: ")) if m in range(1,5): print("Winter") if m in range(5,9): print("Summer") if m in range(9,13): print("Monsoon")
#!/usr/bin/env python3 import random from ex2_rpsls_helper import get_selection def rpsls_game(): compRes=0 userRes=0 drawRes=0 while (compRes-userRes)!=2 and (userRes-compRes)!=2: userChoice=int(input(" Please enter your selection: "+ "1 (Rock), 2 (Paper), 3 (Scissors), 4 (Lizard) or 5 (Spock): ")) if userChoice>5 or userChoice<1: print(" Please select one of the available options.\n") else: print(" Player has selected: %s." %get_selection(userChoice)) compChoice=random.randint(1, 5) print(" Computer has selected: %s." %get_selection(compChoice)) if userChoice==1: #Rock if compChoice==3 or compChoice==4: print(" The winner for this round is: Player\n") userRes+=1 elif compChoice==1: print(" This round was drawn\n") drawRes+=1 else: print(" The winner for this round is: Computer\n") compRes+=1 elif userChoice==2: #Paper if compChoice==1 or compChoice==5: print(" The winner for this round is: Player\n") userRes+=1 elif compChoice==2: print(" This round was drawn\n") drawRes+=1 else: print(" The winner for this round is: Computer\n") compRes+=1 elif userChoice==3: #Scissors if compChoice==2 or compChoice==4: print(" The winner for this round is: Player\n") userRes+=1 elif compChoice==3: print(" This round was drawn\n") drawRes+=1 else: print(" The winner for this round is: Computer\n") compRes+=1 elif userChoice==4: #Lizard if compChoice==2 or compChoice==5: print(" The winner for this round is: Player\n") userRes+=1 elif compChoice==4: print(" This round was drawn\n") drawRes+=1 else: print(" The winner for this round is: Computer\n") compRes+=1 else: #Spock if compChoice==1 or compChoice==3: print(" The winner for this round is: Player\n") userRes+=1 elif compChoice==5: print(" This round was drawn\n") drawRes+=1 else: print(" The winner for this round is: Computer\n") compRes+=1 if compRes>userRes: print("The winner for this game is: Computer") print("Game score: Player %s, Computer %s, draws %s" % (userRes, compRes, drawRes)) return -1 else: print("The winner for this game is: Player") print("Game score: Player %s, Computer %s, draws %s" % (userRes, compRes, drawRes)) return 1 def rpsls_play(): setsCount=0 winCount=0 gameCount=1 userSetCount=0 compSetCount=0 print("Welcome to the Rock-Scissors-Paper-Lizard-Spock game!") setLen=int(input("Select set length: ")) setEven=setLen userQuit=-1 while userQuit!=1: while setLen>0 or compSetCount==userSetCount or +\ (setEven%2==0 and abs(compSetCount-userSetCount)==1): print("Now beginning game %s" %gameCount) rpslsRes=rpsls_game() if rpslsRes==1: userSetCount+=1 elif rpslsRes==-1: compSetCount+=1 setLen-=1 gameCount+=1 print("Set score: Player %s, Computer %s" % (userSetCount, compSetCount)) if setEven%2==1: if ((userSetCount>setEven/2) or (compSetCount>setEven/2)) and compSetCount!=userSetCount : break elif setEven%2==0: if (compSetCount>setEven/2 or userSetCount>setEven/2) and +\ abs(compSetCount-userSetCount)!=1 and compSetCount!=userSetCount: break if userSetCount>compSetCount: print("Congratulations! You have won in %s games." %(gameCount-1)) winCount+=1 elif userSetCount<compSetCount: print("Too bad! You have lost in %s games." %(gameCount-1)) setsCount+=1 print("You have played %s sets, and won %s!\n" %(setsCount, winCount)) userQuit=int(input("Do you want to: 1 - quit, 2 - reset scores or 3 - continue? ")) if userQuit==2: print("Resetting scores") setLen=int(input("Select set length: ")) setEven=setLen setsCount=0 winCount=0 gameCount=1 userSetCount=0 compSetCount=0 elif userQuit==3: setLen=setEven gameCount=1 userSetCount=0 compSetCount=0 elif userQuit==1: break #Here to help you test your code. #When debugging, it is helpful to be able to replay with the computer # repeating the same choices. if __name__=="__main__": #If we are the main script, and not imported from sys import argv try: random.seed(argv[1]) # as a string is good enough except: pass rpsls_play()
__author__ = 'win7' import string def get_words(text): wordList = [] for word in text.split(): for char in word: if char not in string.ascii_letters: break else: wordList.append(word.lower()) return sorted(wordList) print(get_words('abc ascka a$R#fv dsnl abc Abc'))
############################################################################ # FILE: ex3.py # WRITER: Aviad Levy # EXERCISE : intro2cs ex3 2013-2014 # # Description: # # constant_pension: calculate retirement fund assuming constant pesnion # variable_pension: calculate retirement fund assuming variable pension # choose_best_fund: find the best fund to invest in # growth_in_year: return the growth value in a given year # inflation_growth_rates: calculate the adjusted growth list given inflation # post_retirement: calculates the account status after retirement ############################################################################ def constant_pension(salary, save, growth_rate, years): #check for proper values if salary<0 or save<0 or save>100 or growth_rate<-100 or years<0: return #if no year entered return empty list elif years == 0: consPension = [] return consPension else: retireFund = salary*save*0.01 #the value for the 1st year consPension = [retireFund] #enter the value to the list counter = 1 #check and enter the value of the rest years to the list while counter<years: consPension.append(retireFund*(1+growth_rate*0.01)+salary*save*0.01) retireFund = consPension[counter] counter += 1 return consPension def variable_pension(salary, save, growth_rates): #check for proper values if salary<0 or save<0 or save>100: return #if no year entered (growth_rates is empty) return empty list if len(growth_rates) == 0: retireList = [] return retireList #check for proper values inside growth_rates list growCounter = 0 while growCounter<len(growth_rates): if float(growth_rates[growCounter]) < -100: return growCounter += 1 retireFund = salary*save*0.01 #the value of the 1st year varPension = [retireFund] #enter the value to the list counter = 1 #check and enter the value of the rest years to the list while counter<len(growth_rates): varPension.append(retireFund*(1+(float(growth_rates[counter])*0.01)) +salary*save*0.01) retireFund = varPension[counter] counter += 1 return varPension def choose_best_fund(salary,save,funds_file): #check for proper values if salary<0 or save<0 or save>100: return #open the file and read the lines f = open(funds_file, 'r') lines = f.readlines() f.close() lineNum = 0 fundNameList = [] bigFundIndex = -1 #remeber the line of the biggest fund fundValueSafe = [0] #save the biggest fund line while lineNum < len(lines): #loop over all lines in file newGrowthList = [] #list the gets the line and "convert" it to list counterName = 1 #lines[lineNum][0] is '#' so we start at 1 fundName = '' #string that will "read" the fund name while counterName < len(lines[lineNum]): #loop over one line at a time #stop when we "meet" the 1st ',' if lines[lineNum][counterName] == ',': break #fundName gets the fund name fundName += str(lines[lineNum][counterName]) counterName += 1 fundNameList.append(fundName) #enter the name to a list of names counterName += 1 #get the rest of the list: #i used partition[2] to get the second half of the line after the ',' newGrowthList = ((lines[lineNum].partition(','))[2]) newGrowthList = newGrowthList[:-1] #delete '\n' from the end of line newGrowthList = newGrowthList.split(',') #remove all ',' #send the newGrowthList with salary and save provided #to variable_pension fundValue = variable_pension(salary, save, newGrowthList) newVal = float(fundValue[-1]) #last year value of the fund we checked oldVal = float(fundValueSafe[-1]) #last year value of the biggest fund if newVal > oldVal: #check if new is bigger bigFundIndex = lineNum #remember biggest line fundValueSafe = list(fundValue) #keep the new biggest fund list lineNum +=1 #creat tuple of the name and last year value of the biggest we kept bigFund = (fundNameList[bigFundIndex], fundValueSafe[-1]) return bigFund def growth_in_year(growth_rates,year): #check for proper value if year<0: return growCounter = 0 while growCounter<len(growth_rates): if float(growth_rates[growCounter]) < -100: return growCounter += 1 #check if year is on list if growCounter < year+1: return #return the growth rates in the spesific year return float(growth_rates[year]) def inflation_growth_rates(growth_rates,inflation_factors): newGrowthRates = [] #check if we got any infilation factors. #if not return growth rates as it is if len(inflation_factors) == 0: return growth_rates #check for proper values growCounter = 0 while growCounter<len(growth_rates): if float(growth_rates[growCounter]) < -100: return growCounter += 1 growCounter = 0 while growCounter<len(inflation_factors): if float(inflation_factors[growCounter]) <= -100: return growCounter += 1 #loop that run over the infilation factors and add the new value #to the new list. for index in range(len(inflation_factors)): #if infilation factors list is bigger than the growth rates list, #return the new list when we calculate every value in growth list. if index == len(growth_rates): return newGrowthRates newGrowthRates.append(float(100*((100+growth_rates[index])/ \ (100+inflation_factors[index])-1))) index += 1 #run over the rest values of growth rates & add them without change for index1 in range(index,len(growth_rates)): newGrowthRates.append(float(growth_rates[index1])) return newGrowthRates def post_retirement(savings, growth_rates, expenses): #check for proper values if savings<=0 or expenses<0: return growCounter = 0 while growCounter<len(growth_rates): if float(growth_rates[growCounter]) < -100: return growCounter += 1 #if no year entered (growth_rates is empty) return empty list if len(growth_rates) == 0: retireList = [] return retireList retireList = [] #the value of the 1st year: postRetire = savings*(1+growth_rates[0]*0.01)-expenses retireList = [postRetire] #enter the value to the list counter = 1 #check and enter the value of the rest years to the list while counter<len(growth_rates): retireList.append(postRetire*(1+(float(growth_rates[counter])*0.01)) -expenses) postRetire = retireList[counter] counter += 1 return retireList
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Oct 4 11:18:50 2017 @author: Hailey Cray-Dubaz Spirit Animal User ID: Yellow Butterfly Date Last Edited: 10/6/17 Challenge #3 Tutor for Python: Will Sanefski Code taken from Lecture 10 and Class Wiki """ import matplotlib.pyplot as mplot from PIL import Image import numpy as np import os images = os.listdir("unionconstruction") img_list=[] threshold = int(input("Enter your change threshold (values only between 0 and 255 are accepted): ")) for i in range(0, len(images)): if ".jpg" in images[i]: img =np.float32(Image.open("unionconstruction/" + images[i])) img_list.append(img) avg_img=[] for img in img_list: try: avg_img = avg_img + img except: avg_img = img avg_img /= len( img_list ) std_img = [0,0,0] for img in range(len(img_list)): std_img += (img_list[img] - avg_img)**2 std_img /= len( images ) std_img = np.sqrt(std_img) for row in range(len(std_img)): #loops over the number of rows in the image for col in range(len(std_img[row])): # loops over the number of columns in the current row if(sum(std_img[row][col])/3 > threshold): avg_img[row][col]=[255.0, 0.0, 0.0] avg_img=np.clip(avg_img, 0, 255) avg_img=np.uint8(avg_img) mplot.imshow(avg_img) mplot.show()
# test_functions.py # testing functions / added a docstring for greet #def greet(name): # """Return string Hello and a person name assigned to variable name""" # print(f"Hello, {name}!") #greet("Dave") #### a set of temperature conversion functions #### def convert_cel_to_far(C): F = C * 9/5 + 32 return float(F) your_cel = int(input("Enter a temparature in degrees C: ")) new_far = convert_cel_to_far(your_cel) print(f"{your_cel} degrees C = {new_far:.2f} degrees F") def convert_far_to_cel(F): C = (F - 32) * 5/9 return float(C) your_far = int(input("Enter a temparature in degrees F: ")) new_cel = convert_far_to_cel(your_far) print(f"{your_far} degrees C = {new_cel:.2f} degrees F")
# problem link: https://leetcode.com/problems/move-zeroes/ class Solution: def moveZeroes(self, nums: List[int]) -> None: """""" Do not return anything, modify nums in-place instead. """""" j = 0 for i in range(len(nums)): # if current element is not 0,exchange it to left side,otherwise exchange it to right side if nums[i]: nums[j],nums[i] = nums[i],nums[j] j += 1
# problem link: https://leetcode.com/problems/pacific-atlantic-water-flow/ class Solution: def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]: ans = [] dirs = [[-1,0], [0,-1], [1,0],[0,1]] num_r = len(matrix) num_c = len(matrix[0]) if num_r > 0 else 0 can_reach_p = [[False for _ in range(num_c)] for _ in range(num_r)] # mark if one point can reach pacific ocean can_reach_a = [[False for _ in range(num_c)] for _ in range(num_r)] # mark if one point can reach atlantic ocean def dfs(r, c, p_or_a): can_reach = can_reach_p if p_or_a == "p" else can_reach_a if can_reach[r][c] == True: return can_reach[r][c] = True for [i,j] in dirs: next_r = r + i next_c = c + j if 0<=next_r<num_r and 0<=next_c<num_c and matrix[r][c]<=matrix[next_r][next_c]: dfs(next_r, next_c, p_or_a) for r in range(num_r): dfs(r, 0, "p") dfs(r, num_c - 1, "a") for c in range(num_c): dfs(0, c, "p") dfs(num_r - 1, c, "a") for r in range(num_r): for c in range(num_c): if can_reach_p[r][c] and can_reach_a[r][c]: ans.append([r,c]) return ans
import sqlite3 def show_color(username): #connect the db connection = sqlite3.connect('Flask_tut.db', check_same_thread = False) cursor = connection.cursor() # SQL Query cursor.execute(""" SELECT favorite_color FROM users WHERE username = '{username}' ORDER BY pk DESC;""".format(username = username)) color = cursor.fetchone()[0] #close the DB connection connection.commit() cursor.close() connection.close() message = " '{username}'s favorite color is '{color}' ".format(username = username, color = color) return message def check_pw(username): #connect the db connection = sqlite3.connect('Flask_tut.db', check_same_thread = False) cursor = connection.cursor() # SQL Query cursor.execute(""" SELECT password FROM users WHERE username = '{username}' ORDER BY pk DESC;""".format(username = username)) password = cursor.fetchone()[0] #close the DB connection connection.commit() cursor.close() connection.close() return password def check_users(): #this is for user login, logout and session management #connect the db connection = sqlite3.connect('Flask_tut.db', check_same_thread = False) cursor = connection.cursor() # SQL Query cursor.execute(""" SELECT username FROM users ORDER BY pk DESC;""") db_users = cursor.fetchall() # gives a list of lists users = [] for i in range (len(db_users)): person = db_users[i][0] #gets the first item for each user (which should be username) users.append(person) # adds the username to the users list #close the DB connection connection.commit() cursor.close() connection.close() return users def signup(username, password, favorite_color): #connect the db connection = sqlite3.connect('Flask_tut.db', check_same_thread = False) cursor = connection.cursor() # SQL Query checks to see if the user exists cursor.execute(""" SELECT password FROM users WHERE username = '{username}';""".format(username = username)) exist = cursor.fetchone() #inserts the user data into db if exist is None: cursor.execute( """ INSERT INTO users ( username, password, favorite_color ) VALUES ( '{username}', '{password}', '{favorite_color}' );""".format(username = username, password = password, favorite_color = favorite_color)) #close the DB connection connection.commit() cursor.close() connection.close() else: return ('User already exists') return 'You have successfully signed up!'
for i in range(0,13): power = 2 ** i if len(str(power)) == 1: print("0" + str(power)) else: print(power % 100)
s = input("Input a word...\n").lower() def repeated(s, sub): sum_sub = 0 for i in range(len(s)): if s.startswith(sub, i): sum_sub += 1 print("Number of times 'aaa' occurs is:", sum_sub) repeated(s, "aaa")
#!/usr/bin/env python import socket import os import re from threading import Thread from SocketServer import ThreadingMixIn import sys, select import time #Client threads to perform asynchronous communication. It creates threads, for each message recieved, and prints messages when recieved. #initialization class for each thread class ClientThread(Thread): def __init__(self, sc,username): Thread.__init__(self) self.sc = sc self.username = username # Run method that handles sending and recieving messages to and from server. def run(self): header_message = "HTTP/1.0 \r\nContent-Type: text\n\n" while (1): #Recieve Message from server new_message = self.sc.recv(2048) #Check if connection is closed if " closed connection" in new_message: print "\n"+new_message os.execl(sys.executable, sys.executable, *sys.argv) all_message = new_message.split(",") print all_message[0] print all_message[1] # print "\n" + new_message chat_message = raw_input(username + ": ") localtime = time.asctime(time.localtime(time.time())) #Sending message to server sc.send(header_message+","+"Date: "+localtime+","+chat_message+","+str(len(chat_message))) # Client tries to establish a TCP socket connection TCP_IP = '127.0.0.1' TCP_PORT = 62 BUFFER_SIZE = 1024 # MESSAGE = "Hello, World! to server from client 1" sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sc.connect((TCP_IP, TCP_PORT)) threads = [] header_message = "GET HTTP/1.1\r\nContent-Type: text/plain" username = raw_input("Please enter your username") # Checking valid user name while re.match("^[a-zA-Z0-9]+$", username) is None: print " Invalid username, enter a valid username" username = raw_input("Please enter your username") chatname = raw_input("enter the name of the person you want to chat with") #Sending user names to Server sc.send(username + " " + chatname) while (1): check_new = sc.recv(2048) if "is online" in check_new: print check_new #New thread for handling messages while (1): newthread = ClientThread(sc,username) newthread.start() threads.append(newthread) chat_message = raw_input(username + ": ") localtime = time.asctime(time.localtime(time.time())) #Sending message to Server sc.send(header_message+","+"Date: "+localtime+","+chat_message+","+"Content-Length: "+str(len(chat_message))) else: while(1): print check_new break
print('digite o numero da conta: \n') numero_conta = int(input('>>> ')) print('nome do titular:\n ') nome = (input('>>> ')) saldo = 0.0 class banco(): def __init__(self): self.banco = '999' self.conta = numero_conta self.agencia = '08' self.nome = nome def saque(self): s = int(input('Valor de saque = ')) self.sacar = saldo - s print(f'Saldo = {self.sacar}') def deposito(self): d = int(input('Valor do deposito = ')) self.depositar = saldo + d print(f'Saldo = {self.depositar}') def extrato(self): self.extrato = {'Numero do banco: ': self.banco, 'Numero da agencia: ': self.agencia, 'Nome do cliente: ': nome, 'Saldo: ': saldo} print(self.extrato) print('\nOla OldBank') print('Bem vindo!') print('Selecione a opcao abaixo: ') print('\tPara extrato digite 1') print('\tPara saque digite 2') print('\tPara deposito digite 3') opcao = int(input('>>> ')) cliente = banco() try: if opcao == 1: cliente.extrato() elif opcao == 2: cliente.saque() elif opcao == 3: cliente.deposito() else: raise ValueError('Opção invalida') except ValueError as v: print(v)
n = int(input("Enter n value: ")) for i in range(0,n): for j in range(0,i): print(j, end = " ") print(i)
def countingValleys(n, s): if n == 1: return 0 valley_count = 0 sum = 1 if s[0] == 'U' else -1 for i in range(1, n): if sum == 0 and s[i - 1] == 'U': valley_count += 1 if s[i] == 'U': sum += 1 elif s[i] == 'D': sum -= 1 return (valley_count + 1) if sum == 0 and s[n - 1] == 'U' else valley_count
''' Array (VetoresEmatrizes) Um vetor(array) é um conjunto ordenado de variaveis de um mesmo tipo. Definimos: -tipo do dado -nome -tamanho(da celula) obs: cada celula e numerada,começando em 0 indo até tamanho-1 Vetores sao normalmente usados com comandos de repetiçao (for ou while) No Python , nao há vetores,e sim listas.Porem o tipo string se comporta como vetor EXEMPLO: ''' ''' texto = 'Python' for i in range(0,6): print(texto[i]) ''' ''' len(string1): devolve o tamanho de um string ou uma lista ''' ''' teste = input('Digite algo :') print('{} caracteres'.format(len(teste))) ''' ''' Operaçoes com strings +: concotena 2 strings teste1 = 'CC' teste2 = 'SI' print(teste1+teste2) print(teste2+teste1) N*str1{ str1+str1+str1+str1+str1+str1 } ''' ''' teste1='teste' teste2='python' print(teste1+teste2) print(2*(teste1+teste2)) print('primeira string : {} caracteres'.format(len(teste1))) print('segunda string : {} caracteres'.format(len(teste2))) ''' ''' Outros metodos para manipular strings -string.replace('palavra1','palavra2') só executa se os dois forem uma palavra -string.count('x') conta quantas vezes x aparece no string -string.find('x') indica a posiçao em que x aparece vetoriamente -string.upper('x') transforma o string em letra maiuscula ''' teste1='Frase para testar os metodos' print(teste1.replace('testar','coisar')) print('A letra a aparece {} vezes'.format(teste1.count('a'))) print('A letra x aparece {} vezes'.format(teste1.count('x'))) print(teste1.split()) print(teste1.upper()) print(teste1.lower())
#Helper function that returns predecessor of 'n' in tree of depth 'p' def loop(p,n): (previous_largest_possible_parent,largest_possible_parent) = (-1,2**p-1) running_total = 0 while n!=largest_possible_parent: #print(previous_largest_possible_parent,largest_possible_parent,n) if n<2**(p-1)+running_total: (previous_largest_possible_parent,largest_possible_parent) = (largest_possible_parent,largest_possible_parent-2**(p-1)) else: (previous_largest_possible_parent,largest_possible_parent) = (largest_possible_parent,largest_possible_parent-1) running_total+=2**(p-1)-1 p-=1 return(previous_largest_possible_parent) def solution(p, q): return([loop(p,n) for n in q])
# однострочный коммент ''' первая строка вторая строка ''' print('Hello') print('=' * 8, 'Hello', 'World!', '=' * 8) print('=' * 8, 'Hello', 'World!', '=' * 8, sep = '') print('=' * 8, 'Hello', 'World!', '=' * 8, sep = ' *** ') print('=' * 8, 'Hello', 'World!', '=' * 8, end = ' yyy') # Ввод name = input('\nВведите ваше имя: ') print(name, type(name)) age = input('\nСколько вам лет: ') print(int(age), type(int(age)))
Dict={} a=input("Bir değer giriniz:") for i in range(1,int(a)): print({i:i*i})
#!/usr/bin/python # -*- coding: UTF-8 -*- # 定义元组 tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (3, 6, 7, 8, 9) print 'tup1:', tup1 print 'tup2:', tup2 # 访问元组 print 'tup1[0]', tup1[0]
#! /usr/bin/python # -*- coding: utf-8-*- # 打印乘法口诀表 for x in range(1, 10): print for y in range(1, x + 1): print "%d*%d=%d" % (x, y, x * y),
#!/usr/bin/python # -*-coding:utf-8 -*- # 题目:输入三个整数x,y,z,请把这三个数由小到大输出。 # 我们想办法把最小的数放到x上,先将x与y进行比较,如果x>y则将x与y的值进行交换,然后再用x与z进行比较,如果x>z则将x与z的值进行交换,这样能使x最小。 a = int(raw_input('请输入a:')) b = int(raw_input('请输入b:')) c = int(raw_input('请输入c:')) l = [] l.append(a) l.append(b) l.append(c) n = len(l) for x in range(0, n - 1): for y in range(1, n): if l[x] > l[y]: temp = l[x] l[x] = l[y] l[y] = temp print l
class Calculadora: def __init__(self,numero1,numero2): self._num1=numero1 self._num2=numero2 def suma(self): return self._num1+self._num2 def resta(self): return self._num1-self._num2 def multiplicacion(self): return self._num1*self._num2 def division(self): return self._num1/self._num2 class calEstandar(Calculadora): def __init__(self, numero1, numero2): super().__init__(numero1,numero2) def multiplicacion(self): return super().multiplicacion() def exponente(self): return pow(self._num1,self._num2) def valorAbsoluto(self,numero): return abs(numero) class calCientifica(Calculadora): PI=3.1614 def __init__(self, numero1, numero2): super().__init__(numero1,numero2) def circunferencia(self): return 2*self.PI*self._num1 def areaCirculo(self): return self.PI*self._num1**2 def areaCuadrado(self): return self._num1*self._num1
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class BSTIterator(object): def __init__(self, root): """ :type root: TreeNode """ # use a list as a stack of elements that we've seen self.stack=[] stack.append(root) def next(self): """ @return the next smallest number :rtype: int """ # base case, that there is a left node while(stack[-1].left!=None): stack.append(stack[-1].left) # add this to the stack # at the end of this, we'll have the minimum value in our stack leftmost=stack.pop() stack[-1].left=None # so we don't continue down that line anymore return leftmost.val # case we just popped and now we have an element w a right branch if stack[-1] def hasNext(self): """ @return whether we have a next smallest number :rtype: bool """ # Your BSTIterator object will be instantiated and called as such: # obj = BSTIterator(root) # param_1 = obj.next() # param_2 = obj.hasNext()
def array_of_array_products(arr): """ arr = input product of everything except arr[i] for every i for empty case, return empty array if n=6 i=3 i keep track of the sum so far [1,2,[3],4,5] [_,_,] ? [,_, _] [1, 2, 3, 4, 5] ^ ^ ^ """ if arr==[]: return arr if len(arr)==1: return [] num=len(arr) result=[0 for i in range(num)] rollingProd=1 for i in range(1, num): # product so far = for i in range(0, i) sum all the elements # # product after that element = for i in range(i, n) sum all elements # product to return = productbefore * productafter rollingProd*=arr[i-1] result[i]=rollingProd rollingProd=1 for i in range(num-1, 0, -1): rollingProd*=arr[i] result[i-1]*=rollingProd return result
class Node: def __init__(self, node): self.node = node self.next = None class Stack: def __init__(self): self.top_node = None def push(self, node): if self.top_node is None: self.top_node = Node(node) else: temp = self.top_node self.top_node = Node(node) self.top_node.next = temp def top(self): return self.top_node.node def pop(self): if self.isEmpty(): raise Exception("Stack is empty") else: temp = self.top_node.node self.top_node = self.top_node.next return temp def isEmpty(self): if self.top_node is None: return True else: return False
#-*- coding: utf-8 -*- # @Time : 2017/9/30 # @File : 快速排序.py # @Author : zhaohui.ren # 快速排序 def quicksort(array): if len(array)<2: return array #基线条件:为空或只包含一个元素的数组是‘有序’的 else: pivot=array[0] #递归条件 less=[i for i in array[1:] if i<=pivot] #由所有小于基准值的元素组成的子数组 print(less) greater=[i for i in array[1:] if i>pivot] ##由所有大于基准值的元素组成的子数组 return quicksort(less)+[pivot]+quicksort(greater) print(quicksort([10,5,2,3]))
""" File: my_drawing.py Name: Luke ---------------------- TODO: """ import math from campy.graphics.gobjects import GOval, GLine from campy.graphics.gcolor import GColor from campy.graphics.gwindow import GWindow # Declare constants SIDES = 4 # Canvas is rectangle. SEGMENTS = 6 # Segments for each side. LINES = 51 # Best if factor of 255, lower renders faster. INCREMENT = 255//LINES # Calculate increment amount for rgb values. # Declare globals canvas_size = SEGMENTS * LINES window = GWindow(canvas_size, canvas_size, title='my_drawing.py') # Canvas size is segment count times line count. center_x = window.width // 2 # Calculate center point for each line to end at. center_y = window.height // 2 def main(): """ This program might take half a minute to finish, it draws an abstract tunnel, using loops and incrementing rgb values for walls and white circles simulating distance. """ lines() circles() def lines(): """ Draw lines from each side to center, alternating fade in each segment to create pattern. :return: Nothing. """ for i in range(0, SEGMENTS * SIDES): # Start loop for total segments. for x in range(0, LINES): # Start loop for lines in segment. if i // SEGMENTS == 0: # Top side start points: x increment, y at top. start_x = i % SEGMENTS * LINES + x # Increment starts after adding prior segment. start_y = 0 elif i // SEGMENTS == 1: # Right side start points: x at right, y increment. start_x = window.width start_y = i % SEGMENTS * LINES + x elif i // SEGMENTS == 2: # Bottom side start points: x decrement, y bottom. start_x = window.width - (i % SEGMENTS * LINES + x) # Decrements by subtracting from edge. start_y = window.height elif i // SEGMENTS == 3: # Left side start points: x at left, y decrement. start_x = 0 start_y = window.height - (i % SEGMENTS * LINES + x) end_x = center_x # End points for line fixed at canvas center. end_y = center_y if i % 2 == 1: # Odd segments increment rgb values rgb = x * INCREMENT else: # Even segments decrement instead rgb = LINES * INCREMENT - x * INCREMENT line = GLine(start_x, start_y, end_x, end_y) line.color = GColor(rgb, rgb, rgb) window.add(line) return def circles(): """ Draw circles in Fibonacci sequence. :return: Nothing. """ m = 1 # First number. n = 1 # Second number. max_n = math.sqrt(window.width**2/2) * 2 # Use window width to calculate max diameter needed. while n <= max_n: fib = m+n circle = GOval(fib, fib) circle.color = 'white' circle.x = center_x - fib//2 # Center circle. circle.y = center_y - fib//2 window.add(circle) m = n # Update first number with second number. n = fib # Update second number with sum. return if __name__ == '__main__': main()
# Thomas Reagan # ID: 001265074 import csv from HashTable import * from Location import * from Package import * # Function used to build all the necessary tables needed # for the program. Creates a list of locations, a list of # packages, and a hash table of packages that contain a # location object within them # O(n^2) def initialize_tables(distance_csv, package_csv): with open(distance_csv) as distance_file: read_distance_file = csv.reader(distance_file, skipinitialspace=True, delimiter=',') locations = [] for row in read_distance_file: location_id = row name = row[0] address = row[1] zip_code = row[2] distances = row[3:] address = address.replace('North', 'N').replace('South', 'S').replace('East', 'E').replace('West', 'W').replace('Bus', 'bus') locations.append(Location(location_id, name, address, zip_code, distances)) with open(package_csv) as package_file: read_package_file = csv.reader(package_file, delimiter=',') packages = [] for row in read_package_file: package_id = row[0] address = row[1] city = row[2] state = row[3] zip_code = row[4] deadline = row[5] mass = row[6] special_note = row[7] packages.append(Package(int(package_id), address, city, state, zip_code, deadline, mass, special_note, locations[get_matching_location(locations, address)])) manifest = HashTable(packages) for i in range(len(packages)): manifest.insert(packages[i].package_id, packages[i]) return manifest, packages, locations # Function to print the entire package list and all of their # attributes. # O(n) def get_all_package_info(manifest, packages): for i in range(len(packages)): print("Package ID: " + str(manifest.search(i+1).package_id)) print("Address: " + str(manifest.search(i+1).address)) print("Deadline: " + str(manifest.search(i+1).deadline)) print("City: " + str(manifest.search(i+1).city)) print("Zip Code: " + str(manifest.search(i+1).zip_code)) print("Weight: " + str(manifest.search(i+1).mass)) print("Delivery Status: " + str(manifest.search(i+1).delivery_status) + "\n") def get_single_package(manifest, package_id): print("Package ID: " + str(manifest.search(package_id).package_id)) print("Address: " + str(manifest.search(package_id).address)) print("Deadline: " + str(manifest.search(package_id).deadline)) print("City: " + str(manifest.search(package_id).city)) print("Zip Code: " + str(manifest.search(package_id).zip_code)) print("Weight: " + str(manifest.search(package_id).mass)) print("Delivery Status: " + str(manifest.search(package_id).delivery_status) + "\n")
def countChange(money, coinList): # [3, 2, 1] """ This function counts the number of different ways an amount of money can be exchanged, given a lst of coin denominations E.g: countChange(3,[2,1]) = 3 sice 3 can be exchanged with 1+1+1 or 2+1 Parameters: money (int): The amount of money to be exchanged coinList (list[Int]): List of coin denominations """ def count(money, coinList, acc): if len(coinList) == 1: if money % coinList[0] == 0: return acc + 1 else: return acc else: head = coinList[0] surplus = money - head if surplus < 0: return count(money, coinList[1:], acc) elif surplus == 0: return count(money, coinList[1:], acc + 1) else: return count(money, coinList[1:], count(surplus, coinList, acc)) return count(money, coinList, 0) print(countChange(11, [8,7]))
# using array-scalar type # to determine type of each element in array import numpy as np dt=np.dtype(np.int32) # int32 eq string 'i4' print (dt) # name can be used to access content of age column dt = np.dtype([('age',np.int8)]) a = np.array([(10,),(20,),(30,)], dtype=dt) print(a['age']) student=np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')]) a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype=student) print(a['age']) print(a)
import numpy as np a=np.array([[1,2,3,10,1],[4,5,6,7,3]]) # print(a) # [start:end:step] # note end must be end+1 # get intersection sub array from overall print(a[1:3:,0:2:])
simple_list = [1,2,3,4] simple_list.extend([5,6,7]) print(simple_list) del(simple_list[0]) # or del simple_list[0] print(simple_list) d = {'name': 'Max'} #Get tuple of keys and values in dict print(d.items()) # iterate over keys/values and print themS for k, v in d.items(): print(k,v) del(d['name']) print(d) t = (1,2,3) print(t.index(1)) #tuples are immutable and have no "del" function s = {'Max', 'Anna', 'Max'} # Redundant method not included # use IDE autocomplete to see methods (s.) print(s) # del doesn't work for sets new_list = [1, 2, 3, -5] any(new_list) # should return True # returns false all(new_list) number_list = [1, 2, 3, -5] #list comprehension to check for positive numbers [el for el in number_list if el > 0] # returns [1, 2, 3] [el > 0 for el in number_list if el > 0] # returns booleans for list [True, True, True] # We can use any or all with list comprehension [el > 0 for el in number_list] # returns [True, True, True, False] all([el > 0 for el in number_list]) # returns False
from math import log #Criando um vetor/lista meuVetor = [] for i in range(1,11): #Calcularemos o fatorial para todos os "i's", independente se ele será utilizado na geração do valor ou não fat = 1 j = 2 while j <= i: fat = fat*j j = j+1 #Verificando se o índice é par ou ímpar e gerando o seu respectivo valor if i%2 == 0: info = (3**i + 7*fat) meuVetor.append(info) elif i%2 != 0: info = (2**i + 4*log(i)) meuVetor.append(info) #Printando o vetor gerado print(meuVetor) #Resposta1 maiorvalor = max(meuVetor) print("O maior valor presente no vetor solicitado é: {0:.2f}.".format(maiorvalor)) #Resposta2 media = sum(meuVetor)/len(meuVetor) print ("A média dos componentes do vetor solicitado é: {0:.2f}.".format(media))
import os from banner import banner banner(" HTML TAG COUNTER"," Skyler") def load(filename): data = [] if os.path.exists(filename): print(f"..... loading from {filename}") with open(filename) as fin: for entry in fin.readlines(): data.append(entry.rstrip()) return data def main(): run_event_loop() def count_tags(line): count = 0 previous_char = None for char in line: if char != "/" and previous_char == "<": count += 1 previous_char = char return count def run_event_loop(): while True: filename = input("Please enter the name of HTML file: ") tags = 0 data = load(filename) for line in data: line_tags = count_tags(line) tags = tags + count_tags(line) print(f"The file {filename} contains {tags} tags.") name = input("would you like to count another html file (Y/N)? ") if name == "N": print("Thank you for using the HTML Tag counter. Goodbye!") break print("Welcome to the HTML counter") print("") main()
""" CP1404/CP5632 Practical Email dictionary update to commit to prac_05 feedback """ email_dict = {} user_email = input(">>> ") while user_email != "": user_name = user_email.split("@")[0].replace(".", " ").title() if input(f"Is your name {user_name}? (Y/n) ").lower() == "n": user_name = input("Name? ").title() email_dict[user_name] = user_email user_email = input(">>> ") for key in email_dict: print(f"{key} {email_dict[key]}")
import random nums = [] while len(nums) < 5: nums.append(random.randint(1, 100)) Sum = str(sum(nums)) print("Five random numbers: ", end= '') print(*nums) print("The sum is " + Sum)
S = int(input("Initial savings: ")) P = int(input("Interest rate (in percentages): ")) P_percent = P/100 + 1 S_after = round((P_percent**5) * S) print("The value of your savings after 5 years is: ", S_after)
import random from math import pi print("choose N ammount of (x,y) points") print() print("1: n = 100") print("2: n = 10000") print("3: n = 1000000") n_select = int(input("input: ")) if n_select == 1: n = 100 elif n_select == 2: n = 10000 elif n_select == 3: n = 1000000 else: print("invalid input") exit() def get_pi_approx(): count = 0 for i in range(n): x = random.uniform(-1, 1) y = random.uniform(-1, 1) if x**2 + y**2 < 1: count += 1 return count / n * 4 pi_approx = get_pi_approx() print("Pi approximate:", pi_approx) print("Error:", pi - pi_approx)
def says(): return 'hello' def say(animal, nature): """ returns the voice of animals """ if (animal == 'dog'): return nature + ' Bhow! Bhow!' elif (animal == 'cat'): return nature + ' Meow!' elif (animal == 'lion'): return nature + ' Whraaarr!!' animals = ['dog', 'cat', 'lion', ] nature = 'domestic' for ani in animals: if ani == 'lion': nature = 'wild' print(ani + ' says ' + say(ani, nature)) # unline java we can rename the function names in python talks = says print('human said ' + talks()) # functions can be passed as arguments def add(x, y): return x + y def double_add(func, a, b): return func(func(a, b), func(a, b)) print(double_add(add, 10, 5)) # modules import random as rnd # import control_structures from control_structures import test_function, dummy # importing required functions from modules for i in range(5): print(rnd.randint(1, 6)) print(test_function() + ' ' + dummy())
#!/usr/bin/env python3 """Print a pyramid to the terminal A pyramid of height 3 would look like: --=-- -===- ===== """ from argparse import ArgumentParser, RawDescriptionHelpFormatter def print_pyramid(rows): """Print a pyramid of a given height :param int rows: total height """ width = 2 * rows - 1 for row in range(1, rows + 1): double = 2 * row - 1 single = (width - double) // 2 print('-' * single + '=' * double + '-' * single) if __name__ == "__main__": parser = ArgumentParser( description=__doc__, formatter_class=RawDescriptionHelpFormatter ) parser.add_argument("-r", "--rows", default=10, type=int, help="Number of rows") args = parser.parse_args() print_pyramid(args.rows)
# -*- coding: utf-8 -*- #Modo auditória para checar variáveis (Em desenvolvimento) class ModoAudit(object): def __init__(self, obj): #Recebe a instância da classe statistic self.obj= obj def print_dada(self): print("self.amplitude:", self.obj.amplitude) print("self.initial:", self.obj.initial) print("self.xmin:", self.obj.xmin) print("self.xmax:",self.obj.xmax) print("self.x1:", self.obj.x1) print("self.sum_xi:", self.obj.sum_xi) print("self.sum_fi:", self.obj.sum_fi) print("self.sum_fi_xi:", self.obj.sum_fi_xi) print("self.sum_x3:", self.obj.sum_x3) print("self.sum_x4:", self.obj.sum_x4) print("self.sum_fi_x3:", self.obj.sum_fi_x3) print("self.sum_fi_x4:", self.obj.sum_fi_x4) print("self.quant_xi:", self.obj.quant_xi) print("self.quant_fi:", self.obj.quant_fi) print("self.decimal:", self.obj.decimal) print("self.total_amplitude:", self.obj.total_amplitude) print("self.initial:", self.obj.initial) print("self.list_xi:", self.obj.list_xi) print("self.list_fi:", self.obj.list_fi) print("self.list_fi_xi:", self.obj.list_fi_xi) print("self.list_x2:", self.obj.list_x2) print("self.list_x3:", self.obj.list_x3) print("self.list_x4:", self.obj.list_x4) print("self.list_fi_x3:", self.obj.list_fi_x3) print("self.list_fi_x4:", self.obj.list_fi_x4) print("self.list_fri:", self.obj.list_fri) print("self.list_Fi:", self.obj.list_Fi) print("self.list_Fri:", self.obj.list_Fri) #Amostral e populacional print("self.sample:", self.obj.sample) print("self.populational:", self.obj.populational) #Dados Agrupados - Moda print("self.lmo:", self.obj.lmo) print("self.indice", self.obj.indice) print("self.value:", self.obj.value) print("self.ffant:", self.obj.ffant) print("self.fpost:", self.obj.fpost) print("self.delta_2:", self.obj.delta_2) print("self.delta_1:", self.obj.delta_1) print("self.amplitude:", self.obj.amplitude) print("self.modal:", self.obj.modal) #Configurações para visualizar tabela de frequencia #0 - fri% 1- Fi 2 - Fri% 3 - xi 4 - xi.fi print("self.list_config:", self.obj.list_config) #Configura os dados do menu configurações print("self.modo_agrupados:", self.obj.modo_agrupados)
''' # data augmentation In deep learning tasks, a lot of data is need to train DNN model, when the dataset is not big enough, data augmentation should be applied. keras.preprocessing.image.ImageDataGenerator is a data generator, which can feed the DNN with data like : (data,label), it can also do data augmentation at the same time. It is very convenient for us to use keras.preprocessing.image.ImageDataGenerator to do data augmentation by implement image rotation, shift, rescale and so on... see [keras documentation](https://keras.io/preprocessing/image/) for detail. For image segmentation tasks, the image and mask must be transformed **together!!** ''' from data import trainGenerator, geneTrainNpy import os ## define your data generator # If you want to visualize your data augmentation result, set save_to_dir = your path # if you don't want to do data augmentation, set data_gen_args as an empty dict. # data_gen_args = dict() save_to_dir = "data/membrane/train/aug" data_gen_args = dict(rotation_range=0.2, width_shift_range=0.05, height_shift_range=0.05, shear_range=0.05, zoom_range=0.05, horizontal_flip=True, fill_mode='nearest') if not os.path.exists(save_to_dir): os.makedirs(save_to_dir) myGenerator = trainGenerator(20, 'data/membrane/train', 'image', 'label', data_gen_args, save_to_dir=save_to_dir) # you will see 60 transformed images and their masks in data/membrane/train/aug num_batch = 3 for i, batch in enumerate(myGenerator): if (i >= num_batch): break ## create .npy data # If your computer has enough memory, you can create npy files containing all your images and masks, and feed your DNN with them. image_arr, mask_arr = geneTrainNpy("data/membrane/train/aug/", "data/membrane/train/aug/") # np.save("data/image_arr.npy",image_arr) # np.save("data/mask_arr.npy",mask_arr)
# add two numbers 50+50 and 100-10 print((50+50) + (100-10)) # 30+*6, 6^6, 6**6, 6+6+6+6+6+6 # I'm not sure what the first one is because it's invalid syntax print(f'Bitwise XOR: 6^6 = {6^6}. 0b110 ^ 0b110 = 0b000') print(f'6 to the 6th power = {6**6}') print(f'6+6+6+6+6+6 = {6+6+6+6+6+6}') print('Hello World') print('Hello World : 10') # calculate the monthly payment of a loan with principle P, yearly interest R, and paid in L months def calcLoanPayment(P, R, L): # for this formula, R is 1.__ (interest) # Loan Amortization formula: (R**L) * (R-1) / # (R**L) - 1 * P R = ((R / 12) * 0.01) + 1 dividend = (R ** L) * (R - 1) divisor = (R ** L) - 1 payment = P * (dividend / divisor) # round up if not integer if not payment.is_integer(): payment = int(payment + 1) return payment pment = calcLoanPayment(800000, 6, 103) print(f'Monthly payment: {pment}\nTotal Paid: {pment * 103}')
#-------------- list of symbols and words --------- # # - allows you to type comments in your code # """ - allows you to write a string that covers multiple lines of code. # + - * / - signs used to add, subtract, multiply, and divide # print() - prints the contents within the parentheses # = - assigns a value to a variable # f"{}" - a refference cell # .format() - string formatting method in python3, which allows multiple substitutions and value formatting # end='' - appends space instead of a new line. # \n - escape sequence used to push anything right of the escape sequence to the next line # \t - escape sequence used to tab in anything right of the escape sequence # \\ - escape sequence in order to allow '\' to be printed in a string # input() - allows user input # from - refferences the module in which you will import a specific function # import - the import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope. # argv - argument value # open() - the open() function opens a file, and returns it as a file object. # .read() - returns the specified number of bytes from the file. Default is -1 which means the whole file. # .truncate() - used to truncate the file indicated by the specified path to at most specified length # .write() - writes a string to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called. # .close() - closes the opened file # def - the keyword for defining a function. the function name is followed by parameter(s) in (). The colon: signals the start of the function body, which is marked by indentation. Inside the function body, the return statement determines the value to be returned. # .readline() - reads one entire line from the file. # += - A += B is shorthand for A = A + B, where A and B can be numbers, or strings, or tuples, or lists (but both must be of the same type). # .seek() - sets the file's current position at the offset. # return - Exits a function and optionally pass an expression back to the caller. If you use a return statement with no arguments, the function will return None. # exists - the most common way to check for the existence of a file in python3 from the os.path module in the standard library. # len() - returns the length (the number of items) of an object. # sys - a module you load by importing into the current namespace so that you can access the functions and anything else defined within the module using the module name. # os.path - module that is always the path module suitable for the operating system Python is running on, and therefore usable for local paths.
#line prints string print ("Mary had a little lamb.") #line prints string and uses .format to insert the string snow into another string print("It's fleece was white as {}.".format('snow')) #line prints string print ("And everywhere that Mary went.") #line prints "." 10 times print("."*10) #what'd that do? #line assigns value to variable end1 = "C" #line assigns value to variable end2 = "h" #line assigns value to variable end3 = "e" #line assigns value to variable end4 = "e" #line assigns value to variable end5 = "s" #line assigns value to variable end6= "e" #line assigns value to variable end7 = "B" #line assigns value to variable end8 = "u" #line assigns value to variable end9 = "r" #line assigns value to variable end10 = "g" #line assigns value to variable end11 = "e" #line assigns value to variable end12 = "r" #watch end = '' at then end. try removing it to see what happens #line prints the sum of variables end1-end6 and tells the next print to follow this line's print value print(end1+end2+end3+end4+end5+end6, end='') #line prints the sum of variables end7-end12 print(end7+end8+end9+end10+end11+end12)
#lines 2-4 use argv to get a filename from the user from sys import argv script, filename = argv #this line uses the command open to open the specific file and that open file object is assigned to the variable txt txt = open(filename) #this line prints a little string using a refference print(f"Here's your file {filename}:") #this line prints a read command for the variable txt without parameters print(txt.read()) #this line prints a string print("Type the filename again:") #this line assigns the user input to the variable file_again file_again = input("> ") #this line assigns the open commanded variable file_again to the variable txt_again txt_again = open(file_again) #this line prints a read command for the variable txt_again without parameters print(txt_again.read())
import sys import re import numpy as np fd=open("livres/Les 3 Mousquetaires.txt") lines=fd.readlines() fd.close() ## lexique_raw is a sorted unique list ## of space separated words found in file lexique_raw=[] for l in lines: lexique_raw+=l.split(" ") lexique_raw=list(set(lexique_raw)) ## lexique is a sorted unique list ## of space separated unicode words found in file ## removes nbsp and \n from lexique_raw lexique=[] p = re.compile(r'(\w+)',re.UNICODE) for l in lexique_raw: m=p.search(l) if m: lexique.append(m.group(1)) lexique=list(set(lexique)) lexique.sort()
# Numpy import numpy as np # Creating array from list with type float a = np.array([[10, 11, 12], [13, 14, 15]], dtype = 'float') print(a) print(a[1,2]) # Transpose at = a.T print(at) # Reshape the array b = a.reshape(3,2) print(b) c = a.reshape(1,-1) print(c) d = a.reshape(-1,1) print(d) # Create a matrix of zeros zer = np.zeros((3,4)) print(zer) # Create a matrix of ones ones = np.full((2,4),1) print(ones) # Create an array of random values ra = np.random.random((3,5)) print(ra) # Create a sequence of integers # from 0 to 30 with steps of 5 ran = np.arange(0, 30, 5) print(ran) # Create a sequence of 10 values in range 0 to 5 lin = np.linspace(0, 5, 10) print(lin) # Flatten fl = a.flatten() print(fl) #-------------- # Slicing # Just as a regular list a numpy arrays can be sliced arr = np.array([[-1, 2, 0, 5, 7], [4, -0.5, 6, -1, 2], [2.6, 0, 7, 3, 0], [3, -7, 4, 6, -3]]) sli = arr[1:3, 1:] print(sli) # Conditions cond = arr > 2 print(cond) temp = arr[cond] print(temp) # Operations regular_list = [1,2,3] regular_list2 = [4,5,6] np_list = np.array([1,2,3]) np_list2 = np.array([4,5,6]) print(regular_list+1) print(np_list+1) print(regular_list*5) print(np_list*5) print(regular_list**2) print(np_list**2) print(regular_list + regular_list2) print(np_list + np_list2) # Max, Min, Sum print(arr.max()) print(arr.max(axis = 0)) print(arr.max(axis = 1)) print(arr.sum(axis = 0)) print(arr.sum(axis = 1)) #-------------- # Pandas import pandas as pd data = pd.read_csv("D:\Materialy\Python\Basic_08 - data.csv") print(data) print(data['Name']) print(data['Name'][1]) #Selecting data sel = data[['Name','Surname']] print(sel) print(data.iloc[1,:]) # select all columns in the first row print(data.iloc[:,1]) # select all rows in the first column # Filter, sort # filter all people with age above 25 above_25 = data[data['Age'] > 25] print(above_25) # sort by surname in descending order data.sort_values('Surname', ascending = False) print(data) #-------------- # Task 1 # Find names of people that are # Taller than 175 taller_175 = # older than the mean age older_than_mean =
if __name__ == "__main__": class Employee: num_of_employees = 0 def __init__(self, first, last, salary, performance_rating): self.first = first self.last = last self.salary = salary self.email = first + "." + last + "@company.com" self.performance_rating = performance_rating Employee.num_of_employees += 1 def fullname(self): return '{} {}'.format(self.first, self.last) def merit_raise_strategy(self): if self.performance_rating == 1: return self.salary * 1.05 elif self.performance_rating == 2: return self.salary * 1.03 elif self.performance_rating == 3: return self.salary * 1.00 employee_1 = Employee('Average', 'Employee', 70000, 2) print(employee_1.fullname() + "'s new salary is: $" + str(employee_1.merit_raise_strategy()) + " USD") employee_2 = Employee('Stellar', "Employee", 70000, 1) print(employee_2.fullname() + "'s new salary is: $" + str(employee_2.merit_raise_strategy()) + " USD") employee_3 = Employee('Grumpy', "Pants", 70000, 3) print(employee_3.fullname() + "'s new salary is: $" + str(employee_3.merit_raise_strategy()) + " USD") print("Total number of employees in the system: " + str(Employee.num_of_employees))
# Function that takes in a list and multiplies each element with 5 a = [2,4,10,16] def multiply(array): for i in range(len(array)): array[i] = array[i] * 5 return array b = multiply(a) print b
from datetime import datetime, date, timedelta from dateutil import relativedelta import calendar ONEDAY = timedelta(days=1) ONEMONTH = ONEDAY * 30 # Symbol meanings in function name: # dt: datetime.datetime object # date: usually a datetime.datetime object representing a date e.g. (datetime(2015, 11, 8, 0, 0)), sometimes it also means the datetime.date object # date_str: '2015-11-08' or '2015/11/08' # date_range_str: '2015-11-01--2015-11-08' or '2015/11/01--2015/11/08', both ends are inclusive def iso_year_start(iso_year): """The gregorian calendar date of the first day of the given ISO year""" fourth_jan = date(iso_year, 1, 4) delta = timedelta(fourth_jan.isoweekday()-1) return fourth_jan - delta def iso_to_gregorian(iso_year, iso_week, iso_day): """Gregorian calendar date for the given ISO year, week and day""" year_start = iso_year_start(iso_year) return year_start + timedelta(days=iso_day-1, weeks=iso_week-1) def dt_to_date_str(dt): return str(dt.date()) def parse_date_str(date_str): """parse a date string in 2015-08-01 or 2015/08/01 format to datetime""" try: return datetime.strptime(date_str, '%Y-%m-%d') except ValueError: try: return datetime.strptime(date_str, '%Y/%m/%d') except ValueError: raise ValueError("%s is not a date string" % date_str) def dt2date(dt): return dt.date() def date2dt(date): return parse_date_str(str(date)) def any2dt(obj): """convert datetime, date or date_str to datetime object""" if isinstance(obj, datetime): return obj elif isinstance(obj, date): return date2dt(date) elif isinstance(obj, str): return parse_date_str(obj) else: raise TypeError("Cannot convert %s into datetime object" % obj) def any2date(obj): """convert datetime, date or date_str to date object""" if type(obj) == date: return obj return any2dt(obj).date() def any2date_str(obj): """convert datetime, date or date_str to date_str""" if isinstance(obj, str): return obj return str(any2date(obj)) def normalize_date_str(date_str): """normalize date string to 0000-00-00 format""" return any2date_str(any2date(date_str)) def parse_date_range_str(date_range_str): """parse a date string in "2015-10-08--2015-10-10" format to two datetime objects Return [date1, date2] If the given string is in "2015-10-10" format, then return [date1, date1]""" date_strs = date_range_str.split('--') if len(date_strs) == 1: date_strs *= 2 dates = [parse_date_str(date_str) for date_str in date_strs] return dates def date_range(start, end, freq=None): """Generate date range from start to end Freq is in integer.""" import pandas as pd if freq is None: dr = pd.date_range(start, end) else: try: freq_days = int(freq) freq = '%dD' % freq_days except ValueError: pass dr = pd.date_range(start, end, freq=freq) return [dt.date() for dt in dr.tolist()] def date_str_range(start, end, freq=None): dates = date_range(start, end, freq) date_strs = [str(date) for date in dates] return date_strs def date_range_str_to_dates(date_str, freq=None): """gen dates from '2015-10-28--2015-11-08' to dates""" start, end = parse_date_range_str(date_str) return date_range(start, end, freq) def date_range_str_to_date_strs(date_str, freq=None): """gen date_strs from string like '2015-10-28--2015-11-08' to '2015-10-28'...""" start, end = parse_date_range_str(date_str) return date_str_range(start, end, freq) def date_range_str_to_start_and_end(date_range_str): ts = date_range_str.split('--') if len(ts) == 1: start = ts[0] end = start elif len(ts) == 2: start, end = ts else: return return start, end def date_str_add_days(date_str, days): """add days (in int) to a date_str For example date_str_add_days('2015-08-13', 3) => '2015-08-16' """ date = parse_date_str(date_str) delta = timedelta(days=days) ret_dt = date + delta return dt_to_date_str(ret_dt) def last_day_of_month(year, month): return calendar.monthrange(year, month)[1] def this_monday(date_obj=None): if not date_obj: date_obj = str(datetime.today().date()) dt = any2dt(date_obj) weekday = dt.weekday() delta = timedelta(days=weekday) return str((dt - delta).date()) def gen_today_date_str(): return str(datetime.today().date()) def gen_yesterday_date_str(): return date_str_add_days(gen_today_date_str(), -1) def gen_tomorrow_date_str(): return date_str_add_days(gen_today_date_str(), 1) def gen_date_range_str(start_date, end_date): return "%s--%s" % (str(start_date), str(end_date)) def gen_week_date_range_str(year, week): first_day = iso_to_gregorian(year, week, 1) last_day = iso_to_gregorian(year, week, 7) return gen_date_range_str(first_day, last_day) def gen_last_week_date_range_str(today=None): if today: today = any2dt(today) else: today = datetime.today() last_week_day = today - timedelta(days=7) year, week, _ = last_week_day.isocalendar() return gen_week_date_range_str(year, week) def gen_month_date_range_str(year, month): first_day = datetime(year, month, 1).date() last_day = datetime(year, month, last_day_of_month(year, month)).date() return gen_date_range_str(first_day, last_day) def gen_month_date_range_strs(year, months): return [gen_month_date_range_str(year, month) for month in months] def month_range(start, end): ret = [] if start > end: return ret start_year, start_month = start start_date = datetime(start_year, start_month, 1) end_year, end_month = end end_date = datetime(end_year, end_month, 1) ret.append((start_year, start_month)) while start_date != end_date: next_month_of_start_date = start_date + relativedelta.relativedelta(months=1) year = next_month_of_start_date.year month = next_month_of_start_date.month ret.append((year, month)) start_date = next_month_of_start_date return ret def gen_month_range_date_range_strs(start, end): return [gen_month_date_range_str(year, month) for year, month in month_range(start, end)] def parse_datetime_str(s): try: dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S.%f') except ValueError: dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S') return dt
#!/usr/bin/env python # coding: utf-8 # In[4]: # tuplas são listas, porém são imutáveis tupla = (12, 'string', 13.7, 'outra string') print(tupla) #posso imprimir um elemento só da tupla print ('elemento 2: ', tupla[2]) # In[5]: # posso juntar duas tuplas tupla1 = (10, 'string') tupla2 = (20, 'mais uma') tupla3 = tupla1 + tupla2 print(tupla3) # In[6]: # Se tentarmos mudar uma tupla ocorrerá um erro tupla4 = (10, 20, 30) tupla4[2] = 0 # In[10]: # posso usar um laço de repetição para percorrer uma tupla tupla5 = ('primeiro', 'segundo', 'terceiro') for i in range(0,3): print(tupla5[i])
from Q1_1 import get_data import pandas as pd import numpy as np from sklearn.cluster import KMeans import matplotlib.pyplot as plt from sklearn.decomposition import PCA train_x,train_y,test_x,test_y = get_data() train_x = train_x.append(test_x) km = KMeans(n_clusters=3).fit(train_x) y = km.predict(train_x) pca = PCA(n_components=2) train_x = pca.fit_transform(train_x) plt.scatter(train_x[:, 0], train_x[:, 1], c=y) plt.xlabel('x') plt.ylabel('y') plt.title('Q1_3 : Scatter plot of clusters') #plt.show()
test = input("enter the word") s = "" for i in range(0, len(test)): if test[i].islower(): s = s+test[i].upper() elif test[i].isupper(): s = s+(test[i].lower()) else: s = s+test[i] print(s) print(test.swapcase())
again=input("If you want to encrypt/decrypt password enter yes, not Enter no : ") while(again=="yes"): n=input("Enter Your choice (Encrypt=1 Decrypt=2) : ") if(n=="1"): plaintext=input("Enter Password : ") alphabet="abcdefghijklmnopqrstuvwxyz" k=3 cipher='' for c in plaintext: if c in alphabet: cipher +=alphabet[(alphabet.index(c)+k)%(len(alphabet))] print('Your encrypted msg is : ' + cipher) elif(n=="2"): plaintext=input("Enter Password : ") alphabet="zyxwvutsrqponmlkjihgfedcba" k=3 cipher='' for c in plaintext: if c in alphabet: cipher +=alphabet[(alphabet.index(c)+k)%(len(alphabet))] print('Your decrypted msg is : ' + cipher) else: print("Wrong Choice") again=input("If you want to encrypt/decrypt password again enter yes, not Enter no : ")
# Binary Converter # By Ex094 class txt2bin: def __init__(self): pass def encode(self, text): enc = "" for char in text: enc += bin(ord(char))[2:].zfill(8) return enc def decode(self, text): dec = "" txt = [] for x in range(int(len(text) / 8)): txt.append(text[x * 8:(x * 8) + 8]) for item in txt: dec += chr((int(item, 2))) return dec binary = txt2bin()
def reverse_lookup(d,v): l = [] for k in d: if d[k] == v: l +=[k] return l def hist(s): d = dict() for c in s: d[c] = d.get(c, 0) + 1 return d hist = hist("hangover") k=reverse_lookup(hist,2) print(k)
def has_duplicates(str): for i in range(0,len(str)): if(str[i]==str[i+1]): return True else: return False print(has_duplicates([1,1,2,2,3,3,5]))
def nested_sum(list): total=0 for l in list: if (type(l) == type([])): total = total + nested_sum(l) else: total = total + l return total n = [[2,3],[2,3],[5,7]] print("Sum is:", nested_sum(n))
#python basics Assignment - 7 # Task: Print the FizzBuzz numbers. # FizzBuzz is a famous code challenge used in interviews to test basic programming skills. It's time to write your own implementation. # Print numbers from 1 to 100 inclusively following these instructions: # if a number is multiple of 3, print "Fizz" instead of this number, # if a number is multiple of 5, print "Buzz" instead of this number, # for numbers that are multiples of both 3 and 5, print "FizzBuzz", # print the rest of the numbers unchanged. # Output each value on a separate line. # Note that: This question is famous on the web, so to get more benefit from this assignment, try to complete this task on your own. num = 100 for i in range(1, num+1): if i%3 == 0 and i%5 != 0: print('Fizz', str(i)) elif i %5 == 0 and i%3 != 0: print('Buzz', str(i)) elif i%3 == 0 and i%5 == 0: print('FizzBuzz', str(i)) else: print(i)
from random import randint from time import time from array import array def clock(): start = time() while 1: yield time() - start def bubble_sort(a): n = len(a) while n != 0: newn = 0 i = 1 while i < n: fir = a[i - 1] if fir > a[i]: a[i - 1] = a[i] a[i] = fir newn = i i += 1 n = newn def fuzzy_sort(a): L = len(a) m = (L - 1) / float(max(a)) sorted = [None] * L for x in a: index = int(m * x) if sorted[index]: sorted[index].append(x) else: sorted[index] = array('i', [x]) for i in range(L): s = sorted[i] if s: bubble_sort(s) sorted.extend(s) return sorted[L:] def main(): a = [randint(0, 100000) for i in range(1000000)] print("Sorting...") timer = clock() timer.next() a = fuzzy_sort(a) print("Sorted %d items in %f seconds" % (len(a), timer.next())) print('\t '.join(map(str, a[:1000]))) if __name__ == "__main__": main()
dict1 = {"name": "pavichaya", "age": "20"} dict2 = {"name": "pavichaya", "age": "20"} dict3 = dict1 print(dict1 is dict3) print(dict1 is dict2) print(dict1 == dict2)
vectorSaga=['luck','yoda','mike'] def barrido (vector,pos): if vector==[]: return 'NO HAY PERSONAJES' else: if pos<len(vector): return vector[pos]+ str(barrido(vector,pos+1)) print(barrido(vectorSaga,0)) # #QUERIA SABER SI DE LA PRIMERA MANERA TAMBIEN SE PUEDE def barrido2(vector): if len(vector)>0: print(vector[0]) barrido2(vector[1:]) print(barrido2(vectorSaga)) pos=0 def EncontrarYoda(vector,pos): if (pos<len(vector)): if (vector[pos]=='yoda'): return pos else: return EncontrarYoda(vector,pos+1) else: return-1 if pos!=-1: print('el objeto fue encontrado en la posicion ' + str(EncontrarYoda(vectorSaga,0)))
import pygame pygame.init() SIZE = WIDTH, HEIGHT = 1000, 800 BLACK = 0, 0, 0 screen = pygame.display.set_mode(SIZE) done = False clock = pygame.time.Clock() class Ball(): def __init__(self, x, y, radius, color = (255,0,0)): self.x = x self.y = y self.color = color self.radius = radius self.route = [] def draw(self): pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius) def move(self): self.x += 1 self.draw() def set_to_animate(self, x, y, time, FPS): steps = int(time*FPS) if self.route: X, Y = self.route[-1] else: X, Y = self.x, self.y dX = (x - X)//steps dY = (y - Y)//steps for i in range(1, steps): self.route.append((X + i * dX, Y + i * dY)) def animate(self): if self.route: self.x, self.y = self.route.pop(0) self.draw() ball = Ball(500, 400, 50) FPS = 20 while not done: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: done = True exit() if event.type == pygame.MOUSEBUTTONDOWN: ball.set_to_animate(*event.pos, 0.2, 20) screen.fill(BLACK) ball.animate() pygame.display.flip()
# CS122-Win-17 import bs4 import urllib3 import csv import sqlite3 def crawl_census(variable_codes=None, cbsa_codes=None, filename='census.csv'): ''' Crawls 2015 American Community Survey Inputs: variable_codes: a list of strings, each string is a code for a census variable cbsa_codes: a list of strings, each string is a code for a CBSA/MSA filename: (str) optional filename to save results to as a CSV Returns: If filename provided, creates a file with that filename that contains data crawled from the census. If no filename provided, returns a list of lists containing data crawled from the census. ''' # Get CBSA codes if not cbsa_codes: cbsa_codes = get_cbsa_codes_list() cbsa_str = ",".join(cbsa_codes) # Get variable codes if not variable_codes: variable_codes = get_variable_codes_list() variables_str = ",".join(variable_codes) pm = urllib3.PoolManager() key = None #get key from Census query_url = "http://api.census.gov/data/2015/acs5?get={}&for=metropolitan+statistical+area/micropolitan+statistical+area:{}&key={}}".format(variables_str, cbsa_str, key) html = pm.urlopen(url=query_url, method="GET").data soup = bs4.BeautifulSoup(html, "lxml") string = soup.get_text("|", strip=True) str_split = string.split(",\n") str_split = str_split[1:] # Remove header row values = [] for row in str_split: no_brackets = row.strip('[]') row_vals = no_brackets.split(",") # Convert row values to appropriate types (float, int, str) new_row_vals = [] for i, v in enumerate(row_vals): v = v.strip('"') if i == len(row_vals)-1: new_val = int(v) elif v != "null": new_val = float(v) else: new_val = v new_row_vals.append(new_val) values.append(new_row_vals) if filename: with open(filename, "wt") as f: writer = csv.writer(f) writer.writerows(values) else: return values def get_cbsa_codes_list(): ''' Returns a list of CBSA codes from the file 'cbsa_zips.csv'. ''' cbsa_codes = [] with open('cbsa_data/cbsa_zips.csv', 'r') as f: reader = csv.reader(f) for row in reader: cbsa_code = row[3] if cbsa_code not in cbsa_codes: cbsa_codes.append(cbsa_code) f.close() return cbsa_codes def get_variable_codes_list(filename='census_variables.csv'): ''' Returns a list of census variable codes from the spcified file (default='census_variables.csv'). ''' variable_codes = [] with open('census_variables.csv', 'r') as f: reader = csv.reader(f) for row in reader: variable_code = row[1] variable_codes.append(variable_code) f.close() return variable_codes
#sol 1 class Solution: def isSymmetric(self, root: TreeNode) -> bool: def isMirror(L, R): if not L and not R: return True if L and R and L.val == R.val: return isMirror(L.left, R.right) and isMirror(L.right, R.left) return False return isMirror(root, root) ``` 대칭트리인지 확인한 후 아니면 False값을 반환하고 대칭트리이면, 거울 모드인지 계속해서 확인해서 값을 반환한다. ```
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: ListNode) -> ListNode: prev = None current = head #현재 위치가 null값이 아닐 때까지 tail마저 벗어나버린 상태가 아닐 때까지만 진행 while current: #다음 위치의 값을 저장해주자. next_up = current.next #리스트의 시작값의 방향키를 바꿔주자 current.next = prev #다음 단계로 넘어가기 위해, 이전 위치와, 현재 위치값을 재설정해주자. prev = current current = next_up #리스트의 시작점 또한 바꿔주자. head = prev return head
``` sol 1 ``` # Time Complexity: O(N) # Space Complexity: O(1) class Solution: def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ # initiate ans list (ans 리스트 초기화) ans = [] for num in range(1,n+1): divisible_by_3 = (num % 3 == 0) divisible_by_5 = (num % 5 == 0) if divisible_by_3 and divisible_by_5: ans.append("FizzBuzz") elif divisible_by_3: ans.append("Fizz") elif divisible_by_5: ans.append("Buzz") else: # don't forget to add string type to num variable # (리스트 내부요소에서는 string, integer가 혼용될 수 없다) ans.append(str(num)) return ans ``` sol 2 ``` # Time Complexity: O(N) # Space Complexity: O(1) class Solution: def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ # ans list ans = [] for num in range(1,n+1): divisible_by_3 = (num % 3 == 0) divisible_by_5 = (num % 5 == 0) num_ans_str = "" if divisible_by_3: num_ans_str += "Fizz" if divisible_by_5: num_ans_str += "Buzz" if not num_ans_str: num_ans_str = str(num) # Append the current answer str to the ans list ans.append(num_ans_str) return ans ``` sol 3. Hash Table ``` # Time Complexity : O(N) # Space Complexity : O(1) class Solution: def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ # ans list ans = [] # Dictionary to store all fizzbuzz mappings fizz_buzz_dict = {3 : "Fizz", 5 : "Buzz"} for num in range(1,n+1): num_ans_str = "" for key in fizz_buzz_dict.keys(): # If the num is divisible by key, # then add the corresponding string mapping to current num_ans_str if num % key == 0: num_ans_str += fizz_buzz_dict[key] if not num_ans_str: num_ans_str = str(num) # Append the current answer str to the ans list ans.append(num_ans_str) return ans
import math import os import random import re import sys def getRank(arr): rank = {} for i in arr: if i in rank.keys(): rank[i] = rank[i] + 1 else: rank[i] = 1 return rank def countTriplets(arr, r): sum_array=[] if r==1: for i in range(len(arr)-1): sum_array.append((i*(i+1))/2) return sum(sum_array) count= 0 rank = getRank(arr) startelemmap = {} for i in range(0, len(arr)-2): first = arr[i] second = first*r third = second*r noofset = 0 if first not in startelemmap.keys(): if second in rank.keys(): if third in rank.keys(): noofset = rank[first]*rank[second]*rank[third] startelemmap[first]=1 print(first, second,third,noofset) count = count + noofset return count if __name__ == "__main__": fptr = open(os.environ['OUTPUT_PATH'], 'w') nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) result = countTriplets(arr,r) fptr.write(str(result)+'\n') fptr.close()
class Stack: def __init__(self, data): self.data = data def get_top(self): return self.data[-1] def pop(self): top = self.data[-1] del(self.data[-1]) def computeMap(self): numMin_for_maxWin = {} while(self.data!=[]): top = self.get_top() max_win_size = 0 idx = len(self.data)-1 while(top<=self.data[idx] and idx>=0): max_win_size = max_win_size + 1 idx = idx -1 self.pop() offset = 0 if numMin_for_maxWin.keys(): min_key = min(numMin_for_maxWin.keys()) if top<min_key: offset = numMin_for_maxWin[min_key] if top in numMin_for_maxWin.keys(): numMin_for_maxWin[top] = max(max_win_size+offset,numMin_for_maxWin[top]) else: numMin_for_maxWin[top] = max_win_size+offset return numMin_for_maxWin def riddle(arr): # Largest window a given number is minimum for s = Stack(arr) numMin_for_maxWin = s.computeMap() print(numMin_for_maxWin) if __name__ == "__main__": arr = [11, 2, 3, 14, 5, 2, 11, 12] print(riddle(arr))
def swap_case(s): new_s = "" for word in s: for char in word: if char.isupper(): new_s = new_s + char.lower() else: new_s = new_s + char.upper() return new_s if __name__ == '__main__': s = input() result = swap_case(s) print(result)
# Enter your code here. Read input from STDIN. Print output to STDOUT if __name__ == "__main__": input = input().split() n = int(input[0]) m = int(input[1]) #n = 7 #m = 21 design = ".|." no_of_design = 1 no_of_dashes = (m-3)/2 msg = "WELCOME" for i in range(n): if i < int((n-1)/2): print("-"*int(no_of_dashes)+design*no_of_design+"-"*int(no_of_dashes)) no_of_design = int(no_of_design + 2) no_of_dashes = int((m - (3*no_of_design))/2) elif i == int((n-1)/2): print("-"*int((m-7)/2)+"WELCOME"+"-"*int((m-7)/2)) else: no_of_design = int(no_of_design-2) no_of_dashes = int((m - (3*no_of_design))/2) print("-"*int(no_of_dashes)+design*no_of_design+"-"*int(no_of_dashes))
#!/bin/python3 import math import os import random import re import sys # Complete the poisonousPlants function below. class Stack: def __init__(self): self.data = [] self.size = 0 def peek(self): return self.data[-1] def front(self): return self.data[0] def push(self, elem): self.data.append(elem) self.size = self.size + 1 def pop(self): if self.size != 0: del(self.data[-1]) self.size = self.size - 1 def remove_front(self): if self.size != 0: del(self.data[0]) self.size = self.size - 1 def erase_data(self): self.data = [] self.size = 0 def printStack(self): print(self.data) def merge(s1, s2): s1.printStack() s2.printStack() for elem in s2: s1.push(elem) def merge_stacks(list_of_stacks): merge = False for idx, stack in enumerate(list_of_stacks): if stack.size == 0: del(list_of_stacks[idx]) for stack in list_of_stacks: stack.printStack() print(len(list_of_stacks)) start = len(list_of_stacks)-1 for idx in range(start, 0): s1 = list_of_stacks[idx-1] s2 = list_of_stacks[idx] if s1.peek() >= s2.front(): for elem in s2.data: print(elem) s1.push(elem) #del(list_of_stacks[idx]) return list_of_stacks def poisonousPlants(p): days = 0 list_of_stacks = [] curr_stack = Stack() curr_stack.push(p[0]) for idx in range(1, len(p)): if curr_stack.peek() > p[idx]: curr_stack.push(p[idx]) else: list_of_stacks.append(curr_stack) curr_stack = Stack() curr_stack.push(p[idx]) list_of_stacks.append(curr_stack) loopit = True while loopit: for idx, stack in enumerate(list_of_stacks): if idx != 0 and stack.size != 0: stack.remove_front() list_of_stacks = merge_stacks(list_of_stacks) days = days + 1 if len(list_of_stacks) == 1: loopit = False return list_of_stacks, days if __name__ == '__main__': """fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) p = list(map(int, input().rstrip().split())) result = poisonousPlants(p) fptr.write(str(result) + '\n') fptr.close() """ list = [6, 5, 8, 4, 7, 10, 9] list_of_stacks, days = poisonousPlants(list) for stack in list_of_stacks: stack.printStack() print(int(days-1))
class Stack: def __init__(self): self._data = [] self._size = 0 def is_empty(self): return self._size == 0 def __len__(self): return self._size def peek(self): return self._data[-1] def push(self, elem): self._data.append(elem) self._size = self._size + 1 def pop(self): if self.is_empty(): return -1 else: top = self._data[-1] del(self._data[-1]) self._size = self._size - 1 return top def printStack(self): print(self._data) def largestRectangle(hist): posStack = Stack() hStack = Stack() maxArea = 0 for pos, hgt in enumerate(hist): if pos ==0 or hStack.peek() < hgt: posStack.push(pos) hStack.push(hgt) if pos == len(hist)-1: print(pos) posStack.printStack() hStack.printStack() while(hStack.__len__() > 0 ): area = hStack.pop()*(pos-posStack.pop()+1) print(area) if area >= maxArea: maxArea = area return maxArea if __name__ == "__main__": maxArea = largestRectangle([1, 2, 3, 4, 5]) print("M:", maxArea)
#!/bin/python3 import math import os import random import re import sys # Complete the miniMaxSum function below. def getSum(arr): total = 0 for i in arr: total += i print("Total:", total) return total def miniMaxSum(arr, total): min = total max = 0 for i in arr: a = total - i if min > a: min = a if max < a: max = a return min, max if __name__ == '__main__': arr = [1, 2, 3, 4, 5] total = getSum(arr) min, max = miniMaxSum(arr, total) print(min, max)
""" A Statements which are executed by given conditions is known as Conditional statements if condition: print("If condition is true then this if statement will execute") else: print("If condition is false then else statement will execute") Here we can use below Operators in conditional statements 1.) Comparison Operators Equals: a == b Not Equals: a != b Less than: a < b Less than or equal to: a <= b Greater than: a > b Greater than or equal to: a >= b 2.) Logical Operators : and , or 3.) Identity Operators such as : is , is not 4.) Membership Operators such as : in , not in """ a =10 b=5 c=10 if a<b: print("This is a If statement") elif a>c: print("This is a elif statement -1") elif c>b: print("This is elif statement-2") else: print("this is a else statement") if a<b: if a==c: print("A and C are equal") else: print("This is Else") else: print("This is 1st else")
""" What is a variable? Variables are containers for storing values. We can store any data values in python variable In python no need to declare any command to create a variable. A variable is created the moment you first assign a value to it. Python variables Rules ========================= A variable name must start with a letter or the underscore character ( a = 5 or _name = "python" or name = "python" ) A variable name cannot start with a number (1_a = 5 or 1name ="python" ) A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) (name_1 = "python) Variable names are case-sensitive (name, Name and NAME are three different variables) """ a = 5 a = "python" b = 5.2 print(a) name = "Python" Name = "Hello" # Assign single value to Multiple Variables a = b = c = 3 print(a) print(b) print(c) # Assign multiple values to Multiple Variables in single line a, b, c = 1, 2, 3 print(a) print(b) print(c)
# ***************************** 5. Dictionary Data Type ***************************** """ -Dictionaries are the key and value pairs. Which are written with curly brackets. " { } " Ex : employeeData = { "name": "Anil", "number": "9876543210", "DOB": 1990 } """ # Create a Dictionary employeeData={"name":"Anil","number":987654310,"DOB":1990} print(employeeData) print(type(employeeData)) # Access the value from dictionary a=employeeData["number"] print(a) # Update or change the value employeeData["name"] ="Kumar" print(employeeData) # Add key and value for existing dictionary employeeData["address"]="India" print(employeeData) # length of a dictionary print(len(employeeData)) # Copy the dictionary to other variable emp = employeeData.copy() print(emp) # Iterate the values in dictionary for a in employeeData.keys(): print(employeeData[a]) # Iterate both keys and values for a,b in employeeData.items(): print(a,b) # Remove the value employeeData.pop("address") print(employeeData) # Clear the dictionary employeeData.clear() print(employeeData) # delete the dictionary del employeeData #print(employeeData)
""" To perform the operations on variables and its values we will use Operators. In Python there are divides the operators into 7 groups. Arithmetic operators Assignment operators Comparison operators Logical operators Identity operators Membership operators Bitwise operators """ # **************************** 1.) Arithmetic Operators ************************** """ Arithmetic Operators such as Addition(+) , Subtraction(-) , Multiplication(*) , Division(/) , Floor division(//), Exponentiation(**) and Modulus(%). """ a = 10 b = 5 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) # Quiescent print(a ** b) # a to the power b print(a % b) # Remainder """ 2.) Comparison Operators Equals: a == b Not Equals: a != b Less than: a < b Less than or equal to: a <= b Greater than: a > b Greater than or equal to: a >= b 3.) Logical Operators : and , or 4.) Identity Operators such as : is , is not 5.) Membership Operators such as : in , not in """
#basic for x in range(151): print(x) #multiples of five for x in range(0, 1001, 5): print(x) #counting, the dojo way for x in range(1, 101): if x % 5 == 0: print("Coding") continue elif x % 10 == 0: print("Coding Dojo") continue print(x) #whoa. that sucker's huge y=0 for x in range(0, 500001): if x % 2 != 0: y = y + x if x == 500000: print(y) #countdown by fours for x in range(2018, 0, -4): print(x) #flexible counter lowNum=1 highNum=1000 mult=4 for x in range(lowNum, highNum, 1): if x % mult == 0: print(x)
class BankAccount: def __init__ (self,int_rate,balance): self.int_rate = int_rate self.balance = balance def deposit(self, amount): self.balance += amount return self def withdraw(self, amount): self.balance -= amount if self.balance >= amount: self.balance -= amount else: self.balance- 5 print("Insufficent Funds! Charging $5 Fee") return self def display_account_info(self): print(f"Balance: ${self.balance}") return self def yield_interest(self): if self.balance > 0: self.balance = self.balance + self.balance * self.int_rate return self # ba1 = BankAccount(0,2030210) # ba2 = BankAccount(.012, 2103413) # ba1.deposit(1000).deposit(123123).deposit(213).withdraw(2321321321).yield_interest().display_account_info() # ba2.deposit(1000).deposit(123123).withdraw(100).withdraw(200).withdraw(300).withdraw(400).yield_interest().display_account_info() class User: def __init__ (self, name, email): self.name = name self.email = email self.account = BankAccount(int_rate=0.02, balance = 0) def make_withdrawl(self, amount): self.account.withdraw = amount return self def make_deposit(self, amount): self.account.deposit = amount return self.account def display_user_balance(self): print(f"User:{self.name}, Balance:${self.account.display_account_info}") todd = User("Todd", "todd.smith@gmail.com") sara = User("Sara","sara.smith@gmail.com") jim = User("Jim", "jim.smith@gmail.com") todd.account.deposit(100) todd.make_deposit(100) todd.make_deposit(100) todd.make_withdrawl(300) todd.display_user_balance() sara.make_deposit(800) sara.make_deposit(1500) sara.make_withdrawl(200) sara.make_withdrawl(234) sara.display_user_balance() jim.make_deposit(3000000) jim.make_withdrawl(2500) jim.make_withdrawl(13000) jim.make_withdrawl(2400) jim.display_user_balance()
'''Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i''' input_array = [1,2,3,4,10] output_array = [] for i in input_array: prod = 1 for j in input_array: if i!=j: prod *= j output_array.append(prod) for k in output_array: print(k)
a = 10 b = 13 if (a % 2 == 0) and (b % 2 == 0) : print("모두 짝수 입니다.") if (a % 2 == 0) or (b % 2 == 0) : print("두 수중 하나 이상이 짝수입니다.")
selected = None while selected not in ['가위','바위','보'] : selected = input('가위,바위,보 중에서 선택>') print('선택한 값은:',selected)
#! python3 ''' Zebra Puzzle ''' import itertools def immediate_right(house1, house2): ''' House house1 is immediately right of house2 if house1-house2 == 1. ''' return house1 - house2 == 1 def next_to(house1, house2): ''' Two houses are next to each other if they differ by 1. ''' return abs(house1 - house2) == 1 def zebra_puzzle(): ''' Return a tuple (WATER, ZEBRA) indicating their house numbers. ''' houses = first, _, middle, _, _ = [1, 2, 3, 4, 5] orderings = list(itertools.permutations(houses)) # 1 return next((WATER, ZEBRA) for (red, green, ivory, yellow, blue) in orderings if immediate_right(green, ivory) # 6 for (Englishman, Spaniard, Ukrainian, Japanese, Norwegian) in orderings if Englishman is red # 2 if Norwegian is first # 10 if next_to(Norwegian, blue) #15 for (coffee, tea, milk, oj, WATER) in orderings if coffee is green # 4 if Ukrainian is tea # 5 if milk is middle # 9 for (OldGold, Kools, Chesterfields, LuckyStrike, Parliaments) in orderings if Kools is yellow # 8 if LuckyStrike is oj # 13 if Japanese is Parliaments # 14 for (dog, snails, fox, horse, ZEBRA) in orderings if Spaniard is dog # 3 if OldGold is snails # 7 if next_to(Chesterfields, fox) # 11 if next_to(Kools, horse) # 12 ) def timed_call(fn, *args): ''' Call function with args; return the time in seconds and result. ''' import time start_time = time.clock() result = fn(*args) end_time = time.clock() return end_time - start_time, result def average(numbers): "Return the average (arithmetic mean) of a sequence of numbers." return sum(numbers) / float(len(numbers)) def timed_calls(n, fn, *args): """Call fn(*args) repeatedly: n times if n is an int, or up to n seconds if n is a float; return the min, avg, and max time""" if isinstance(n, int): times = [timed_call(fn, *args)[0] for _ in range(n)] else: times = [] total_time = 0.0 while total_time < n: time = timed_call(fn, *args)[0] times.append(time) total_time += time return min(times), average(times), max(times) def c(sequence): ''' Generate items in sequence; keeping counts as we go. c.starts is the number of sequences started; c.items is number of items generated. ''' c.starts += 1 for item in sequence: c.items += 1 yield item def instrument_fn(fn, *args): ''' Instrument for count how many items generator from generator. ''' c.starts, c.items = 0, 0 result = fn(*args) print('%s got %s with %5d iters over %7d items' % (fn.__name__, result, c.starts, c.items)) def floor_puzzle(): ''' Hopper, Kay, Liskov, Perlis, and Ritchie live on different floors of a five-floor apartment building. Hopper does not live on the top floor. Kay does not live on the bottom floor. Liskov does not live on either the top or the bottom floor. Perlis lives on a higher floor than does Kay. Ritchie does not live on a floor adjacent to Liskov's. Liskov does not live on a floor adjacent to Kay's. ''' floors = bottom, _, _, _, top = [1, 2, 3, 4, 5] orderings = itertools.permutations(floors) # init for Hopper, Kay, Liskov, Perlis, Ritchie in orderings: if (Hopper is not top # 1 and Kay is not bottom # 2 and Liskov is not top and Liskov is not bottom # 3 and Perlis > Kay # 4 and abs(Ritchie - Liskov) > 1 # 5 and abs(Liskov - Kay) > 1 # 6 ): return [Hopper, Kay, Liskov, Perlis, Ritchie] if __name__ == '__main__': print(timed_calls(1000, zebra_puzzle)) print(floor_puzzle())
#!/usr/bin/python3 import psycopg2 DBNAME = "news" def execute_query(query): """ Executes the given query against the given database name :param query: SQL query to execute :return: Result of the database query """ try: db = psycopg2.connect(database=DBNAME) c = db.cursor() c.execute(query) results = c.fetchall() db.close() return results except Exception as e: print("Failed to execute query:\n {}Error: {}\n". format(query, e)) def get_popular_articles(): """What are the most popular three articles of all time?""" GET_QUERY = """SELECT articles.title, clean_articles.views FROM (SELECT REPLACE(SUBSTRING(log.path, 10),'-', ' ') AS article, count(log.path) AS views FROM log WHERE log.status = '200 OK' AND log.path LIKE '%article%' GROUP BY log.path ORDER BY views DESC LIMIT 3) as clean_articles, articles WHERE articles.title ~* clean_articles.article ORDER BY clean_articles.views DESC; """ return execute_query(GET_QUERY) def get_popular_authors(): """Who are the most popular (top 5) article authors of all time?""" GET_QUERY = """ SELECT authors.name, COUNT(log.path) AS total_views FROM authors, log, articles WHERE log.status = '200 OK' AND articles.author = authors.id AND SUBSTRING(log.path, 10) = articles.slug GROUP BY authors.name ORDER BY total_views DESC; """ return execute_query(GET_QUERY) def get_error_day(): """On which days did more than 1% of requests lead to errors?""" GET_QUERY = """SELECT TO_CHAR(error.day::DATE,'Mon dd, yyyy') AS date, TRUNC(error.prc::NUMERIC, 2) FROM (SELECT error.day as day, 100*(error.num::float/req.num::float) AS prc FROM (SELECT DATE(time) as day, count(*) as num FROM log WHERE status = '404 NOT FOUND' GROUP by day ORDER BY num DESC) as error, (SELECT date(time) as day, count(*) as num FROM log GROUP by day ORDER BY num DESC) as req WHERE error.day = req.day AND 100*(error.num::float/req.num::float) > 1 ORDER BY error.day) AS error; """ return execute_query(GET_QUERY) if __name__ == '__main__': print("The top 3 articles are:") for article in get_popular_articles(): print("{} -- {} views".format(article[0], article[1])) print("\nThe top authors are:") for top in get_popular_authors(): print("{} -- {} views".format(top[0], top[1])) print("\nThe day(s) request errors greater than 1%:") for error_day in get_error_day(): print("{} -- {}% errors".format(error_day[0], error_day[1]))
import re gpa_map = { "A": 4.0, "AB": 3.5, "B": 3.0, "BC": 2.5, "C": 2.0, "D": 1.0, "E": 0.0, } def parse_command(command: str): """ command (str): "4A 3B 2C 5BC 2AB 2E 2AC initial 3.72 72" """ arguments = command.split("initial")[-1] regex_match = re.compile(r'(\d[\.,]?\d*)') initial_gpa, total_credit = re.findall(regex_match, arguments) return float(initial_gpa), float(total_credit) # TODO : Make test case for Regex to prevent further bug def calc_gpa_string(string: str, inital_gpa=0, total_credit=0): """ string (str): "4A 3B 2C 5BC 2AB 2E 2AC" """ string = string.upper() regex_match = re.compile(r'(\dAB|\dBC|\d[A-E])') total = 0 count_total = 0 matches = re.findall(regex_match, string) if len(matches) == 0: return "Please give the correct format {credit}{grade}" for gpa_string in matches: grade = gpa_string.strip()[1:] count = int(gpa_string.strip()[0]) if count <= 0: return "Please give a valid credit > 0" count_total += count total += count*gpa_map[grade] if total == 0: return "Please give a valid credit > 0" gpa = (total+inital_gpa*total_credit)/(count_total+total_credit) return "{:.2f}".format(gpa) def get_gpa(command: str): """ command (str): "4A 3B 2C 5BC 2AB 2E 2AC initial 3.72 72" """ if "initial" in command: initial_gpa, total_credit = parse_command(command) return calc_gpa_string( command, inital_gpa=initial_gpa, total_credit=total_credit) return calc_gpa_string(command)
'''This code is written after watching this: https://www.youtube.com/watch?v=EK32jo7i5LQ&t=100s In short we take the Prime Numbers (or Natural Numbers) and plot them taking each number as a parametric coordinate i.e if the number is say p, the corresponding (r,theta) is (p,p). Then we convert this to cartesian coordinate by (x,y) = (r*Cos(theta), r* Sin(theta)), and plot these. For details and explanation we should watch the video or visit: https://math.stackexchange.com/questions/885879/meaning-of-rays-in-polar-plot-of-prime-numbers/885894 ''' ### Sahil Islam ### ### 03/06/2020 ### import matplotlib.pyplot as plt import numpy as np def ifprime(num): if num > 1: for i in range(2, num): if (num % i) == 0: return False else: return True else: return False def listingPrimeNums(nMax): primeNums = [] nonPrimeNums = [] for i in range(nMax): if ifprime(i): primeNums.append(i) else: nonPrimeNums.append(i) return primeNums, nonPrimeNums def listingNaturalNum(nMax): naturalNumbers = [] for i in range(nMax): naturalNumbers.append(i + 1) return naturalNumbers def converter(list): cartesianX = [] cartesianY = [] for i in range(len(list)): tempx = list[i] * np.cos(list[i]) tempy = list[i] * np.sin(list[i]) cartesianX.append(tempx) cartesianY.append(tempy) return cartesianX, cartesianY nMax = 250000 # Shows Satisfactory result for nMax>200000 naturalNum = listingNaturalNum(nMax) primeNum, nonPrimeNum = listingPrimeNums(nMax) cartesianPrimesX, cartesianPrimesY = converter(primeNum) cartesianNonPrimesX, cartesianNonPrimesY = converter(nonPrimeNum) cartesianNaturalX, cartesianNaturalY = converter(naturalNum) colors1 = np.linspace(10, 150, len(cartesianPrimesX)) # plt.scatter(cartesianNaturalX, cartesianNaturalY, marker='.', label="Natural") plt.scatter(cartesianPrimesX, cartesianPrimesY, marker='.', label='Prime', c=colors1, cmap='hsv') # plt.scatter(cartesianNonPrimesX, cartesianNonPrimesY, marker='.', label='Non Prime') plt.legend() plt.grid() plt.title("Total Num" + str(nMax)) plt.show()
import sys from sequences.sequence import * from sequences.sequence_list import * ################ ### Implements a simple sequence example taken from wikipedia ### States are Sunny and Rainy ### Observations are: Shop, Clean, Walk ################# class SimpleSequence: def __init__(self): y_dict = {'r' : 0, 's': 1} int_to_pos = ['r','s'] x_dict = {'w' : 0, 's' : 1, 'c' : 2, 't' : 3} int_to_word = ['w','s','c','t'] sl = Sequence_List(x_dict,int_to_word,y_dict,int_to_pos) sl2 = Sequence_List(x_dict,int_to_word,y_dict,int_to_pos) sl.add_sequence([0,0,1,2],[0,1,1,1]) sl.add_sequence([0,0,1,2],[0,0,0,1]) sl.add_sequence([0,1,1,2],[1,1,1,1]) sl2.add_sequence([0,0,1,2],[0,1,1,1]) sl2.add_sequence([2,0,3,0],[1,1,1,1]) self.x_dict = x_dict self.y_dict = y_dict self.int_to_word = int_to_word self.int_to_pos = int_to_pos self.train = sl self.dev = 0 self.test = sl2
def find_score(player_list): hearts = 0 diamonds = 0 clubs = 0 spades = 0 for card in player_list: if card.get_suit() == "Hearts": if card.get_value() == "Jack" or card.get_value() == "Queen" or card.get_value() == "King": hearts += 10 elif card.get_value() == "Ace": hearts += 11 else: hearts += card.get_value() if card.get_suit() == "Diamonds": if card.get_value() == "Jack" or card.get_value() == "Queen" or card.get_value() == "King": diamonds += 10 elif card.get_value() == "Ace": diamonds += 11 else: diamonds += card.get_value() if card.get_suit() == "Clubs": if card.get_value() == "Jack" or card.get_value() == "Queen" or card.get_value() == "King": clubs += 10 elif card.get_value() == "Ace": clubs += 11 else: clubs += card.get_value() if card.get_suit() == "Spades": if card.get_value() == "Jack" or card.get_value() == "Queen" or card.get_value() == "King": spades += 10 elif card.get_value() == "Ace": spades += 11 else: spades += card.get_value() totals = {hearts:"Hearts",diamonds:"Diamonds",clubs:"Clubs",spades:"Spades"} return "Hearts: {}, Diamonds: {}, Clubs: {}, Spades: {}".format(hearts,diamonds,clubs,spades)
import math T = [int(x) for x in raw_input().split()][0] def find_sum_of_digits(n): s = 0 while n: s += n % 10 n /= 10 return s while T > 0: T -= 1 N = [int(x) for x in raw_input().split()][0] sqrt_of_N = long(math.sqrt(N)) sqrt_of_half_N = long(math.sqrt(N / 2)) for x in xrange(sqrt_of_half_N, sqrt_of_N + 1): b = find_sum_of_digits(x) lhs = (x * (x + b)) if lhs == N: print x break else: print -1
first_line = [int(x) for x in raw_input().split()] repo = {} def count_minimum(strength): if repo.get(strength) is not None: return repo.get(strength) if strength == 1: return 0 if strength % 3 != 0 and strength % 2 != 0: count1 = count_minimum(strength - 1) + 1 count2 = None elif strength % 3 == 0 and strength % 2 == 0: count1 = count_minimum(strength / 3) + 1 count2 = count_minimum(strength / 2) + 1 elif strength % 3 != 0 and strength % 2 == 0: count1 = count_minimum(strength / 2) + 1 count2 = count_minimum(strength - 1) + 1 elif strength % 3 == 0 and strength % 2 != 0: count1 = count_minimum(strength / 3) + 1 count2 = count_minimum(strength - 1) + 1 if count2 is None: repo[strength] = count1 return count1 if count1 < count2: repo[strength] = count1 return count1 else: repo[strength] = count2 return count2 for i in range(first_line[0]): enemy_strength = [int(x) for x in raw_input().split()][0] print count_minimum(enemy_strength)
"""A collection of non-contextual bandits""" import numpy as np # basic bandit to test the functionality of agents class Bandit: """Class for a simple k-armed bandit without context dependence. It includes variable number of arms, initialization reward distribution for each arm (hidden from agent) and method to have arm pulled and return reward. The reward distribution is: Normal.""" def __init__(self, k): self.k = k self.means = np.random.normal( loc=0, scale=2, size=k ) # this is expectation value in this case for each level # just to make it explicit: self.expected_reward = self.means self.stdevs = [1] * k self.best_arm = np.argmax(self.means) self.best_reward = self.means[self.best_arm] def pull_lever(self, lever): return np.random.normal(loc=self.means[lever], scale=self.stdevs[lever])