text
stringlengths
37
1.41M
#Write a recursive function which calculates the factorial of a given number. # Use exception handling to raise an appropriate exception if the input parameter is not a # positive integer, but allow the user to enter floats as long as they are whole numbers. import math def factorial( n ): if n ==0: # base case return 1 else: returnNumber = n * factorial( n - 1 ) # recursive call # print(str(n) + '! = ' + str(returnNumber)) return returnNumber fact = factorial(5) print(fact)
battleship_guesses = { (3, 4): False, (2, 6): True, (2, 5): True, } surnames = {} # this is an empty dictionary surnames["John"] = "Smith" surnames["John"] = "Doe" print(surnames) # we overwrote the older surname marbles = {"red": 34, "green": 30, "brown": 31, "yellow": 29 } marbles["blue"] = 30 # this will work print(marbles)
temperature=float(input()) if temperature < 0: print("Below freezing") elif temperature < 10: print("Very cold") elif temperature < 20: print("Chilly") elif temperature < 30: print("Warm") elif temperature < 40: print("Hot") else: print("Too hot")
''' Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining. Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] Output: 4 Explanation: After the rain, water is trapped between the blocks. We have two small pounds 1 and 3 units trapped. The total volume of water trapped is 4. ''' import heapq class Solution: def trapRainWater(self, heightMap: List[List[int]]) -> int: # To ensure the calculation of the height of the water is correct, # a binary heap is needed to process cells from the lowest height, # and the stored values in the heap are representation of boundries. # In other words, the lowest possible level of water is recorded # as the boundries are shrinking/processed, therefore: # for every boundry, check if there's a cell lower than it, # if there is, then the volume of water at that cell MUST be # the current level of water - the height of that lower cell # to record visited cell, modify the cell to -1 if not heightMap or not heightMap[0]: return 0 n, m = len(heightMap), len(heightMap[0]) heap = [] # height, x, y for i in range(n): for j in range(m): if i == 0 or i == n - 1 or j == 0 or j == m - 1: heapq.heappush(heap, (heightMap[i][j], i, j)) heightMap[i][j] = -1 res, level = 0, 0 while heap: height, x, y = heapq.heappop(heap) level = max(height, level) for i, j in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]: if 0 <= i < n and 0 <= j < m and heightMap[i][j] != -1: heapq.heappush(heap, (heightMap[i][j], i, j)) if heightMap[i][j] < level: res += level - heightMap[i][j] heightMap[i][j] = -1 return res
#This is a guess the number game import random secretNumber=random.randint(1, 20) print('I am thinking of a number between 1 to 20.') for guessesTaken in range(1,7): print('Guess my number') guess=int(input()) if guess < secretNumber: print('The number guessed is lower than my number') elif guess > secretNumber: print('The number guessed is greater than my number') else: break #This the condition when guess matches! if guess == secretNumber: print ('Good Job you got my number in ' +str(guessesTaken) + ' guesses!') else: print ('Nope, The number I was thinking of was ' + str(secretNumber))
course = "Python Programming" print(course.upper()) print(course.lower()) print(course.title()) course = " Python Programming" print(course) print(course.strip()) print(course.find("Pro")) print(course.find("pro")) print(course.replace("P", "-")) print("Programming" in course) print("Programming" not in course)
def repeat_to_length(string_to_expand, length): return (string_to_expand * (int(length/len(string_to_expand))+1))[:length] def xor_crypt(text, key): expanded_key = repeat_to_length(key, len(text)) index = 0 encrypted_string = "" for char in text: original_char_ascii = ord(char) key_char_ascii = ord(expanded_key[index:index+1]) shifted_char = chr(original_char_ascii ^ key_char_ascii) encrypted_string += shifted_char index = index + 1 return encrypted_string def xor_encrypt(text, key): return xor_crypt(text, key) def xor_decrypt(secret_text, key): return xor_crypt(secret_text, key) print(xor_encrypt("01234", "asde")) # QBVVU print(xor_decrypt("QBVVU", "asde")) # 01234
def HammingDistance(string1, string2): if len(string1) != len(string2): raise Exception("Lengths of strings are not equal") string1_hex_value = bytearray.fromhex(string1.encode("utf-8").hex()) string2_hex_value = bytearray.fromhex(string2.encode("utf-8").hex()) xor_result = bytes(a ^ b for (a, b) in zip(string1_hex_value, string2_hex_value)) distance = 0 for byte in xor_result: for bit in bin(byte)[2:]: if bit == '1': distance += 1 return distance distance = HammingDistance("this is a test", "wokka wokka!!!")
#update memo:时间需要自动更新到今天的日期,并且显示出来 #获取的数据是否是复权数据 import tushare as ts from decimal import Decimal import time import sys sys.path.append('/home/alzer/PycharmProjects/THShelper/utils') from myTushare import getTuShareService #input validation def exCompletion(ex): if(len(ex) != 6 ): print('ex code %s error,not recognised.' %ex) return False #begin with #000 shenzhen 主板 #002 shenzhen 中小板 #600 shanghai 主板 #3 shenzhen 创业板 #shenzhen if ( ex.startswith('000') or ex.startswith('002') or ex.startswith('3') or ex.startswith('00')): exComplete = '%s.SZ' %ex return exComplete elif (ex.startswith('600') or ex.startswith('601') or ex.startswith('603')): exComplete = '%s.SH' %ex return exComplete else: print('The ex code %s not recognised.' %ex) return False def scheme1(p): price = Decimal(p) factor = 99.00 while factor >= 90.00: buyPrice = price * Decimal(factor/100) print('factor=%s%%,buyPrice=%f' %(factor,buyPrice)) factor -= 1 def today(): today=time.strftime('%Y%m%d') return today #THS团队的冒险指数,如果<1表示谨慎,如果大于1表示想追涨 def calcRish(closePrice,expectPrice): # print('t1=%s' %type(closePrice)) # print('t2=%s' %type(expectPrice)) risk = Decimal(expectPrice)/Decimal(closePrice) return risk print('Please input the exchanges , seperate by a space,end with an enter:') #login on to the tushare # ts.set_token('c43dab7d00de3db2a87947459b13da12bada68f6bd78019102ffa04e') # IApi = ts.pro_api() IApi = getTuShareService() ExchangeList = input().split() iStockCount = len(ExchangeList) if(iStockCount%3 != 0): print('input error.') sys.exit(1) #get close price of each stock. for j in range(0,iStockCount,3): # print('j=%d' %j) # i+=1 # ex=ExchangeList[j] # low=ExchangeList[j+1] # high=ExchangeList[j+2] # print('test=%s,low=%s,high=%s' %(ex,low,high)) exComplete = exCompletion(ExchangeList[j]) if(exComplete != False and exComplete != None): print('The %d stock info,code=%s:' %(j/3+1,exComplete)) df = IApi.daily(ts_code=exComplete, start_date='20180830', end_date='20180830') # df = IApi.daily(ts_code=exComplete, start_date=today(), end_date=today()) print(df) closePrice = df.iat[0,5] # print(closePrice) scheme1(closePrice) lowRish = (1 - calcRish(closePrice,ExchangeList[j+1])) * 100 highRish =(1 - calcRish(closePrice,ExchangeList[j+2])) * 100 if(lowRish >= 0): lowRishStr = '-%.5s' %lowRish else: lowRishStr = '%.5s' %-lowRish if(highRish >= 0): highRishStr = '-%.5s' %highRish else: highRishStr ='%.5s' %-highRish print('Risk=[%s,%s]' %(lowRishStr,highRishStr)) if(lowRish *2 < 5): pioneerPrice = (100 - Decimal(lowRish)*2)/100 * Decimal(closePrice) print('pioneerPrice=%s' %pioneerPrice) else: print('No pioneerPrice') if(j < iStockCount): print('------------------------------------------')
''' #taking input x = input('Enter name:') print ('Name',x) ''' #import module import statistics example_list = [5,2,5,6,1,2,6,7,2,6,3,5,5] #list print(statistics.mean(example_list)) from statistics import mean # so here, we've imported the mean function only. print(mean(example_list)) # and again we can do as from statistics import mean as m print(m(example_list)) from statistics import mean, median # here we imported 2 functions. print(median(example_list)) from statistics import mean as m, median as d print(m(example_list)) print(d(example_list)) from statistics import * print(mean(example_list))
# Written by Austin Staton # Used to demonstrate the use of OOP in Python. class University: def __init__(self, name, location): self._name = name self._location = location def getName(self): return self._name def getLocation(self): return self._location def getUniversity(self): return self.getName() + "; " + self.getLocation() class College(University): def __init__ (self, name, location, collegeName): University.__init__(self, name, location) self._collegeName = collegeName def getCollegeName(self): return self._collegeName def getCollege(self): return self.getUniversity() + "; " + self.getCollegeName() def main(): # Create 'University' and 'College' Object UofSC = University("Univeristy of South Carolina", "Columbia, SC") EngrComp = College("UofSC", "COLA, SC", "College of Engineering and Computing") #print (UofSC.getName() + "; " + UofSC.getLocation()) #print (EngrComp.getCollege()) print (UofSC.getUniversity()) print (EngrComp.getCollege()) main()
'''This program works like the Engima machine. It utilized the Ceaser encryption method along with a few advanced tweaks that make sure that the encrypted message is not easy to crack To us this: 1) To encrypt a message: >python3 encrypter.py -e then enter an integer key followed by a message 2) To decrypt a message: >python3 encrypter.py -d then enter the integer key followed by the encrypted message ''' import argparse simplealphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ" complexalphabet="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,><-_=+)(&*^%$#@!`/\ 1234567890" alphabet=complexalphabet length=len(alphabet)-1 def get_index(a): i=0 while(i<(length+1)): x=alphabet[i] if(x==a): return(i) break else: i=i+1 def convertmessage(k,m,f): mess=str(m) result="" l=1 for j in mess: oldindex=get_index(j) newindex=(oldindex + (f*l*funct(k)))%length #modulo ensures index value remains between 0 and 36. the 'l' increment ensures that no character has the same encoded value twice. result=result+alphabet[newindex] l=l+1 return(result) def funct(h): #this function generates a hashed key n=int((h*h)/(3.14)) return(n) p=argparse.ArgumentParser() g=p.add_mutually_exclusive_group() g.add_argument("-e","--encrypt",help="Add the -e to encrypt a message",action="store_true") g.add_argument("-d","--decrypt",help="Add the -d to decrypt a message",action="store_true") argopt=p.parse_args() if(argopt.encrypt): key=int(input("Enter key: ")) message=str(input("Enter message to be encrypted: ")) print(convertmessage(key,message,(1))) elif(argopt.decrypt): key=int(input("Enter key: ")) message=str(input("Enter message to be encrypted: ")) print(convertmessage(key,message,(-1)))
#!/usr/bin/env python # -*- coding: utf-8 -*- """unit conversions""" import numbers #Define exceptions class ConversionNotPossible(Exception): pass def convert(fromUnit,toUnit,value): if not isinstance(value, numbers.Number) or isinstance(value, bool): raise ConversionNotPossible, "non number entered" if (fromUnit == toUnit): raise ConversionNotPossible, "No conversions" if ((fromUnit == 'celsius' or fromUnit == 'kelvin' or fromUnit == 'fahrenheit') and (toUnit == 'meter' or toUnit == 'yard' or toUnit == 'mile')): raise ConversionNotPossible, "Mismatch units" if ((fromUnit == 'meter' or fromUnit == 'yard' or fromUnit == 'mile') and (toUnit == 'celsius' or toUnit == 'kelvin' or toUnit == 'fahrenheit')): raise ConversionNotPossible, "Mismatch units" if (fromUnit == 'celsius'): if (toUnit == 'kelvin'): return value + 273.15 elif (toUnit == 'fahrenheit'): return value * 1.8 + 32 elif (fromUnit == 'kelvin'): if (toUnit == 'celsius'): return value - 273.15 elif (toUnit == 'fahrenheit'): return value * 1.8 - 459.67 elif (fromUnit == 'fahrenheit'): if (toUnit == 'celsius'): return (value - 32) * 0.555555555555556 elif (toUnit == 'kelvin'): return (value + 459.67) * 0.555555555555556 elif (fromUnit == 'meter'): if (toUnit == 'yard'): return value * 1.093613 elif (toUnit == 'mile'): return value / 1609.344 elif (fromUnit == 'yard'): if (toUnit == 'meter'): return value / 1.0936 elif (toUnit == 'mile'): return value * 0.00056818 elif (fromUnit == 'mile'): if (toUnit == 'yard'): return value * 1760.0 elif (toUnit == 'meter'): return value * 1609.344
# -*- coding: utf-8 -*- """ Created on Fri Sep 22 07:10:09 2017 @author: shrey """ import numpy as np import matplotlib.pyplot as plt import pandas as pd from pca import do_pca #read the data data=pd.read_csv("/home/shrey/Desktop/ml/dataset_1.csv") #fetch the three variables x=data['x'] y=data['y'] z=data['z'] #convert them into numpy arrays x_var=np.array(x) y_var=np.array(y) z_var=np.array(z) #Calculate Variance variance_x=np.var(x) variance_y=np.var(y) variance_z=np.var(z) #Calculate the covariance cov_x_y=np.cov(x,y) cov_y_z=np.cov(y,z) # Now to calcualte the new transformed matrix y and principal component matriz dataset=np.array(data) n=2 #number of principal components I need y,m=do_pca(dataset,n) # do_pca is my function I made in my module print(y) #y is the new transformed matrix print(m) #m is the principal component matrix having 2 principal components
import pandas as pd import sqlite3 import matplotlib.pyplot as plt import folium def q1(qq1,connection): start_year= input('Enter start year(YYYY) ') end_year = input('Enter end year(YYYY) ') crime_type = input('Enter crime type ') df = pd.read_sql('select month1,count(Incidents_Count) from (select distinct crime_incidents.Month as month1 from crime_incidents where typeof(month1) = \"integer\") left outer join (select * , crime_incidents.Month as month2 from crime_incidents where crime_incidents.Year >= ' + str(start_year) + ' AND crime_incidents.Year <= ' + str(end_year) + ' AND crime_incidents.Crime_Type = \"' + str(crime_type) + '\" ) on month1 = month2 group by month1', connection) plot = df.plot.bar(x="month1") plt.plot() plt.savefig('Q1-'+str(qq1)+'.png') def q2(qq2,conn): m = folium.Map(location=[53.5444,-113.323], zoom_start=11)#connect map c=conn.cursor()#create cursor a=input('Enter number of locations: ') #to select top neighbourhood c.execute('select (population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE) as number,population.Neighbourhood_Name,coordinates.Latitude,coordinates.Longitude from population,coordinates where population.Neighbourhood_Name=coordinates.Neighbourhood_Name and number <> 0 and (coordinates.Latitude<>0 or coordinates.Longitude<>0) order by population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE desc limit :a;',{"a":a}) rows=c.fetchall()#get result #draw circles for i in range(0,len(rows)-1): folium.Circle( location=[rows[i][2], rows[i][3]], # location popup=str(rows[i][1])+"<br>"+str(rows[i][0]) , # popup text radius= 0.1*rows[i][0], # size of radius in meter color= 'crimson', # color of the radius fill= True, # whether to fill the map fill_color= 'crimson' # color to fill with ).add_to(m) #to select last neighbourhood c.execute('select (population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE) as number,population.Neighbourhood_Name,coordinates.Latitude,coordinates.Longitude from population ,coordinates where population.Neighbourhood_Name=coordinates.Neighbourhood_Name and number <> 0 and (coordinates.Latitude<>0 or coordinates.Longitude<>0) order by population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE asc limit :a;',{"a":a}) rows2 = c.fetchall() if len(rows) !=0 and len(rows2)!=0: for i in range(0,len(rows2)-1): folium.Circle( location=[rows2[i][2], rows2[i][3]], # location popup=str(rows2[i][1])+"<br>"+str(rows2[i][0]) , # popup text radius= 0.1*rows2[i][0], # size of radius in meter color= 'crimson', # color of the radius fill= True, # whether to fill the map fill_color= 'crimson' # color to fill with ).add_to(m) lasttop = rows[len(rows)-1][0] lastmin = rows2[len(rows2)-1][0] #deal with tie cases c.execute('select (population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE) as number,population.Neighbourhood_Name,coordinates.Latitude,coordinates.Longitude from population ,coordinates where population.Neighbourhood_Name=coordinates.Neighbourhood_Name and number <> 0 and (coordinates.Latitude<>0 or coordinates.Longitude<>0) and (number=:a or number=:b);',{"a":int(lasttop),"b":int(lastmin)}) rows3=c.fetchall() s=len(rows3) for i in range(len(rows3)): folium.Circle( location=[rows3[i][2], rows3[i][3]], # location popup=str(rows3[i][1])+"<br>"+str(rows3[i][0]) , # popup text radius= 0.1*rows3[i][0], # size of radius in meter color= 'crimson', # color of the radius fill= True, # whether to fill the map fill_color= 'crimson' # color to fill with ).add_to(m) m.save('Q2-'+str(qq2)+'.html') conn.commit() def q3(qq3,conn): m = folium.Map(location=[53.5444,-113.323], zoom_start=11)#connect map c=conn.cursor()#create cursor #get input start_year= input('Enter start year(YYYY) ') end_year = input('Enter end year(YYYY) ') crime_type = input('Enter crime type ') number=input('Enter number of neighborhoods ') #to select top crime count neighbourhood c.execute("select crime_incidents.Neighbourhood_Name, SUM(crime_incidents.Incidents_Count) as number ,coordinates.Latitude,coordinates.Longitude from crime_incidents,coordinates where crime_incidents.Year >=:a AND crime_incidents. Year <= :b AND crime_incidents.Crime_Type = :c and crime_incidents.Neighbourhood_Name=coordinates.Neighbourhood_Name and(coordinates.Latitude<>0 or coordinates.Longitude<>0) group by crime_incidents.Neighbourhood_Name order by number DESC LIMIT :d;", {"a":int(start_year),"b":int(end_year),"c":crime_type,"d":number}) rows=c.fetchall() for i in range(0,len(rows)-1): folium.Circle( location=[rows[i][2], rows[i][3]], # location popup=str(rows[i][0])+"<br>"+str(rows[i][1]) , # popup text radius= 2*rows[i][1], # size of radius in meter color= 'crimson', # color of the radius fill= True, # whether to fill the map fill_color= 'crimson' # color to fill with ).add_to(m) if len(rows)!=0: lasttop=int(rows[len(rows)-1][1]) #deal with tie cases c.execute("select Neighbourhood_Name,number ,Latitude,Longitude from (select crime_incidents.Neighbourhood_Name, SUM(crime_incidents.Incidents_Count) as number ,coordinates.Latitude,coordinates.Longitude from crime_incidents,coordinates where crime_incidents.Year >=:a AND crime_incidents. Year <= :b AND crime_incidents.Crime_Type = :c and crime_incidents.Neighbourhood_Name=coordinates.Neighbourhood_Name and (coordinates.Latitude<>0 or coordinates.Longitude<>0) group by crime_incidents.Neighbourhood_Name) where number=:d;", {"a":int(start_year),"b":int(end_year),"c":crime_type,"d":lasttop}) rows2=rows=c.fetchall() for i in range(len(rows2)): folium.Circle( location=[rows2[i][2], rows2[i][3]], # location popup=str(rows2[i][0])+"<br>"+str(rows2[i][1]) , # popup text radius= 2*rows2[i][1], # size of radius in meter color= 'crimson', # color of the radius fill= True, # whether to fill the map fill_color= 'crimson' # color to fill with ).add_to(m) m.save('Q3-'+str(qq3)+'.html') conn.commit() def q4(qq4,conn): m = folium.Map(location=[53.5444,-113.323], zoom_start=11)#connect map c=conn.cursor()#create cursor start_year= input('Enter start year(YYYY) ') end_year = input('Enter end year(YYYY) ') neighborhoods = input('Enter numebr of neighborhoods ') #to select the top radio neighbourhood c.execute('select population.Neighbourhood_Name,max(crime_incidents.Incidents_Count),crime_incidents.Crime_Type,coordinates.Latitude,coordinates.Longitude,cast(sum(crime_incidents.Incidents_Count)as float)/(population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE)as number from population,crime_incidents,coordinates where crime_incidents.Year >=:a AND crime_incidents.Year <= :b and population.Neighbourhood_Name=crime_incidents.Neighbourhood_Name and (population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE) <>0 and (coordinates.Latitude<>0 or coordinates.Longitude<>0)and population.Neighbourhood_Name=coordinates.Neighbourhood_Name group by population.Neighbourhood_Name order by number desc limit :c',{"a":int(start_year),"b":int(end_year),"c":int(neighborhoods)}) rows=c.fetchall() if len(rows)!=0: lasttop=rows[int(neighborhoods)-1][5] #to select the most frenquntly crime type for i in range(len(rows)): s='' c.execute('select Crime_Type from (select crime_incidents.Crime_Type ,sum(crime_incidents.Incidents_Count)as number from crime_incidents where crime_incidents.Year >=:a AND crime_incidents.Year <=:b and crime_incidents.Neighbourhood_Name=:d group by crime_incidents.Crime_Type) where number = (select max(number) from (select crime_incidents.Crime_Type ,sum(crime_incidents.Incidents_Count)as number from crime_incidents where crime_incidents.Year >=:a AND crime_incidents.Year <=:b and crime_incidents.Neighbourhood_Name=:d group by crime_incidents.Crime_Type))',{"a":int(start_year),"b":int(end_year),"d":rows[i][0]}) rows2=c.fetchall() for j in range(len(rows2)): s=s+'<br>'+rows2[j][0] folium.Circle( location=[rows[i][3], rows[i][4]], # location popup=str(rows[i][0])+s+"<br>"+str(rows[i][5]) , # popup text radius= 1000*rows[i][5], # size of radius in meter color= 'crimson', # color of the radius fill= True, # whether to fill the map fill_color= 'crimson' # color to fill with ).add_to(m) #to deal with tie cases c.execute('select Neighbourhood_Name,Latitude,Longitude,number from(select population.Neighbourhood_Name,coordinates.Latitude,coordinates.Longitude,cast(sum(crime_incidents.Incidents_Count)as float)/(population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE)as number from population,crime_incidents,coordinates where crime_incidents.Year >=:a AND crime_incidents.Year <= :b and population.Neighbourhood_Name=crime_incidents.Neighbourhood_Name and population.Neighbourhood_Number<>0 and (coordinates.Latitude<>0 or coordinates.Longitude<>0)and population.Neighbourhood_Name=coordinates.Neighbourhood_Name group by population.Neighbourhood_Name) where number =:c',{"a":int(start_year),"b":int(end_year),"c":int(lasttop)}) rows3=c.fetchall() # to find the most frenquntly crime type in tie cases for i in range(len(rows3)): s='' c.execute('select Crime_Type from (select crime_incidents.Crime_Type ,sum(crime_incidents.Incidents_Count)as number from crime_incidents where crime_incidents.Year >=:a AND crime_incidents.Year <=:b and crime_incidents.Neighbourhood_Name=:d group by crime_incidents.Crime_Type) where number = (select max(number) from (select crime_incidents.Crime_Type ,sum(crime_incidents.Incidents_Count)as number from crime_incidents where crime_incidents.Year >=:a AND crime_incidents.Year <=:b and crime_incidents.Neighbourhood_Name=:d group by crime_incidents.Crime_Type))',{"a":int(start_year),"b":int(end_year),"d":rows[i][0]}) rows2=c.fetchall() for j in range(len(rows2)): s=s+'<br>'+rows2[j][0] folium.Circle( location=[rows3[i][1], rows3[i][2]], # location popup=str(rows[i][0])+s+"<br>"+str(rows[i][3]) , # popup text radius= 1000*rows[i][3], # size of radius in meter color= 'crimson', # color of the radius fill= True, # whether to fill the map fill_color= 'crimson' # color to fill with ).add_to(m) m.save('Q4-'+str(qq4)+'.html') conn.commit() def main(): qq1=0 qq2=0 qq3=0 qq4=0 command = '' connection = sqlite3.connect('./' + input('Enter database name: ')) while command != 'E': command = input('1:Q1\n2:Q2\n3:Q3\n4:Q4\nE:Exit\n') if command=='1': qq1=qq1+1 q1(qq1,connection) if command=='2': qq2=qq2+1 q2(qq2,connection) if command=='3': qq3=qq3+1 q3(qq3,connection) if command=='4': qq4=qq4+1 q4(qq4,connection) connection.close() if __name__ == "__main__": main()
words = "It's thanksgiving day. It's my birthday, too!" print words.find("day") print words.replace("day", "month") myList = [2,54,-2,7,12,98] print max(myList) print min(myList) x = ["hello",2,54,-2,0.5,7,12,98,"world"] print x[0::len(x)-1] #prints the first and last item :: skips numbers in between print x[0], x[-1] #prints first and last item of list x = [19,2,54,-2,7,12,98,32,10,-3,6] x.sort() #sorts list x smallest to biggest y = x[:len(x)/2] #assigns first half of list split by total length of list z = x[len(x)/2:] #assigns second half of list split by total length of list newList = y, z #assign y and z to a variable so it can be printed at the same time print newList
def is_constant(const): '''returns True if const is constant, False if it const is folder const is a dict with the following keys: {'id': 'math', 'name': 'Mathematics', 'parent_id': '', \ 'value': '', 'unit': '', 'unit_system': ''} ''' if const == None: return None return const['value'] != '' def is_topmost_node(const): '''Returns True if const in the topmost level folder, False otherwise. const is a dict with the following keys: {'id': 'math', 'name': 'Mathematics', 'parent_id': '', \ 'value': '', 'unit': '', 'unit_system': ''} ''' if const == None: return None return const['parent_id'] == '' def get_menuitems_id(menu_items, item_name): '''return id of `item_name` string if it is present in menu_items list''' names = [item['name'].lower() for item in menu_items] ids = [item['id'] for item in menu_items] try: idx = names.index(item_name.lower()) except: return None return ids[idx] def units_present(const): if (const['unit'] != '') & (const['unit_system'] != ''): return True return False
""" Simple prime number practice program. Solution for: http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html """ from InputHandler import inputintgen # strong probable prime def is_sprp(n, b=2): """Returns True if n is prime. Code borrowed from: https://codegolf.stackexchange.com/a/10702 Implementation of Baillie–PSW: https://en.wikipedia.org/wiki/Baillie%E2%80%93PSW_primality_test This one is a bit uglier, but is vastly faster Tested: Almost immediate response up to 200 digits """ d = n-1 s = 0 while d&1 == 0: s += 1 d >>= 1 x = pow(b, d, n) if x == 1 or x == n-1: return True for r in range(1, s): x = (x * x)%n if x == 1: return False elif x == n-1: return True return False def isprime(n): """Returns True if n is prime. Code borrowed from: https://stackoverflow.com/a/1801446 Nice clean implementation, why reinvent the wheel Tested: acceptable interactive performance up to about 16 decimal digits ...on a fairly slow virtual machine Note: pylint doesn't like these short variable names, ... but for this simple module I think they are fine. """ if n == 2: return True if n == 3: return True if n % 2 == 0: return False if n % 3 == 0: return False i = 5 w = 2 while i * i <= n: if n % i == 0: return False i += w w = 6 - w return True def main(): """ Run the check prime program. """ for test in inputintgen("Choose a number to see if it is prime"): if is_sprp(int(test)): print(test, "is prime!") else: print(test, "is not prime.") # user exited program print("Goodbye!\n") main()
# -*- coding:UTF-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') import random import time from fractions import Fraction #getsymbol函数,返回一个运算符号 def getoperators(): operatorslist=('+','-','×','÷','+','-') operators=random.choice(operatorslist) if operators=='×': length=2 elif operators=='÷': length=2 else: length=1 return operators,length #calculate函数,用于计算两个值的四则运算 def calculate(n1,n2,op): if op=='+': ans=n1+n2 elif op=='-': ans=n1-n2 elif op=='×': ans=n1*n2 else: if n2==0: print '分母不能为零!' else: ans=n1/n2 return ans #getnumber函数,返回一个数,表示整数或者一个真分数,有两种形式,字符串和浮点数 def getoperands(range): operandstype=random.randint(1,2) degree=0 if operandstype==1: operands=random.randint(1,range) operandsvalue=Fraction(operands,1) operands=str(operands) degree=1 #print operands else: operands1=random.randint(1,range) operands2=random.randint(1,range) degree=1.5 if operands1<operands2: operands1,operands2=operands2,operands1 if operands1==operands2: operandsvalue=Fraction(1,2) operands='1/2' else: operandsvalue=Fraction(operands2,operands1) operands=str(Fraction(operands2,operands1)) return operands,operandsvalue,degree #getquestion函数,以字符串的形式返回一个题目 def getquestion(ran):#range是操作数的取值范围 symbolnumber=random.randint(1,5) question='' questionstack=[] ans=0 length_ques=0 for i in range(1,symbolnumber+1): (op,va,de)=getoperands(ran) operands=op value=va (operators,length)=getoperators() question=question+operands+operators questionstack.append(value) questionstack.append(operators) length_ques=length_ques+length+de (op,va,de)=getoperands(ran) operands=op value=va question=question+operands questionstack.append(value) length_ques=length_ques+de #print question #print questionstack condition=0 while len(questionstack)>1: for i in range(0,len(questionstack)): if questionstack[i]=='×': questionstack[i-1]=questionstack[i-1]*questionstack[i+1] del questionstack[i] del questionstack[i] break elif questionstack[i]=='÷': questionstack[i-1]=questionstack[i-1]/questionstack[i+1] del questionstack[i] del questionstack[i] break else: condition=1 if condition==1: if len(questionstack)>1: questionstack[0]=calculate(questionstack[0],questionstack[2],questionstack[1]) del questionstack[1] del questionstack[1] #print question #print questionstack else: ans=questionstack[0] return question,ans,length_ques def getquestionlist(num,ran): questionlist = [] # 题目存在一个列表中 anslist = [] # 答案存在一个列表中 lengthlist = [] # 权重存在一个列表中 scorelist = [] # 分数存在一个列表中 myanslist = [] # 回答答案存在一个列表中 totalscore = 0 #questionfile = file('questionlist.txt', 'w') # 根据输入的题目个数生成题目清单,每一个新生成的题会与现有题进行比较,重复不则重新生成 # 将生成的题目写入文件中,便于查看与打印 while len(questionlist) < num: (question, ans, length) = getlabelquestion('随机','随机',ran) cond = 0 for element in questionlist: if element == question: cond = 1 if cond == 0: questionlist.append(question) anslist.append(ans) myanslist.append("") lengthlist.append(length) totalscore = totalscore + length #questionfile.write(question + '\n') #questionfile.close() #print '题目已经生成完毕!' # 根据权重分配分值 for i in range(0, len(lengthlist)): scorelist.append(round(lengthlist[i] * 100 / totalscore)) return questionlist,anslist,scorelist,myanslist def transtime(sec): hours=sec/3600 tem1=sec-(hours*3600) minutes=tem1/60 tem2=tem1-minutes*60 seconds=tem2 return hours,minutes,seconds def deletei(txtname,i): with open(txtname, 'r') as old_file: with open(txtname, 'r+') as new_file: current_line = 0 # 定位到需要删除的行 while current_line < (i - 1): old_file.readline() current_line += 1 # 当前光标在被删除行的行首,记录该位置 seek_point = old_file.tell() # 设置光标位置 new_file.seek(seek_point, 0) # 读需要删除的行,光标移到下一行行首 old_file.readline() # 被删除行的下一行读给 next_line next_line = old_file.readline() # 连续覆盖剩余行,后面所有行上移一行 while next_line: new_file.write(next_line) next_line = old_file.readline() # 写完最后一行后截断文件,因为删除操作,文件整体少了一行,原文件最后一行需要去掉 new_file.truncate() def vfraction(str): str1='1' str2='1' con=0 for i in range(0,len(str)-1): if str[i]=='/': str1=str[0:i] str2=str[i+1:len(str)] con=1 if con==0: str1=str return Fraction(int(str1),int(str2)) def replacestr(ques,ques_1): question = ques.encode('utf8') # print question queslist = [] requeslist = '' requesstack = [] k = 0 for i in range(0, len(question) - 1): # print question[i:i+2] if question[i] == "+": # 前处理 queslist.append(question[k:i]) queslist.append(question[i]) k = i + 1 elif question[i] == '-': queslist.append(question[k:i]) queslist.append(question[i]) k = i + 1 elif question[i:i + 2] == '×': queslist.append(question[k:i]) queslist.append(question[i:i + 2]) k = i + 2 elif question[i:i + 2] == '÷': queslist.append(question[k:i]) queslist.append(question[i:i + 2]) k = i + 2 queslist.append(question[k:len(question)]) # print queslist # print len(queslist) for i in range(0, len(queslist) - 1): # print i if queslist[i] == '+' or queslist[i] == '-' or queslist[i] == '×' or queslist[i] == '÷': if queslist[i-1]==ques_1: requeslist = requeslist + queslist[i - 1] + queslist[i] requesstack.append(vfraction(queslist[i - 1])) requesstack.append(queslist[i]) continue else: deal = random.randint(1, 10) if deal < 2: # 删 continue # del queslist[i - 1] # del queslist[i] elif deal > 1 and deal < 7: # 增 # dd = random.randint(-1 * int(queslist[i - 1])+1, int(queslist[i - 1])) add = random.randint(-1 * int(vfraction(queslist[i - 1])), int(vfraction(queslist[i - 1]))) queslist[i - 1] = str(vfraction(queslist[i - 1]) + add) requeslist = requeslist + queslist[i - 1] + queslist[i] requesstack.append(vfraction(queslist[i - 1])) requesstack.append(queslist[i]) else: o, w = getoperators() queslist[i] = o requeslist = requeslist + queslist[i - 1] + queslist[i] requesstack.append(vfraction(queslist[i - 1])) requesstack.append(queslist[i]) requeslist = requeslist + queslist[len(queslist) - 1] requesstack.append(vfraction(queslist[len(queslist) - 1])) # for i in range(0,len(requesstack)-1): # if requesstack[i]=='÷': # frac=Fraction(requesstack[i-1],requesstack[i+1]) # requesstack[i-1]=frac.numerator # requesstack[i+1]=frac.denominator condition = 0 while len(requesstack) > 1: for i in range(0, len(requesstack)): if requesstack[i] == '×': requesstack[i - 1] = requesstack[i - 1] * requesstack[i + 1] del requesstack[i] del requesstack[i] break elif requesstack[i:i] == '÷': requesstack[i - 1] = requesstack[i - 1] / requesstack[i + 1] del requesstack[i] del requesstack[i] break else: condition = 1 if condition == 1: if len(requesstack) > 1: requesstack[0] = calculate(requesstack[0], requesstack[2], requesstack[1]) del requesstack[1] del requesstack[1] # print question # print questionstack else: ans = requesstack[0] return requeslist, ans def calcustr(ques): question = ques.encode('utf8') # print question queslist = [] requeslist = '' requesstack = [] k = 0 for i in range(0, len(question) - 1): # print question[i:i+2] if question[i] == "+": # 前处理 queslist.append(question[k:i]) queslist.append(question[i]) k = i + 1 elif question[i] == '-': queslist.append(question[k:i]) queslist.append(question[i]) k = i + 1 elif question[i:i + 2] == '×': queslist.append(question[k:i]) queslist.append(question[i:i + 2]) k = i + 2 elif question[i:i + 2] == '÷': queslist.append(question[k:i]) queslist.append(question[i:i + 2]) k = i + 2 queslist.append(question[k:len(question)]) for i in range(0, len(queslist) - 1): # print i if queslist[i] == '+' or queslist[i] == '-' or queslist[i] == '×' or queslist[i] == '÷': queslist[i-1]=vfraction(queslist[i-1]) queslist[len(queslist)-1]=vfraction(queslist[len(queslist) - 1]) condition = 0 while len(requesstack) > 1: for i in range(0, len(requesstack)): if requesstack[i] == '×': requesstack[i - 1] = requesstack[i - 1] * requesstack[i + 1] del requesstack[i] del requesstack[i] break elif requesstack[i:i] == '÷': requesstack[i - 1] = requesstack[i - 1] / requesstack[i + 1] del requesstack[i] del requesstack[i] break else: condition = 1 if condition == 1: if len(requesstack) > 1: requesstack[0] = calculate(requesstack[0], requesstack[2], requesstack[1]) del requesstack[1] del requesstack[1] # print question # print questionstack else: ans = requesstack[0] return ans def replaceques(ques): con=0 if '(' in ques: con=1 if con==0: requeslist,ans=replacestr(ques,'') elif con==1: k1=ques.find('(') k2=ques.find(')') quesin=ques[k1+1:k2] questem,anstem=replacestr(quesin,' ') if '-' not in str(anstem): quesin = '(' + quesin + ')' ques = ques.replace(quesin, str(anstem)) requeslist, ans = replacestr(ques, str(anstem)) questem = '(' + questem + ')' requeslist = requeslist.replace(str(anstem), questem) else: requeslist=questem ans=anstem return requeslist,ans #(9×4/9×2/7-6-6×1/2)+2/5 #a='(3/5+2/3×6×2/9÷9-8-1/2)×8' #list,ans=replaceques(a) #print list #print ans #for i in range(0,len(a)): #print a[i] #b=a[0:7] #c=a[6:11] #print b #print c def getoperatorslist(st): if st=="随机": list=['+','-','×','÷','+','-'] elif st=="无乘": list = ['+', '-', '÷', '+', '-'] elif st=="无除": list = ['+', '-', '×', '+', '-'] elif st=="无加": list = ['×', '-', '÷', '-'] elif st=="无减": list = ['+', '×', '÷', '+'] elif st=="仅乘除": list = ['×', '÷'] elif st=="仅加减": list = ['+', '-'] elif st=="连乘": list = ['×'] elif st=="连除": list = ['÷'] elif st=="连加": list = ['+'] elif st=="连减": list = ['-'] return list def getlabeloperators(st): operatorslist=getoperatorslist((st)) operators = random.choice(operatorslist) if operators == '×': length = 2 elif operators == '÷': length = 2 else: length = 1 return operators, length def getlabeloperands(st,range): if st=="随机": operandstype = random.randint(1, 2) degree = 0 if operandstype == 1: operands = random.randint(1, range) operandsvalue = Fraction(operands, 1) operands = str(operands) degree = 1 # print operands else: operands1 = random.randint(1, range) operands2 = random.randint(1, range) degree = 1.5 if operands1 < operands2: operands1, operands2 = operands2, operands1 if operands1 == operands2: operandsvalue = Fraction(1, 2) operands = '1/2' else: operandsvalue = Fraction(operands2, operands1) operands = str(Fraction(operands2, operands1)) elif st=="整数": operands = random.randint(1, range) operandsvalue = Fraction(operands, 1) operands = str(operands) degree = 1 elif st=="真分数": operands1 = random.randint(1, range) operands2 = random.randint(1, range) degree = 1.5 if operands1 < operands2: operands1, operands2 = operands2, operands1 if operands1 == operands2: operandsvalue = Fraction(1, 2) operands = '1/2' else: operandsvalue = Fraction(operands2, operands1) operands = str(Fraction(operands2, operands1)) return operands, operandsvalue, degree def getlabelquestionbyn(opestr,numstr,ran,n): symbolnumber = n question = '' questionstack = [] ans = 0 length_ques = 0 for i in range(1, symbolnumber + 1): (op, va, de) = getlabeloperands(numstr, ran) operands = op value = va (operators, length) = getlabeloperators(opestr) question = question + operands + operators questionstack.append(value) questionstack.append(operators) length_ques = length_ques + length + de (op, va, de) = getlabeloperands(numstr, ran) operands = op value = va question = question + operands questionstack.append(value) length_ques = length_ques + de # print question # print questionstack condition = 0 while len(questionstack) > 1: for i in range(0, len(questionstack)): if questionstack[i] == '×': questionstack[i - 1] = questionstack[i - 1] * questionstack[i + 1] del questionstack[i] del questionstack[i] break elif questionstack[i] == '÷': questionstack[i - 1] = questionstack[i - 1] / questionstack[i + 1] del questionstack[i] del questionstack[i] break else: condition = 1 if condition == 1: if len(questionstack) > 1: questionstack[0] = calculate(questionstack[0], questionstack[2], questionstack[1]) del questionstack[1] del questionstack[1] # print question # print questionstack else: ans = questionstack[0] return question, ans, length_ques def getlabelquestion(opestr,numstr,ran): questiontype=random.randint(1,6) if questiontype<4: symbolnumber = random.randint(1, 5) question = '' questionstack = [] ans = 0 length_ques = 0 for i in range(1, symbolnumber + 1): (op, va, de) = getlabeloperands(numstr, ran) operands = op value = va (operators, length) = getlabeloperators(opestr) question = question + operands + operators questionstack.append(value) questionstack.append(operators) length_ques = length_ques + length + de (op, va, de) = getlabeloperands(numstr, ran) operands = op value = va question = question + operands questionstack.append(value) length_ques = length_ques + de # print question # print questionstack condition = 0 while len(questionstack) > 1: for i in range(0, len(questionstack)): if questionstack[i] == '×': questionstack[i - 1] = questionstack[i - 1] * questionstack[i + 1] del questionstack[i] del questionstack[i] break elif questionstack[i] == '÷': questionstack[i - 1] = questionstack[i - 1] / questionstack[i + 1] del questionstack[i] del questionstack[i] break else: condition = 1 if condition == 1: if len(questionstack) > 1: questionstack[0] = calculate(questionstack[0], questionstack[2], questionstack[1]) del questionstack[1] del questionstack[1] # print question # print questionstack else: ans = questionstack[0] else: n1=random.randint(1,5) n2=random.randint(1,3) n3=random.randint(1,5) symbolnumber = n1 question = '' questionstack = [] ans = 0 length_ques = 0 for i in range(1, symbolnumber + 1): if i==n3: (op,va,de)=getlabelquestionbyn(opestr,numstr,ran,n2) operands = op value = va (operators, length) = getlabeloperators(opestr) question = question +'('+ operands +')'+ operators questionstack.append(value) questionstack.append(operators) length_ques = length_ques + length + de else: (op, va, de) = getlabeloperands(numstr, ran) operands = op value = va (operators, length) = getlabeloperators(opestr) question = question + operands + operators questionstack.append(value) questionstack.append(operators) length_ques = length_ques + length + de (op, va, de) = getlabeloperands(numstr, ran) operands = op value = va question = question + operands questionstack.append(value) length_ques = length_ques + de # print question # print questionstack condition = 0 while len(questionstack) > 1: for i in range(0, len(questionstack)): if questionstack[i] == '×': questionstack[i - 1] = questionstack[i - 1] * questionstack[i + 1] del questionstack[i] del questionstack[i] break elif questionstack[i] == '÷': questionstack[i - 1] = questionstack[i - 1] / questionstack[i + 1] del questionstack[i] del questionstack[i] break else: condition = 1 if condition == 1: if len(questionstack) > 1: questionstack[0] = calculate(questionstack[0], questionstack[2], questionstack[1]) del questionstack[1] del questionstack[1] # print question # print questionstack else: ans = questionstack[0] return question, ans, length_ques def getdiyoperators(list): operators = random.choice(list) list.remove(operators) if operators == '×': length = 2 elif operators == '÷': length = 2 else: length = 1 return operators, length,list def getdiyquestionbylist(list,numstr,ran): question = '' questionstack = [] ans = 0 length_ques = 0 for i in range(1, len(list) + 1): (op, va, de) = getlabeloperands(numstr, ran) operands = op value = va (operators, length, list1) = getdiyoperators(list) list = list1 question = question + operands + operators questionstack.append(value) questionstack.append(operators) length_ques = length_ques + length + de (op, va, de) = getlabeloperands(numstr, ran) operands = op value = va question = question + operands questionstack.append(value) length_ques = length_ques + de # print question # print questionstack condition = 0 while len(questionstack) > 1: for i in range(0, len(questionstack)): if questionstack[i] == '×': questionstack[i - 1] = questionstack[i - 1] * questionstack[i + 1] del questionstack[i] del questionstack[i] break elif questionstack[i] == '÷': questionstack[i - 1] = questionstack[i - 1] / questionstack[i + 1] del questionstack[i] del questionstack[i] break else: condition = 1 if condition == 1: if len(questionstack) > 1: questionstack[0] = calculate(questionstack[0], questionstack[2], questionstack[1]) del questionstack[1] del questionstack[1] # print question # print questionstack else: ans = questionstack[0] return question, ans, length_ques def getdiyquestion(list,numstr,ran,brastr): if brastr=="无": question = '' questionstack = [] ans = 0 length_ques = 0 for i in range(1, len(list) + 1): (op, va, de) = getlabeloperands(numstr, ran) operands = op value = va (operators, length, list1) = getdiyoperators(list) list = list1 question = question + operands + operators questionstack.append(value) questionstack.append(operators) length_ques = length_ques + length + de (op, va, de) = getlabeloperands(numstr, ran) operands = op value = va question = question + operands questionstack.append(value) length_ques = length_ques + de # print question # print questionstack condition = 0 while len(questionstack) > 1: for i in range(0, len(questionstack)): if questionstack[i] == '×': questionstack[i - 1] = questionstack[i - 1] * questionstack[i + 1] del questionstack[i] del questionstack[i] break elif questionstack[i] == '÷': questionstack[i - 1] = questionstack[i - 1] / questionstack[i + 1] del questionstack[i] del questionstack[i] break else: condition = 1 if condition == 1: if len(questionstack) > 1: questionstack[0] = calculate(questionstack[0], questionstack[2], questionstack[1]) del questionstack[1] del questionstack[1] # print question # print questionstack else: ans = questionstack[0] elif brastr=="有": n1=random.randint(1,len(list)-1) n2=len(list)-n1 n3=random.randint(1,n2) list_in=[] for i in range(1,n1+1): kop=random.choice(list) list_in.append(kop) list.remove(kop) question = '' questionstack = [] ans = 0 length_ques = 0 for i in range(1, n2 + 1): if i==n3: (op,va,de)=getdiyquestionbylist(list_in,numstr,ran) operands = op value = va (operators, length, list1) = getdiyoperators(list) list = list1 question = question + '('+operands+')' + operators questionstack.append(value) questionstack.append(operators) length_ques = length_ques + length + de else: (op, va, de) = getlabeloperands(numstr, ran) operands = op value = va (operators, length, list1) = getdiyoperators(list) list = list1 question = question + operands + operators questionstack.append(value) questionstack.append(operators) length_ques = length_ques + length + de (op, va, de) = getlabeloperands(numstr, ran) operands = op value = va question = question + operands questionstack.append(value) length_ques = length_ques + de # print question # print questionstack condition = 0 while len(questionstack) > 1: for i in range(0, len(questionstack)): if questionstack[i] == '×': questionstack[i - 1] = questionstack[i - 1] * questionstack[i + 1] del questionstack[i] del questionstack[i] break elif questionstack[i] == '÷': questionstack[i - 1] = questionstack[i - 1] / questionstack[i + 1] del questionstack[i] del questionstack[i] break else: condition = 1 if condition == 1: if len(questionstack) > 1: questionstack[0] = calculate(questionstack[0], questionstack[2], questionstack[1]) del questionstack[1] del questionstack[1] # print question # print questionstack else: ans = questionstack[0] return question, ans, length_ques
def calculate1(data:list, waypoint = (0,1)): """Calculate the values""" '''Direction 1: North 2: East 3: South 4: West ''' waypoint_map = { 'N': lambda x,y: (x, y), 'E': lambda x,y: (y, -x), 'S': lambda x,y: (-x, -y), 'W': lambda x,y: (-y, x), } movement_mapping = { 'N': (0, 1), 'E': (1, 0), 'S': (0,-1), 'W': (-1,0), } dirs = { 'N': 0, 0: 'N', 'E': 1, 1: 'E', 'S': 2, 2: 'S', 'W': 3, 3: 'W', } curr_dir = 'E' position = [0, 0] #x, y for movement in data: direction = movement[0] space = int(movement[1:]) # Get current direction if direction == 'F': x_change, y_change = waypoint_map[curr_dir](*waypoint) position[0] += x_change * space position[1] += y_change * space continue if (direction in movement_mapping.keys()): #Shift the position x_change, y_change = movement_mapping[direction] position[0] += x_change * space position[1] += y_change * space continue #Change direction change = space // 90 dir_num = dirs[curr_dir] if direction == 'R': d = (dir_num + change) elif direction == 'L': d = (dir_num - change) else: raise Exception(f"Not suppose to be here {direction}") curr_dir = dirs[d % 4] return tuple(position) def part1(data:tuple): '''Part 1 solution''' #Calculate position position = calculate1(data) #Return pos1 + pos2 return abs(position[0] + position[1]) def calculate2(data:list, waypoint:list): '''Direction 1: North 2: East 3: South 4: West ''' movement_mapping = { 'N': (0, 1), 'E': (1, 0), 'S': (0,-1), 'W': (-1,0), } position = [0, 0] #x, y for movement in data: direction = movement[0] space = int(movement[1:]) # Get current direction if direction == 'F': x_change, y_change = waypoint position[0] += x_change * space position[1] += y_change * space continue if (direction in movement_mapping.keys()): #Shift the position x_change, y_change = movement_mapping[direction] waypoint[0] += x_change * space waypoint[1] += y_change * space continue #Change direction change = space // 90 if direction == 'R': for _ in range(change): waypoint[0], waypoint[1] = waypoint[1], -waypoint[0] elif direction == 'L': for _ in range(change): waypoint[0], waypoint[1] = -waypoint[1], waypoint[0] else: raise Exception(f"Not suppose to be here {direction}") return tuple(position) def part2(data:tuple): waypoint = [10, 1] position = calculate2(data, waypoint) return abs(position[0]) + abs(position[1]) with open('data.txt') as file: data = tuple(map(lambda x: x.strip(), file.readlines())) print(part1(data)) print(part2(data))
import os import pandas as pd import sqlite3 CSV_FILEPATH = os.path.join(os.path.dirname(__file__), "..", "data", "buddymove_holidayiq.csv") DB_FILEPATH = os.path.join(os.path.dirname(__file__), "..", "data", "buddymove_holidayiq.db") connection = sqlite3.connect(DB_FILEPATH) table_name = "reviews2" df = pd.read_csv(CSV_FILEPATH) # assigns a column label "id" for the index column df.index.rename("id", inplace=True) df.index += 1 # starts ids at 1 instead of 0 print(df.head()) df.to_sql(table_name, con=connection) cursor = connection.cursor() cursor.execute(f"SELECT count(distinct id) as review_count FROM {table_name};") results = cursor.fetchone() print(results, "RECORDS") # Other approach # conn = sqlite3.connect("buddymove_holidayiq.sqlite3") # data.to_sql('review', conn, if_exists = 'replace') # curs = conn.cursor() # query = "SELECT * FROM review" # results = curs.execute(query).fetchall() # print("There are", len(results), "rows") # ---------------------------------------- # (Stretch) What are the average number of reviews for each category? conn = sqlite3.connect("buddymove_holidayiq.sqlite3") curs = conn.cursor() categories = ['Sports', 'Religious', 'Nature', 'Theatre', 'Shopping', 'Picnic'] query = "SELECT * FROM review" length = len(curs.execute(query).fetchall()) for item in categories: query = f"SELECT SUM({item}) FROM review" results = curs.execute(query).fetchall() print(f'Average number of reviews for {item} column:', round(results[0][0]/length))
from help import RemoveWhiteSpaces from help import Space_Out def PART_1_OF_FINAL_PROJECT_CPSC_323(): print("\n\nWHITE SPACE AND COMMENT REMOVEAL\n\n") infile = open('finalp1.txt','r') whole = infile.read() number_of_lines = whole.count('\n') infile.close() file1 = open('finalp1.txt', 'r') output_to_file2 = open('finalp2.txt', 'w') for i in range(number_of_lines): read_line = file1.readline() #This will read a line from the .txt file read_line = read_line.strip() # This will strip whitespaces, \t s, and \n s from both sides of the string in variable read_line = read_line.replace('\t', '') #It will remove any \t characters that still exist in the string read_line = RemoveWhiteSpaces(read_line) # will remove any excess whitespaces are_there_comments = False comments_start_index = 0 if read_line[0:2] !='/*' and read_line[len(read_line)-2:] != '*/' and read_line[0:2] !='//' and read_line != '': read_line = Space_Out(read_line) read_line = RemoveWhiteSpaces(read_line) for i in range(len(read_line)): if read_line[i - 2:i] == '//': are_there_comments = True comments_start_index = i - 2 if are_there_comments: read_line = read_line[0:comments_start_index] read_line = read_line.strip() output_to_file2.write(read_line + '\n') else: read_line = read_line.strip() output_to_file2.write(read_line + '\n') read_line = file1.readline() # This will read a line from the .txt file read_line = read_line.strip() # This will strip whitespaces, \t s, and \n s from both sides of the string in variable read_line = read_line.replace('\t', '') # It will remove any \t characters that still exist in the string read_line = RemoveWhiteSpaces(read_line) # will remove any excess whitespaces are_there_comments = False comments_start_index = 0 if read_line[0:2] != '/*' and read_line[len(read_line) - 2:] != '*/' and read_line[0:2] != '//' and read_line != '': read_line = Space_Out(read_line) read_line = RemoveWhiteSpaces(read_line) for i in range(len(read_line)): if read_line[i - 2:i] == '//': are_there_comments = True comments_start_index = i - 2 if are_there_comments: read_line = read_line[0:comments_start_index] read_line = read_line.strip() output_to_file2.write(read_line) else: read_line = read_line.strip() output_to_file2.write(read_line) file1.close() output_to_file2.close() print("\nFINISHED PART 1\n")
# Lightly modified from from https://scipython.com/book/chapter-8-scipy/additional-examples/the-sir-epidemic-model/ # Goal is to learn the beta and gamma parameters from socio-economic facotrs import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt class SIRmodel(): def __init__(self, N=1000, I0=1, R0=1): # Total population, N. self.N = N # Initial number of infected and recovered individuals, I0 and R0. self.I0 = I0 self.R0 = R0 # Everyone else, S0, is susceptible to infection initially. self.S0 = N - I0 - R0 # Contact rate, beta, and mean recovery rate, gamma, (in 1/days). # These should be learned self.beta = 0.2 self.gamma = 1./10 # The SIR model differential equations. def deriv(self, y, t, N, beta, gamma): S, I, R = y dSdt = -beta * S * I / N dIdt = beta * S * I / N - gamma * I dRdt = gamma * I return dSdt, dIdt, dRdt # Learn parameters and update them here def update_param(self, beta, gamma): self.beta = beta self.gamma = gamma def plot(self, t): # Initial conditions vector y0 = self.S0, self.I0, self.R0 # Integrate the SIR equations over the time grid, t. ret = odeint(self.deriv, y0, t, args=(self.N, self.beta, self.gamma)) S, I, R = ret.T # Plot the data on three separate curves for S(t), I(t) and R(t) fig = plt.figure(facecolor='w') ax = fig.add_subplot(111, axisbelow=True) ax.plot(t, S/1000, 'b', alpha=0.5, lw=2, label='Susceptible') ax.plot(t, I/1000, 'r', alpha=0.5, lw=2, label='Infected') ax.plot(t, R/1000, 'g', alpha=0.5, lw=2, label='Recovered with immunity') ax.set_xlabel('Time /days') ax.set_ylabel('Number (1000s)') ax.set_ylim(0,1.2) ax.yaxis.set_tick_params(length=0) ax.xaxis.set_tick_params(length=0) ax.grid(b=True, which='major', c='w', lw=2, ls='-') legend = ax.legend() legend.get_frame().set_alpha(0.5) for spine in ('top', 'right', 'bottom', 'left'): ax.spines[spine].set_visible(False) plt.show() if __name__ == "__main__": # A grid of time points (in days) t = np.linspace(0, 160, 160) model = SIRmodel() model.plot(t)
from abc import ABC, abstractmethod class Distribution(ABC): def __init__(self): super().__init__() @abstractmethod def mean(self): pass @abstractmethod def update(self): pass @abstractmethod def sample(self): pass @abstractmethod def get_params(self): pass @abstractmethod def set_params(self): pass
# program of a terminal calculator a = int(input("Enter first number : ")) b = int(input("Enter second number : ")) print( "Welcome! \n \n Select an option \n 1 for addition \n 2 for subtraction \n 3 for multiplication \n 4 for division \n q for quitting") ch = input() while True: if ch == "1": print("Sum is :", a + b) a = int(input("Enter first number : ")) b = int(input("Enter second number : ")) print( "Welcome! \n \n Select an option \n 1 for addition \n 2 for subtraction \n 3 for multiplication \n 4 for division \n q for quitting") ch = input() elif ch == "2": print("Difference is : ", a - b) a = int(input("Enter first number : ")) b = int(input("Enter second number : ")) print( "Welcome! \n \n Select an option \n 1 for addition \n 2 for subtraction \n 3 for multiplication \n 4 for division \n q for quitting") ch = input() elif ch == "3": print("Product is : ", a * b) a = int(input("Enter first number : ")) b = int(input("Enter second number : ")) print( "Welcome! \n \n Select an option \n 1 for addition \n 2 for subtraction \n 3 for multiplication \n 4 for division \n q for quitting") ch = input() elif ch == "4": print("Division is : ", a / b) a = int(input("Enter first number : ")) b = int(input("Enter second number : ")) print( "Welcome! \n \n Select an option \n 1 for addition \n 2 for subtraction \n 3 for multiplication \n 4 for division \n q for quitting") ch = input() elif ch =="q": print("Quitting calculator") break else: print("Not a valid option") print( "Welcome! \n \n Select an option \n 1 for addition \n 2 for subtraction \n 3 for multiplication \n 4 for division \n q for quitting") ch = input() # program to find if a year is leap or not a = int(input("Enter the year : ")) if a % 4 == 0: print(a, "is a leap year") else: print(a, "is not a leap year") # program that checks if a form is valid name = input("Enter your name : ") age = input("Enter your age : ") mob_num = input("Enter mobile number : ") while True: if name =="": name = input("Name cannot be empty, enter your name again : ") elif name.isalpha() == False: name = input("Name can contain only alphabets, enter your name again : ") else: if age =="": age= input("age cannot be empty, enter your age again : ") elif age.isdigit() == False: age = input("Age can contain only numbers, enter your age again : ") elif int(age) < 19: age = input("Age can only be over 18, enter your age again : ") else: if mob_num =="": mob_num = input("Mobile number cannot be empty, enter your number again : ") elif mob_num.isdigit() == False: mob_num = input("Mobile Number can contain only numbers, enter your number again : ") else: print("Name = ", name , "\nAge = ", age, "\nMobile Number = ", mob_num) break # program to print multiplication table a = int(input("Enter number for which the table is required : ")) for i in range(1,11): print(a ,"*", i, "=", a*i ) # program to add 10 numbers using only one input statement to a list list = [] i=1 while i <=10: a = input("Enter #" + str(i)) if a.isnumeric(): list.append(a) i = i+1 else: print(a, "is not a number") print("List of numbers = ", list) # program to display only even number among a list list_num = [12,4,35,98,99,13,52,67,1,22,76] list_even =[] for x in list_num: if x%2 == 0: list_even.append(x) print("List of numbers = ", list_num) print("List of even numbers = ", list_even) # program to arrange data in list into different list according to their data type list = ["a",12,1.89, 66,"rahul", 4.22, "rojan", "himalaya", 44,1.87] list_int=[] list_float=[] list_string=[] for x in list: if isinstance(x, int): list_int.append(x) elif isinstance(x,str): list_string.append(x) else: list_float.append(x) print("The list with int :", list_int) print("The list with float :", list_float) print("The list with string :", list_string) # program to remove a user desired number from a list list = [23, 11, 69, 12, 34, 2, 6, 23, 43, 1233, 23, 222, 69, 23] print("Old list is ", list) num = int(input("Enter number to be removed")) for x in list: if x == num: list.remove(x) print("New list is", list)
import sys str = sys.argv[1] st = str.strip() i = str.find("_",0,len(str)) j = str.find("_",i+1,len(str)) #f.write(str + "\n") newStr = str[j+1:] + " of " + str[i+1:j] newStr = newStr.strip() print newStr.upper()
""" This module implement a rainbow effect. It will send color messages to pass through all rainbow colors : red, yellow, green, turquoise, blue, purple. """ import threading import colorsys class RainbowThread(threading.Thread): """docstring for RainbowThread""" def __init__(self, connection, lights, stop_event): super(RainbowThread, self).__init__() self.stop_event = stop_event self.connection = connection self.lights = lights def run(self): sleep_time = 0.1 hue_increment = sleep_time / 30 # Start the write data loop hue = 0.0 self.stop_event.clear() # Loop execute every sleep_time second until stop_event is set while not self.stop_event.wait(sleep_time): rgb = colorsys.hsv_to_rgb(hue, 1.0, 1.0) message = "" for light in self.lights: message = message + 'set light %s rgb %f %f %f\n' % ( light, rgb[0], rgb[1], rgb[2]) self.connection.send(message.encode()) hue = (hue + hue_increment) % 1.0
# ---------------------------------------------------------------------------- # 8-7. Album: Write a function called make_album() that builds a dictionary # describing a music album. The function should take in an artist name and an # album title, and it should return a dictionary containing these two pieces of # information. Use the function to make three dictionaries representing # different albums. Print each return value to show that the dictionaries are # storing the album information correctly. # Add an optional parameter to make_album() that allows you to store the # number of tracks on an album. If the calling line includes a value for # the number of tracks, add that value to the album’s dictionary. Make at least # one new function call that includes the number of tracks on an album. # ---------------------------------------------------------------------------- # 8-8. User Albums: Start with your program from Exercise 8-7. Write a while # loop that allows users to enter an album’s artist and title. Once you have # that information, call make_album() with the user’s input and print the # dictionary that’s created. Be sure to include a quit value in the while loop. # ---------------------------------------------------------------------------- print("This is ex8-7 and ex8-8: ") def make_album(artist_name, album_title, track_num=''): """Return a dictionary describing a music album """ album_info = {'artist name': artist_name, 'album title': album_title,} if track_num: album_info['number of tracks'] = track_num return album_info while True: print("(enter 'q' at any time to quit)") ar_name = raw_input("\nTell me the artist's name: ") if ar_name == 'q': break al_name = raw_input("\nWhat's the album's name: ") if al_name == 'q': break tr_num = raw_input("\nDo you know the number of tracks on that album? ") if tr_num == 'q': break print("Here is something about an album: ") album = make_album(ar_name, al_name, tr_num) print(album) # ---------------------------------------------------------------------------- # 8-12. Sandwiches: Write a function that accepts a list of items a person # wants on a sandwich. The function should have one parameter that collects as # many items as the function call provides, and it should print a summary of # the sandwich that is being ordered. Call the function three times, using a # different number of arguments each time. # ---------------------------------------------------------------------------- print("This is ex8-12: ") def make_sandwich(*items): """Make a sandwich with the given items.""" print("\nI'll make you a great sandwich: ") for item in items: print(" ...adding " + item + " to your sandwich.") print("Your sandwich is ready!") make_sandwich('cheese', 'roast beef', 'lettcue') make_sandwich('turkey', 'extra cheese', 'honey dijon', 'apple slice') make_sandwich('strawberry jam', 'peanut butter') # ---------------------------------------------------------------------------- # 8-13. User Profile: Start with a copy of user_profile.py from page 153. Build # a profile of yourself by calling build_profile(), using your first and last # names and three other key-value pairs that describe you. # ---------------------------------------------------------------------------- print("\nThis is ex8-13: ") def build_profile(first, last, **user_info): """Build a dictionary containing everything we know about a user.""" profile = {} profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile('alex', 'dumphy', location='new york', field='physics') print(user_profile) # ---------------------------------------------------------------------------- # 8-14. Cars: Write a function that stores information about a car in a # dictionary. The function should always receive a manufacturer and a model # name. It should then accept an arbitrary number of keyword arguments. # Call the function with the required information and two other name-value # pairs, such as a color or an optional feature. Your function should work for # a call like this one: # -------------------------------------------------------------------------- # car = make_car('subaru', 'outback', color='blue', tow_package=True) # -------------------------------------------------------------------------- # Print the dictionary that’s returned to make sure all the information was # stored correctly. # ---------------------------------------------------------------------------- print("\nThis is ex8-14: ") def make_car(make, model, **options): """Make a dictionary representing a car.""" car_info = { 'manufacturer': make.title(), 'model': model.title(), } for option, value in options.items(): car_info[option] = value return car_info my_tesla = make_car('tesla', 's', color='silver', year=2017) print(my_tesla)
import unittest from hash_table_with_separate_chaining import HashTable class TestWithSeparateChaining(unittest.TestCase): def test_init(self): """ Test new Node initialization """ ht = HashTable() self.assertIsInstance(ht, HashTable) self.assertEqual(ht.size, 9) self.assertEqual(ht._map, [None] * 9) def test_hash(self): ht = HashTable() self.assertEqual(ht._hash('jon'), 3) self.assertEqual(ht._hash('amy'), 3) self.assertEqual(ht._hash('mike'), 4) self.assertEqual(ht._hash('123456789'), 0) def test_set(self): ht = HashTable() ht.set('jon', 'jons value') self.assertEqual(ht._map[3], [['jon', 'jons value']]) ht.set('mike', 'mikes value') self.assertEqual(ht._map[4], [['mike', 'mikes value']]) # amy will overwrite jon ht.set('amy', 'amys value') self.assertEqual(ht._map[3], [['jon', 'jons value'], ['amy', 'amys value']]) def test_get(self): ht = HashTable() ht.set('jon', 'jons value') self.assertEqual(ht.get('jon'), 'jons value') ht.set('mike', 'mikes value') self.assertEqual(ht.get('mike'), 'mikes value') # amy will overwrite jon ht.set('amy', 'amys value') self.assertEqual(ht.get('amy'), 'amys value') # jon will still return jons value, amy will NOT have over written jon self.assertEqual(ht.get('jon'), 'jons value') def test_keys(self): ht = HashTable() ht.set('jon', 'jons value') ht.set('mike', 'mikes value') self.assertEqual(ht.keys(), ['jon', 'mike']) ht.set('amy', 'amys value') self.assertEqual(ht.keys(), ['jon', 'amy', 'mike']) if __name__ == "__main__": unittest.main()
import copy import itertools import random def first(iterable): return next(iter(iterable)) def pairwise(iterable): first, second = itertools.tee(iterable) next(second, None) return itertools.zip_longest(first, second) def prepend(first, iterable): yield first for item in iterable: yield item def random_iter(iterable): a = copy.copy(iterable) random.shuffle(a) return iter(a) class count_iter(): def __init__(self, iterable): self._iterator = iter(iterable) self._index = 0 def __iter__(self): return self def __next__(self): self._index += 1 return next(self._iterator) @property def index(self): return self._index
Nama_Teman = ['Fagih','Raka','Alif','Ano','Rizal','Nauval','Ahnaf','Jefri','Rafli','Hasan'] print('Nama Teman_Semula:', Nama_Teman) print ("Nama Teman[4]:", Nama_Teman[4]) print ("Nama Teman[6]:", Nama_Teman[6]) print ("Nama Teman[7]:", Nama_Teman[7]) Nama_Teman[3] = ('Akrom') Nama_Teman[5] = ('Rara') Nama_Teman[9] = ('Aji') print('Nama Teman Setelah Diubah:', Nama_Teman) Nama_Teman.append('Ilham') Nama_Teman.append('Rian') print('Nama Teman setelah ditambah:', Nama_Teman) for i in Nama_Teman: print(i) print('Panjang List:', len(Nama_Teman))
import numpy as np import pandas as pd from pandas.api.types import is_datetime64_any_dtype as is_datetype def drop_n_rows(df, n): """Drop first n rows from data. Args: df: DataFrame to be modified. n: number of rows to drop. """ if (not isinstance(n, int)) or (n < 0): raise TypeError("n must be a positive integer") df.drop(df.index[:n], inplace=True) return df def drop_cols(df, cols): """ Drop selected columns inplace Args: df: DataFrame to modify. cols: Columns to drop. """ if not isinstance(cols, list): cols = [cols] df.drop(cols, axis=1, inplace=True) return df def keep_cols(df, cols): """ Keep selected columns inplace. Args: df: DataFrame to modify. cols: Columns to keep. """ if not isinstance(cols, list): cols = [cols] dcols = [col for col in df.columns if col not in cols] df.drop(dcols, axis=1, inplace=True) return df def rename_cols(df, new_names): """Rename selected columns inplace Args: df: DataFrame to modify. new_names: Either a string (If df is a series or has one columns), a list (whose length must be the same as the number col columns in df or a dictionary with {old_name; new_name} pairs. """ if isinstance(new_names, str): new_names = [new_names] if isinstance(new_names, list): if len(new_names) != len(df.columns): raise ValueError(f"if new_names is a list, it must be of the same length as dataframe columns, \ which in this case is {len(df.columns)}") df.columns = new_names elif isinstance(new_names, dict): df.rename(new_names, axis=1, inplace=True) return df def set_date_index(df, cols="Date", is_iloc=False, date_format=None): """Set the selected datetime column as the dataframe's index. Args: df: DataFrame to be modified col_name: Column to become index. is_iloc: whether the "cols" parameter is an integer location to the column. date_format: datetime format to convert column, in case the column is currently currently of type string. """ if is_iloc: if not isinstance(cols, int): TypeError("col_name must be an integer column location if you set is_iloc equal to True") if isinstance(cols, slice): cols = df.columns[cols].tolist() else: cols = df.columns[cols] if not is_datetype(df[cols]): df[cols] = pd.to_datetime(df[cols], format=None) df.set_index(cols, drop=True, inplace=True) df.index.name = "Date" df.sort_index(inplace=True) return df def remove_punct(df, punct, cols=None) : """Remove a certain punctuation from selected columns. NOTE: This function had problems in the past where the very last elemnt of a column is set to np.nan. This implementation checks for that, but adds some complexity and slows down the function. Args: df: DataFrame to modify. punct: Single punctuation or list of punctuation to remove. cols: columns to modify. """ if cols is None: cols = df.columns.tolist() elif not isinstance(cols, list): cols = [cols] if not isinstance(punct, list): punct = [punct] for col in cols: if df[col].dtypes == "object": for p in punct: # TODO: you absolue monster # Anyhow, the .str.replace method deletes the last value # of a series from time to time. new_col = df[col].str.replace(p, "") if pd.isna(new_col[-1]): new_col[-1] = df[col][-1] df[col] = new_col return df def delete_item(df, item, cols=None) : """Delete specific items from the dataframe Args: df: DataFrame to modify. item: Item to find and delete. cols: Columns to delete items. """ if cols is None: cols = df.columns.tolist() elif not isinstance(cols, list): cols = [cols] elif not isinstance(item, list): item = [item] for col in cols: df[col] = df[col].replace(item, np.nan) return df def set_type(df, dtype, cols=None, is_iloc=False): """Set a column to a specific data type. Args: df: DataFrame to modify. dtype: Data type to change columns into. cols: columns to modify. is_iloc: whether the "cols" parameter is an integer location to the column. """ if not isinstance(dtype, type): raise TypeError("dtypep argument must of of type type") if is_iloc: if not isinstance(cols, (int, slice)): raise TypeError("col_name must be an integer column location if you set is_iloc equal to True") if isinstance(cols, slice): cols = df.columns[cols].tolist() else: cols = df.columns[cols] if cols is None: cols = df.columns.tolist() elif not isinstance(cols, list): cols = [cols] df[cols] = df[cols].astype(dtype) return df
#average N = int(input()) numbers = list(map(int, input().split())) total=0 for i in numbers: total+=i avg=total/N print(avg) #median numbers.sort() if N % 2 != 0 : med = numbers[((N-1)//2)+1] else: med = (numbers[(N-1)//2]+numbers[((N-1)//2)+1])/2 print(med) #Mode mode=max(numbers, key=numbers.count) print(mode)
def list_item (list, value): """a function to find all indices of a given value in a list.""" indices =[] # Iterate through list to for i in range(len(liste)): if liste[i] == value: indices.append([i]) # if list contain other list elif type(liste[i]) is list: # using recursive method to find index in sublist for index in list_item(liste[i],value): # catenate the index of the list to the front of index value indices.append ([i]+index) return indices
# # @lc app=leetcode.cn id=94 lang=python3 # # [94] 二叉树的中序遍历 # # @lc code=start # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: res = [] arr = [] while arr or root: while root: arr.append(root) root = root.left root = arr.pop() res.append(root.val) root = root.right return res head = TreeNode(1) right = TreeNode(2) left = TreeNode(3) head.right = right right.left = left s = Solution() s.inorderTraversal(head) # @lc code=end
import unittest import isprime class TestStringMethods(unittest.TestCase): def test_two_is_prime(self): self.assertTrue(isprime.isPrime(2)) def test_one_is_not_prime(self): self.assertFalse(isprime.isPrime(1)) def test_three_is_prime(self): self.assertTrue(isprime.isPrime(3)) def test_four_is_not_prime(self): self.assertFalse(isprime.isPrime(4)) def test_fifteen_is_not_prime(self): self.assertFalse(isprime.isPrime(15)) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # -*- encoding: utf-8 -*- # @Author : Ren Qiang # ACtion2 互补DNA 其中,A与T互补,C与G互补编写函数DNA_strand(dna) # %% 自己的做法 def DNA_strand(dna): out = '' for i in dna: # print(i) if i == 'A': out += 'T' elif i == 'T': out += 'A' elif i == 'C': out += 'G' elif i == 'G': out += 'C' else: print("输入的数据中有非ATCG字符,异常字符为:", i) print(dna + ' 转录后为:' + out) return out DNA_strand("ATTGC") DNA_strand("AAAA") DNA_strand("ATCGT") # %% 借鉴优秀案例1 Dict = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'} DNA_input = ['ATTGC', 'AAAA', 'ATCGT'] def DNA_trans_1(dna): out = '' for i in dna: try: out += Dict[i] except: out += '{' + i + '}' print(dna + '\t中有非ATCG字符:' + i) print(dna + '\t转录后为:' + out) return out print('优秀案例1:') result = list(map(DNA_trans_1, DNA_input)) # %% 借鉴优秀案例2 def DNA_trans_2(dna): # 定义转录函数 key = 'GACT' # 构建巧妙的索引循环 output = '' for i in dna: try: output += key[key.index(i.upper())-2] except: output += '{' + i + '}' # 标注非标准字符 print(dna, '\t中有非ATCG字符:', i) print(dna, '\t转录后为:', output) return output DNA_input = ['qttgc', 'AAAA', 'ATCGT'] # 输入 print('优秀案例2:') result = list(map(DNA_trans_2, DNA_input)) # 调用转录函数 # %%
for i in range(1,5): for j in range(4-i): print(" ",end="") for j in range(i*2-1): print("*",end="") print("") for i in range(5,8): for j in range(i-4): print(" ",end="") for j in range(15-2*i): print("*",end="") print("")
def mult(n): res = 1 for i in range(1,n+1): res *= i return res sum = 0 for i in range(1,21): sum += mult(i) print(mult(i),sum)
a = [1,2,3,4,10,12] num = int(input("num:")) res = [] for i in range(len(a)): if num >= a[i]: res.append(a[i]) if i == len(a)-1: res.append(num) else: res.append(num) for j in range(i,len(a)): res.append(a[j]) break print(res)
list = [] for i in range(5): str = input() list.append(str) print(list)
class student: name = "" age = 0 score = 0 def input(self): self.name = input("name:") self.age = int(input("age:")) self.score = int(input("score:")) def output(self): print("name:",self.name) print("age:",self.age) print("score:",self.score) if __name__ == '__main__': student_list = [] for i in range(5): student_list.append(student()) for i in range(5): student_list[i].input() for i in range(5): student_list[i].output()
# 递归 def fib(n): if n == 1 or n == 2: return 1 else: return fib(n-1)+fib(n-2) # 非递归 def fib1(n): a,b = 0,1 for i in range(0,n-1): a,b = b,a+b return b print(fib(10)) print(fib1(10))
str1 = "hello" str2 = "wujue" str = str1 + str2 print(str)
class Solution: #define if A win score = 100, else A lose (i.e B wins) score = -100 #define winning scenario for A's round (when player = A and remain = 1 to 3) Turn_A_Score={ 1:100, 2:100, 3:100 } #define winning scenario for B's round (when player = B and remain = 1 to 3) Turn_B_Score={ 1:-100, 2:-100, 3:-100 } def score(self,player,remain): if (player=='A'): #A is maximizing score in each round to give himself win, if remain >3; #N: max(TurnB(N-1),TurnB(N-2),TurnB(N-3)) if remain not in self.Turn_A_Score: self.Turn_A_Score[remain] = max(self.score('B',remain-1),\ self.score('B',remain-2),\ self.score('B',remain-3)) return self.Turn_A_Score[remain] else: #if (player=='B'): #B is minimizing score in each round to give himself win, if remain >3 #N: min(TurnA(N-1),TurnA(N-2),TurnA(N-3)) if remain not in self.Turn_B_Score: self.Turn_B_Score[remain] = min(self.score('A',remain-1),\ self.score('A',remain-2),\ self.score('A',remain-3)) return self.Turn_B_Score[remain] def canWinNim(self, n): """ :type n: int :rtype: bool """ #method 1: using math trick, which is essential for large no. if performance is required if (n > 1000000): return n%4 != 0 #method 2: generic method using minimax tree if self.score('A', n) >= 100: return True else: return False
#Base Tasks #Task 1 home_tube_station='southwark' print(home_tube_station.title()) kcl_tube_station='temple' print('I cannot go from ' + home_tube_station.title() + ' to ' + kcl_tube_station.title() + ' in one go') #Task 2 elizabeth_line=['Southwark', 'Temple', 'Dilly', 'Campfire', 'Wonderland', 'Asterix', 'SevenEleven', 'Tricks'] def line_printer(line): for station in sorted(line): print(station) #Task 3 def stop_distance(line, origin, destination): if origin == destination: return 0 elif origin not in line or destination not in line: return -1 else: return abs(line.index(origin) - line.index(destination)) #takes the absolute value to have a positive number of stops in both directions print(stop_distance(elizabeth_line, 'Southwark', 'Campfire')) #Task 4 def journey_printer(line, origin, destination): if origin and destination not in line: return "A station isn't on the line" else: for i in range(abs(line.index(origin) - line.index(destination))+line.index(origin)+1): #takes the absolute value to have a positive number of stops in both directions, adds origin index to start from origin station and adds 1 to have the last station (because of the range function exclusion) print(line[i]) journey_printer(elizabeth_line, 'Southwark', 'Campfire') #Task 5 def fare(line, origin, destination, flag): c=0 if origin not in line or destination not in line: return 0 elif origin == destination: return 0 #because who would pay for the tube without travelling? else: for i in range(stop_distance(line, origin, destination)): if i < 5: c += 0.25 #the first four stops are charged 0.25 else: c += 0.2 #the following stops are charged 0.2 if flag == True: c += 2.5 #0.5 surcharge for peake time + base fare else: c += 2 #base fare if c > 3.5: c = 3.5 #maximum fare of 3.5 return c print(fare(elizabeth_line, 'Southwark', 'Campfire', True)) #Task 6 piccadilly = ['Arsenal', 'Kings Cross', 'Holborn', 'Covent Garden'] jubilee = ['Southwark', 'Queensbury', 'Cottage', 'Baker Street', 'Dilly'] tube_network = [('elizabeth_line', elizabeth_line), ('piccadilly', piccadilly), ('jubilee', jubilee)] def network_printer(network): for line in network: #selects the tuples in the network for tube in line: #selects the elements inside the tuple if type(tube) == str: #index 0 of the tuple is the name of the tube line print(tube.title(), ' line:') else: for station in tube: #index 1 of the tuple is a list of the tube stations print(station.title()) #we separated the tuple between index 0 and index 1 print('\n') network_printer(tube_network) #Task 7 def same_line(network, station1, station2): for line in network: #selects the tuples in the network flag1 = False #flags to check if each station is in the line flag2 = False for tube in line: #selects the elements inside the tuple if type(tube) == str: #index 0 of the tuple is the name of the tube line so we avoid it and focus on the stations pass else: #index 1 of the tuple is a list of the tube stations which is what we focus on for station in tube: #we check for each station in the line if they are the same as the two station given if station == station1: flag1 = True elif station == station2: flag2 = True if flag1 and flag2 == True: #if both station are in this line, True return True else: #we go back to the loop to check for the other lines in the network pass return False #if none of the lines have worked, False print(same_line(tube_network, 'Southwark', 'Dilly')) #Task8, creating a new database that is quicker to compute on def connected(network, station1, station2): cnet = [] #cnet for connected network where each index represents a network of connected lines for line in network: #selects the tuples in the network flag = False #flag to detect if new stations are already connected i = 0 #counter used to keep track of the cnet index we are on for tube in line: #selects the elements inside the tuple if type(tube) == str: pass else: while i<len(cnet): #check for each index in cnet for station in tube: #check for each station in the line if station in cnet[i]: for station in tube: if station in cnet[i]: #check to avoid duplicates pass else: cnet[i].append(station) #append each station to the connected network of index i flag = True #means the whole line is connected to the network of index i in cnet break else: pass if flag == True: #by using that second break, we avoid useless computation for the different indexes of cnet break else: pass i+=1 if flag == False: #the line is not connected to the previous lines and we need to create a new index cnet.append([]) for station in tube: cnet[len(cnet)-1].append(station) #uses new index to append each station else: pass c = 0 #counter used to keep track of the cnet index FROM which we check for similar stations for cline in cnet: #selects each list of connected stations in cnet for cstation in cline: #selects each station inside this list d=1 #counter used to keep track of the cnet index IN which we check for similar stations while d<len(cnet): if c-d==0: #avoid lists checking themselves d+=1 pass else: if cstation in cnet[d]: cnet[d].remove(cstation) #to avoid duplicates while cnet[d] != []: cnet[c].append(cnet[d].pop(0)) #deletes each value and adds them to the main connection list of index c d+=1 c+=1 #Now the program that actually verifies if the two stations are connected c = 0 while c<len(cnet): #check in each index of cnet individually if station1 in cnet[c] and station2 in cnet[c]: return True else: pass c+=1 return False print(connected(tube_network, 'Arsenal', 'Campfire'))
stack=[] stack.append('apple') stack.extend(['pear', 'banana', 'tomato']) print (stack) print(stack.pop(1)) letters = ['a', 'b', 'c', 'd'] new_list_1 = letters new_list_2 = letters[:] letters[2] = 'e' print(new_list_1) print(new_list_2) x = [1, 2] y = [1, 2] print(x == y) print(x is y) x=y print(x is y)
def split_and_reverse(string): length = (len(string) // 2) - 1 a, b = string[length::-1], string[:length:-1] return a + b print(split_and_reverse('privet'))
import pygame class Button(pygame.sprite.Sprite): def __init__(self, text, game, x, y, color): super().__init__() self.text = text self.width = 150 self.height = 50 self.game = game self.image = pygame.Surface([self.width, self.height]) self.image.fill(color) self.rect = self.image.get_rect() self.rect.midleft = (x,y) self.textsurface = self.game.font.render(text, False, (0, 0, 0)) self.image.blit(self.textsurface, (0, 0)) def click(self): pass class StartButton(Button): def __init__(self, text, game, x, y, color): super().__init__(text, game, x, y, color) def click(self): self.game.gamestate["playing"] = True self.game.gamestate["paused"] = False self.game.gamestate["menu"] = False class ContinueButton(Button): def __init__(self, text, game, x, y, color): super().__init__(text, game, x, y, color) def click(self): self.game.gamestate["playing"] = True self.game.gamestate["paused"] = False self.game.gamestate["menu"] = False self.game.mouseoffset = (0, 0) class QuitButton(Button): def __init__(self, text, game, x, y, color): super().__init__(text, game, x, y, color) def click(self): if not self.game.gamestate["playing"]: self.game.running = False else: """ To do: Implement are you sure you wish to quit with a sprite box. """ self.game.running = False
run = True users = [] while run: command = input("command >> ") if command == "exit": run = False if command == "new user": name = input("Nome: ") users.append(name) if command == "list users": for user in users: print(user) if command == "show user": index = int(input("Index: ")) print(users[index])
length = int(input(f"Введите длину массива: ")) array = [] for item in range(length): number = int(input(f"Введите элемент массива: ")) array.append(number) def sum_and_mult(array): summ = 0 mult = 1 for item in array: summ += item mult *= item return { "summ": summ, "mult": mult, "array": array } print(sum_and_mult(array))
string = input(f'Введите буквы: ') def str_compress(string): result = string[0] counter = 1 for i in range(len(string) - 1): if string[i] == string[i + 1]: counter += 1 else: if counter > 1: result += str(counter) result += string[i + 1] counter = 1 if counter > 1: result += str(counter) return result print(str_compress(string))
# В строке, состоящей из слов, разделенных пробелом, найти самое длинное слово. # Строка вводится с клавиатуры. string = input('Введите слова через пробел: ') def long_substr(string): array = string.split(' ') result = '' for item in array: if len(item) > len(result): result = item return f'Длинное слово: {result}' print(long_substr(string))
def remove_duplicates(array): result = [] for item in array: if item not in result: result.append(item) return result print(remove_duplicates([1, 1, 1, 2, 3, 2, 3]))
# Найти максимальный элемент среди минимальных элементов строк матрицы. def min_to_max(matrix): min_row = [] for item in matrix: min_row.append(min(item)) return f'Max element is {max(min_row)}' print(min_to_max([[1, 2, 3], [4, 5, 6], [100, -800, 99]]))
str1 = input(f'Введите слово 1-е: ') str2 = input(f'Введите слово 2-е: ') def anagram_str(str1, str2): str1 = str1.upper() str2 = str2.upper() if str1 == str2 or len(str1) != len(str2): return False for char in str1: if str1.count(char) != str2.count(char): return False return True print(anagram_str(str1, str2))
# Дан лист. Вернуть лист, состоящий из элементов, которые меньше среднего арифметического исходного листа. # С.а. = сумма элементов разделить на количество. def arr_less_average(arr): result = [] avr = sum(arr) / len(arr) for i in arr: if i < avr: result.append(i) return result print(arr_less_average([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]))
def pair_sum(arr, k): result = [] i = 0 while i < len(arr): ii = 0 while ii < len(arr): if arr[i] + arr[ii] == k and i != ii: find = sorted([arr[i], arr[ii]]) if find not in result: result.append(find) ii += 1 i += 1 return result print(pair_sum([1, 3, 3, 2, 4, -1, 5], 6))
def help_bob(string): result = '' for char in string: if char.isdigit() or char.isalpha(): result += char # print(result) return len(result) print(help_bob("!2jh$%#%3g"))
def convert_housing_data_to_quarters(): '''Converts the housing data to quarters and returns it as mean values in a dataframe. This dataframe should be a dataframe with columns for 2000q1 through 2016q3, and should have a multi-index in the shape of ["State","RegionName"]. Note: Quarters are defined in the assignment description, they are not arbitrary three month periods. The resulting dataframe should have 67 columns, and 10,730 rows. ''' import pandas as pd df= pd.read_csv("City_Zhvi_AllHomes.csv") #print(df.columns[1:7]) df.rename(columns ={"State": "states"}, inplace= True) df= df.set_index(["states","RegionName"]) df = df.iloc[:,49:250] def quarters(col): if col.endswith(("01", "02", "03")): s = col[:4] + "q1" elif col.endswith(("04", "05", "06")): s = col[:4] + "q2" elif col.endswith(("07", "08", "09")): s = col[:4] + "q3" else: s = col[:4] + "q4" return s housing = df.groupby(quarters, axis = 1).mean() housing = housing.sort_index() return housing convert_housing_data_to_quarters()
"""Q1. Define a class called Bike that accepts a string and a float as input, and assigns those inputs respectively to two instance variables, color and price. Assign to the variable testOne an instance of Bike whose color is blue and whose price is 89.99. Assign to the variable testTwo an instance of Bike whose color is purple and whose price is 25.0.""" class Bike: def __init__(self, color, price): self.color = color self.price = price testOne = Bike ("blue", 89.99) testTwo = Bike ("purple", 25.0) """Q2.Create a class called AppleBasket whose constructor accepts two inputs: a string representing a color, and a number representing a quantity of apples. The constructor should initialize two instance variables: apple_color and apple_quantity. Write a class method called increase that increases the quantity by 1 each time it is invoked. You should also write a __str__ method for this class that returns a string of the format: "A basket of [quantity goes here] [color goes here] apples." e.g. "A basket of 4 red apples." or "A basket of 50 blue apples." (Writing some test code that creates instances and assigns values to variables may help you solve this problem!) """ class AppleBasket: def __init__(self, apple_color, apple_quantity): self.apple_color = apple_color self.apple_quantity = apple_quantity def __str__(self): # special method return "A basket of {} {} apples."\ .format(self.apple_quantity, self.apple_color) def increase(self): # method return (self.apple_quantity + 1 ) apple = AppleBasket ("red", 4) apple1 = AppleBasket ("blue", 50) print(apple) print(apple.increase()) print(apple1) print(apple1.increase()) """Q3. Define a class called BankAccount that accepts the name you want associated with your bank account in a string, and an integer that represents the amount of money in the account. The constructor should initialize two instance variables from those inputs: name and amt. Add a string method so that when you print an instance of BankAccount, you see "Your account, [name goes here], has [start_amt goes here] dollars." Create an instance of this class with "Bob" as the name and 100 as the amount. Save this to the variable t1.""" class BankAccount: def __init__(self, name,amt): self.name = name self.amt = amt def __str__(self): return "Your account, {}, has {} dollars."\ .format(self.name, self.amt) t1 = BankAccount("Bob",100)
# Operadores Aritmeticos soma = "+" subt = "-" mult = "*" div = "/" exponenciacao = "**" parte_inteira = "//" soma_exe = 2 + 2 #= 4 ok subt_exe = 2 - 2 #= 0 ok mult_exe = 2 * 2 #= 4 ok div_exe = 2 / 2 #= 1 ok expo_exe = 2 ** 2 #= 4 ok parte_inteira_exe = 2 // 2 #= 1 ok print(soma_exe, "\n", subt_exe, "\n", mult_exe, "\n", div_exe, "\n", expo_exe, "\n", parte_inteira_exe) soma_2 = 2 + 2 texto = f'O resultado da soma é: {soma_2}' #print(nome, idade, email, telefone) print('O resultado da soma é: ', (2 + 2)) print('O resultado da soma é: ', soma_2) print(texto, soma_2) print('O resultado da soma é: ' + str(soma_2)) print(texto + str(soma_2)) print(texto) print('texto', 2 + 2, 8 / 2) x = (2 + 2)*2 float = 2.44 soma = (int(input('Primeiro Operador: ')) + int(input('Segundo Operador: '))) print(f'Resultado: {soma}') soma1 = int(input('Primeiro Operador: ')) soma2 = int(input('Segundo Operador: ')) resultado = (soma1 + soma2) print(f'Resultado: {resultado}') pais = "brasil" ano = "1500" descobridor = "Cabral" #'No ano de ANO, o PAIS foi descoberto por DESCOBRIDOR' #f'No ano de {ANO}, o {PAIS} foi descoberto por {DESCOBRIDOR}' print(f"Prova dos 9: {int(input('Informe um int'))}") print(f"Prova dos 9: {float(input('Informe um int'))}")
# -*- coding:UTF-8 -*- class Pizza(): name, dough, sauce, toppings = None, None, None, [] def prepare(self): print 'Preparing' + self.name print 'tossing dough...' print 'Adding sauce' print 'Adding toppings: ' for each in self.toppings: print " " + each def bake(self): print 'Bake for 25 minutes at 350' def cut(self): print 'Cutting the pizza into diagonal slices' def box(self): print 'Place pizza in official PizzaStore box' def get_name(self): return self.name class NYStyleCheesePizza(Pizza): def __init__(self): self.name = 'NY Style Sauce and Cheese Pizza' self.dough = 'Thin Crust Dough' self.sauce = 'Marinara Sauce' self.toppings.append('Grated Reggiano Cheese') class NYStyleVeggiePizza(Pizza): def __init__(self): self.name = 'NY Style Veggie Pizza' self.dough = 'Thin Crust Dough' self.sauce = 'Marinara Sauce' self.toppings.append('Grated Reggiano Cheese') class NYStyleClamPizza(Pizza): def __init__(self): self.name = 'NY Style Clam Pizza' self.dough = 'Thin Crust Dough' self.sauce = 'Marinara Sauce' self.toppings.append('Grated Reggiano Cheese') class NYStylePepperoni(Pizza): def __init__(self): self.name = 'NY Style Pepperoni Pizza' self.dough = 'Thin Crust Dough' self.sauce = 'Marinara Sauce' self.toppings.append('Grated Reggiano Cheese') class ChicagoStyleCheesePizza(Pizza): def __init__(self): self.name = 'Chicago Style Deep Dish Cheese Pizza' self.dough = 'Extra Thick Crust Dough' self.sauce = 'Plum Tomato Sauce' self.toppings.append("Shredded Mozzarella Cheese") def cut(self): print 'Cutting the pizza into square slices' class ChicagoStyleVeggiePizza(Pizza): def __init__(self): self.name = 'Chicago Style Veggie Cheese Pizza' self.dough = 'Extra Thick Crust Dough' self.sauce = 'Plum Tomato Sauce' self.toppings.append("Shredded Mozzarella Cheese") def cut(self): print 'Cutting the pizza into square slices' class ChicagoStyleClamPizza(Pizza): def __init__(self): self.name = 'Chicago Style Clam Cheese Pizza' self.dough = 'Extra Thick Crust Dough' self.sauce = 'Plum Tomato Sauce' self.toppings.append("Shredded Mozzarella Cheese") def cut(self): print 'Cutting the pizza into square slices' class ChicagoStylePepperoni(Pizza): def __init__(self): self.name = 'Chicago Style Pepperoni Cheese Pizza' self.dough = 'Extra Thick Crust Dough' self.sauce = 'Plum Tomato Sauce' self.toppings.append("Shredded Mozzarella Cheese") def cut(self): print 'Cutting the pizza into square slices' class PizzaStore(): def order_pizza(self, name): pizza = self.create_pizza(name) pizza.prepare() pizza.bake() pizza.cut() pizza.box() return pizza def create_pizza(self, name): raise NotImplementedError class NYPizzaStore(PizzaStore): def create_pizza(self, name): if name == 'cheese': return NYStyleCheesePizza() elif name == 'veggie': return NYStyleVeggiePizza() elif name == 'clam': return NYStyleClamPizza() elif name == 'pepperoni': return NYStylePepperoni() else: return None class ChicagoPizzaStore(PizzaStore): def create_pizza(self, name): if name == 'cheese': return ChicagoStyleCheesePizza() elif name == 'veggie': return ChicagoStyleVeggiePizza() elif name == 'clam': return ChicagoStyleClamPizza() elif name == 'pepperoni': return ChicagoStylePepperoni() else: return None nyStore = NYPizzaStore() chicagoStore = ChicagoPizzaStore() pizza = nyStore.order_pizza('cheese') print 'Ethan ordered a ' + pizza.get_name() pizza = chicagoStore.order_pizza('cheese') print 'Hoel ordered a ' + pizza.get_name()
""" Author: Ramiz Raja Created on: 11/01/2020 Problem 3: Rearrange Array Elements Rearrange Array Elements so as to form two number such that their sum is maximum. Return these two numbers. You can assume that all array elements are in the range [0, 9]. The number of digits in both the numbers cannot differ by more than 1. You're not allowed to use any sorting function that Python provides and the expected time complexity is O(nlog(n)). for e.g. [1, 2, 3, 4, 5] The expected answer would be [531, 42]. Another expected answer can be [542, 31]. In scenarios such as these when there are more than one possible answers, return any one. """ def rearrange_digits(input_list): """ Rearrange Array Elements so as to form two number such that their sum is maximum. Args: input_list(list): Input List Returns: (int),(int): Two maximum sums """ n = len(input_list) heap_sort(input_list) decimal_value = 1 n1 = 0 for i in range(0, n, 2): n1 += input_list[i] * decimal_value decimal_value *= 10 decimal_value = 1 n2 = 0 for i in range(1, n, 2): n2 += input_list[i] * decimal_value decimal_value *= 10 return n1, n2 def heap_sort(array): # convert array into max-heap n = len(array) for i in range(n-1, -1, -1): heapify_down(array, i, n) # swap max element at the end and call heapify again repeatedly for i in range(n-1, -1, -1): # Remove max element from heap: involves following 2 steps # 1. swap max element (array[0]) with element at last array[0], array[i] = array[i], array[0] # 2. heapify the root element (array[0] is always the root in a heap) till the i-1 index or n = i size heapify_down(array, 0, i) def heapify_down(array, parent, n): while parent < n: left = 2 * parent + 1 right = 2 * parent + 2 max_index = parent if left < n and array[left] > array[parent]: max_index = left if right < n and array[right] > array[max_index]: max_index = right if max_index != parent: # swap parent with child that has maximum value (max_index child) array[parent], array[max_index] = array[max_index], array[parent] # now check on the child parent = max_index else: # parent is fine so no need to check down break def assert_(expected, actual): assert expected == actual, f"expected={expected}, actual={actual}" print("Pass") def test_function(test_case): output = rearrange_digits(test_case[0]) solution = test_case[1] assert_(expected=sum(solution), actual=sum(output)) def tests(): test_case = ([1, 2, 3, 4, 5], [542, 31]) test_function(test_case) test_case = ([4, 6, 2, 5, 9, 8], [964, 852]) test_function(test_case) # edge cases test_case = ([1, 0, 0, 0, 1], [100, 10]) test_function(test_case) test_case = ([0, 0], [0, 0]) test_function(test_case) test_case = ([], [0, 0]) test_function(test_case) tests()
from turtle import Screen, Turtle from paddle import Paddle from ball import Ball from scoreboard import Scoreboard import time screen = Screen() screen.tracer(0) screen.bgcolor("black") screen.setup(width=800, height=600) screen.title("pong") player_1=screen.textinput("PLAYER DETAILS","PLAYER 1 NAME") player_2=screen.textinput("PLAYER DETAILS","PLAYER 2 NAME") final_winner = Turtle() r_paddle = Paddle((350, 0)) l_paddle = Paddle((-350, 0)) ball = Ball() scoreboard=Scoreboard(player_1,player_2) screen.listen() screen.onkey(r_paddle.go_up, "Up") screen.onkey(r_paddle.go_down, "Down") screen.onkey(l_paddle.go_up, "w") screen.onkey(l_paddle.go_down, "s") game_is_on = True def winner_print(winner): final_winner.penup() final_winner.color("white") final_winner.write("The Winner is "+winner,align="center",font=("Courier",30,"normal")) while game_is_on: time.sleep(ball.move_speed) screen.update() ball.ball_move() if ball.ycor() > 280 or ball.ycor() < -280: ball.bounce_y() if ball.distance(r_paddle) < 50 and ball.xcor() > 330 or ball.distance(l_paddle) < 50 and ball.xcor()<-330: ball.bounce_x() if ball.xcor()>380: ball.reset() scoreboard.update_l_score() if ball.xcor()<-380: ball.reset() scoreboard.update_r_score() if(scoreboard.l_score==11): winner_print(player_1) game_is_on=False if(scoreboard.r_score==11): winner_print(player_2) game_is_on=False screen.exitonclick()
# geringoso.py # Alumna: Julieta Bloise # Ejercicio 1.18: # Usá una iteración sobre el string cadena para agregar la sílaba 'pa', 'pe', 'pi', 'po', o 'pu' según corresponda luego de cada vocal. cadena = input("Escribí la palabra que quieras traducir a geringoso: ") capadepenapa = '' for c in cadena: if c == "a" or c == "A": capadepenapa = capadepenapa + "apa" elif c == "e" or c == "E": capadepenapa = capadepenapa + "epe" elif c == "i" or c == "I": capadepenapa = capadepenapa + "ipi" elif c == "o" or c == "O": capadepenapa = capadepenapa + "opo" elif c == "u" or c == "U": capadepenapa = capadepenapa + "upu" else: capadepenapa = capadepenapa + c print("Palabra en geringoso:", capadepenapa)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 14 20:09:09 2021 @author: bloisejuli """ # bbin.py #%% # Ejercicio 6.15: # Usando lo que hiciste en el Ejercicio 6.14, agregale al archivo bbin.py una función insertar(lista, x) que reciba una lista ordenada # y un elemento. Si el elemento se encuentra en la lista solamente devuelve su posición; si no se encuentra en la lista, lo inserta en # la posición correcta para mantener el orden. En este segundo caso, también debe devolver su posición. def busqueda_binaria(lista, x, verbose = False): '''Búsqueda binaria Precondición: la lista está ordenada Devuelve -1 si x no está en lista; Devuelve p tal que lista[p] == x, si x está en lista ''' if verbose: print(f'[DEBUG] izq |der |medio') pos = -1 # Inicializo respuesta, el valor no fue encontrado izq = 0 der = len(lista) - 1 while izq <= der: medio = (izq + der) // 2 if verbose: print(f'[DEBUG] {izq:3d} |{der:>3d} |{medio:3d}') if lista[medio] == x: pos = medio # elemento encontrado! if lista[medio] > x: der = medio - 1 # descarto mitad derecha else: # if lista[medio] < x: izq = medio + 1 # descarto mitad izquierda return pos def donde_insertar(lista, x): i = 0 try: while lista[i] < x: i += 1 except IndexError: i = i return i def insertar(lista, x): pos = busqueda_binaria(lista,x) if (busqueda_binaria(lista, x) == -1): pos = donde_insertar(lista,x) lista.insert(pos, x) return pos
length, width = 18, 7 def find_perimeter(l, w): return (l * 2) + (w * 2) def find_area(l, w): return l * w perimeter = find_perimeter(length, width) area = find_area(length, width) print("The perimeter is: {}".format(perimeter)) print("The area is: {}".format(area))
# Uses python3 def calc_fib(n): if n==0: return 0 if n==1: return 1 a = [0,1] for i in range(2,n+1): a.append(a[i-1]+a[i-2]) return a[-1] n = int(input()) print(calc_fib(n))
#Recurssive function for multiples of three def f(n): 'Please enter a positive number. n > 0.' if n > 0: if n == 1: return 3 else: return f(n-1) + 3 else: print('Please introduce a positive number')
#Local vs Global variable print('The global variable is x = 5 and the x inside the function is the local variable. Try to run the function with divide(x) and the program will automatically consider x = 5 as the value of x') x = 5 def divide(x): print(x/2)
#Function that tells the strength of an acid def ph_level(x): if x>=0 and x<=4: print('It is a strong acid.') if x>=5 and x<=6: print('It is a weak acid.') if x==7: print('It is neutral') if x>=8 and x<=9: print('It is a weak base') if x>=10 and x<=14: print('It is a strong base') else: print("Enter a number between 0 and 14")
#Multiplying a number by 2 print('Enter even_number(n) for multiplying 2 times the number n') def even_number(x): y = x * 2 print(y)
#Reviewing properties of dictionnaries Month_of_Year={'January': 1, 'February' : 2, 'March': 3, 'April' : 4} M2={'May': 5, 'June' : 6,} #Take april out of the dictionary Month_of_Year.pop('April') print(Month_of_Year) #Add M2 to Month_of_Year Month_of_Year.update(M2) print(Month_of_Year) #Print strings in dictionary Month_of_Year.keys() print(Month_of_Year.keys()) #Print values in dictionary Month_of_Year.values() print(Month_of_Year.values())
#try-except exercise try: while True: x = input('Enter your area-code: ') y = int(x) print('Your code-area is {}'.format(y)) break except: print('Only numbers accepted 0-9')
# 扁平化的处理嵌套型序列 # 例如将嵌套的list解析成单个的元素,忽略掉字符串 from collections import Iterable def flatten(items, ignore_type = (str,bytes)): for x in items: if isinstance(x, Iterable) and not isinstance(x,ignore_type): yield from flatten(x) else: yield x items = [1,2, [3,4, [5, 6],8],10] for i in flatten(items): print(i)
# 避免出现重复的属性方法 # 在初始化的时候会被调用,所以要用到self def type_property(name,expected_type): storage_name='_'+name @property def prop(self): print('ok') return getattr(self,storage_name) @prop.setter def prop(self,value): print('ok1') if not isinstance(value,expected_type): raise TypeError('{} must be a {}'.format(name,expected_type)) setattr(self,storage_name,value) return prop class Person: name=type_property('name',str) age=type_property('age',int) def __init__(self,name,age): self.name=name self.age=age p=Person('A',10) print(p.name)
# 对固定大小的文件进行迭代 from functools import partial RECORD_SIZE = 32 with open('data.bin','rb') as f: records = iter(partial(f.read,RECORD_SIZE),b'') for i in records: print(i)
# 找出当月的日期范围 from datetime import datetime,date,timedelta import calendar def get_month_range(start_date = None): if start_date is None: start_date = date.today().replace(day = 1) _,dates_in_month = calendar.monthrange(year=start_date.year, month= start_date.month) end_date = start_date + timedelta(days= dates_in_month) return (start_date,end_date) a_day = timedelta(days = 1) first_day ,last_day = get_month_range() while first_day < last_day: print(first_day) first_day +=a_day
# 使用生成器作为线程的替代 # 即协程或者用户级线程,绿色线程 def foo(): while True: x = yield print("value:",x) g = foo() # g是一个生成器 # 程序运行到yield就停住了,等待下一个next g.send(None) # 我们给yield发送值1,然后这个值被赋值给了x,并且打印出来,然后继续下一次循环停在yield处 g.send(2) # 同上 next(g) # 没有给x赋值,执行print语句,打印出None,继续循环停在yield处 # 错误提示:不能传递一个非空值给一个未启动的生成器。 # ####关键点: #也就是说,在一个生成器函数未启动之前,是不能传递数值进去。必须先传递一个None进去或者调用一次next(g)方法,才能进行传值操作。至于为什么要先传递一个None进去,可以看一下官方说法。
# 避免死锁 # 如果一个线程需要获取不止一把锁,则可能会出现死锁 # 解决方案:给每一个锁分配一个数字序号,并且在获取多个锁的时候,只能按升序的方式来获取 import threading from contextlib import contextmanager _local = threading.local() @contextmanager def acquire(*locks): locks = sorted(locks,key=lambda x:id(x)) acquired = getattr(_local,'acquired',[]) if acquired and max(id(lock) for lock in acquired) >= id(locks[0]): raise RuntimeError('Lock Order Violation') acquired.extend(locks) try: _local.acquired=acquired except Exception as E: print(E) try: for lock in locks: lock.acquire() yield finally: for lock in reversed(locks): lock.release() del acquired[-len(locks):] x_lock=threading.Lock() y_lock=threading.Lock() def thread_1(): while True: with acquire(x_lock,y_lock): print('Thread-1') def thread_2(): while True: with acquire(y_lock,x_lock): print('Thread-2') t1=threading.Thread(target=thread_1) t1.daemon=True t1.start() t2=threading.Thread(target=thread_2) t2.daemon=True t2.start()
# 从序列中随机出元素 import random values = [1,2,3,4,5,6] print(random.choice(values)) # 取出N个元素 print(random.sample(values,2)) # 打乱元素的顺序,原地打乱 random.shuffle(values) print(values) # 产生随机数 print(random.randint(0,10)) # 产生0到1之间的浮点数 print(random.random()) # 产生N个随机byte位表示的整数 print(random.getrandbits(200)) # random模块采用的是确定性算法,即伪随机算法,梅森旋转 # 对于相同的初始序列,产生的随机状态几乎相同,不能用于蒙特卡洛模拟,产生的随机数与seed相关 random.seed(0) print(random.getrandbits(3)) print(random.getrandbits(3)) random.seed(0) print(random.getrandbits(3)) print(random.getrandbits(3)) # 如果要产生加密安全的随机字节序列 # 使用ssl.RANDOM_bytes()
"""Calculator >>> calc("+ 1 2") # 1 + 2 3 >>> calc("* 2 + 1 2") # 2 * (1 + 2) 6 >>> calc("+ 9 * 2 3") # 9 + (2 * 3) 15 Let's make sure we have non-commutative operators working: >>> calc("- 1 2") # 1 - 2 -1 >>> calc("- 9 * 2 3") # 9 - (2 * 3) 3 >>> calc("/ 6 - 4 2") # 6 / (4 - 2) 3 """ def calc(s): """Evaluate expression.""" # Convert string to list of tokens with operators and numbers # For example: "+ 1 2" -> ["+", "1", "2"] tokens = s.split() # Start with the right-most number num2 = int(tokens.pop()) while tokens: # Grab the right-most number num1 = int(tokens.pop()) # Grab the right-most operator operator = tokens.pop() # Do math using the result as the right-hand value (num2) for next time if operator == "+": num2 = num1 + num2 elif operator == "-": num2 = num1 - num2 elif operator == "*": num2 = num1 * num2 elif operator == "/": num2 = num1 / num2 # When token list is empty, num2 is the result of last operation return num2 if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print "\n*** ALL TESTS PASSED; WELL-CALCULATED! ***\n"
import re def parse(s): s = s.strip() s = s.strip("{") s = s.strip("}") return set(re.split("[ \t,]+",s)) def output(s): return "{" + ", ".join(s) + "}" with open("rosalind_seto.txt","r") as f: n = int(f.readline()) s1 = parse(f.readline()) s2 = parse(f.readline()) print(output(s1.union(s2))) print(output(s1.intersection(s2))) print(output(s1.difference(s2))) print(output(s2.difference(s1))) x = set(map(lambda x:str(x),range(1,n+1))) print(output(x.difference(s1))) print(output(x.difference(s2)))
# age=25 # # count=0 # while count<=5: # guest = int(input('输入年龄:')) # count+=1 # # if guest>age: # print('大了') # elif guest<age: # print('小了') # else: # print('正好') # break # for i in range(0,100,2): print(i)
#!/usr/bin/python import sys crypt = [] special=["35","97","37","74","99","38","37"] for i in range(len(special)): special[i]=int(special[i]) special_index=0 password=list(sys.argv[6]) length=len(password) key_index=1 for i in range(length): password[i] = ord(password[i]) for i in range(length): if key_index == 6: key_index=1 if special_index == 7: special_index=0 crypt.append(password[i]+int(sys.argv[key_index])) crypt.append(special[special_index]) key_index += 1 special_index += 1 print('\n\nCrypt > ',end="") for j in range(length*2): print (chr(crypt[j]),end="") print('\n')
def area(radius): return 3.14*(radius**2) r=int(input("Enter radius of circle :")) print(f"Area of Circle is ",area(r))
# I take no responsibility for the correctness of the test cases. # Test cases may included goals unreachable from start point, in which case the result for each search is an empty list # ~ST let me know if any of the test cases are wrong :3 #import Assignment2 import PESU-MI_0110_0285_0328 file = open("mi_test_cases_up.txt", "r") test_num = 1 failed = [] file.readline() file.readline() file.readline() for i in range(10): file.readline() size = int(file.readline()) file.readline() cost = [list(map(int, file.readline().split())) for x in range(size)] for j in range(100): file.readline() file.readline() file.readline() heuristic = list(map(int, file.readline().split())) file.readline() start_point = int(file.readline()) file.readline() goals = list(map(int, file.readline().split())) file.readline() correct_answer = [list(map(int, s.split())) for s in file.readline().split(",")] correct_answer.pop() your_answer = Assignment2.tri_traversal(cost, heuristic, start_point, goals) if(your_answer == correct_answer): print("Test",test_num,": PASSED!") else: print("Test",test_num,": FAILED!") print("Your answer :", your_answer) print("Correct answer :", correct_answer) failed.append(test_num) test_num += 1 file.readline() print("================================================================") if(not failed): print("ALL TEST CASES PASSED!") else: print("ono FOLLOWING TEST CASES FAILED!") print(*failed)
from utils import time_it import sys primes = [2, 3] class PrimeListTooShortException(Exception): def __init__(self): self.msg = 'Prime list is not long enough to test this number' def is_prime(p, prime_list=primes): """ :param p: Number to be tested :param prime_list: lista de primos a usar como base :return: True if the number is prime, False otherwise >>> is_prime(1811) True >>> is_prime(1813) False """ if p in prime_list: return True limite_de_teste = root_limit(p) for i in prime_list: if p % i == 0: return False if i > limite_de_teste: return True raise PrimeListTooShortException() def root_limit(p): return int(p**.5) #@time_it() def next_prime(prime_list=primes): if not prime_list: prime_list = [2, 3] last = prime_list[-1] while True: last += 2 if is_prime(last, prime_list): prime_list.append(last) return last def print_primes(qtd): [print(f"{next_prime(primes)}, ","\n" if i%20==0 else " ", end='') for i in range(qtd)] if __name__=='__main__': print_primes(50_000)
# Uses python3 import sys def optimal_weight(W,n,w,value_dic): if (W==0) or (n==0): return 0 if (W,n) in value_dic: return value_dic[(W,n)] for i in range(1,n+1): #金条数组 for j in range(1,W+1): #总重量 #print ("kkk") value_dic[(j,i)]=optimal_weight(j,i-1,w,value_dic) if w[i-1]<=j: value=optimal_weight(j-w[i-1],i-1,w,value_dic)+w[i-1] if value_dic[(j,i)]<value: value_dic[(j,i)]=value return value_dic[(W,n)] if __name__ == '__main__': input = sys.stdin.read() W, n, *w = list(map(int, input.split())) value_dic={} #print (W,n) print(optimal_weight(W, n,w,value_dic)) #print (value_dic.keys())
#Uses python3 import sys import math import heapq def dijkstra(adj,cost,s): dist=[[100000,1] for i in range(len(adj))] #set distance to infinite,count to 1 prev=[-1]*len(adj) #parents dist[s][0]=0 #first vertex pair=[] for i,j in enumerate(dist): pair.append((j[0],[i,j[1]])) #the entry in heap has this properities (distance,[index,count]) heapq.heapify(pair) #construct the heap while pair: want=False #not sure whether to pop the first one #becaue it might be the old distance that we haven't deleted while not want: #if we don't need that x=heapq.heappop(pair) #(distance,[index,count]) pop first if x[1][1]==dist[x[1][0]][1]: #if the count is the same, we need that node want=True if pair==[]: #if the heap is already empty break if want==False: break u=x[1][0] #the vertex we poped print "pop=%d" %u #now I get the right vertex to pop for i,j in enumerate(adj[u]): #i is the index, j is the vertex it connected if dist[j][0]>dist[u][0]+cost[u][i]: #cost[u][i] is the length between u and v dist[j][0]=dist[u][0]+cost[u][i] #update distance dist[j][1]+=1 #add the count prev[j]=u #add parents new_entry=(dist[j][0],[j,dist[j][1]]) #put new distance information heapq.heappush(pair,new_entry) #put into the heap return dist,prev def minimum_distance(x, y): adj=[] cost=[] for i in range(len(x)): adj.append([j for j in range(len(x)) if j!=i]) cost.append([((x[j]-x[i])**2+(y[j]-y[i])**2)**0.5 for j in range(len(x)) if j!=i]) #print adj,cost dist,prev=dijkstra(adj,cost,2) result=0 for i in dist: result+=i[0] print prev print dist return result if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) n = data[0] x = data[1::2] y = data[2::2] #print(x,y) print("{0:.9f}".format(minimum_distance(x, y)))
""" Handling missing values Generally, there are two strategies involved: 1. Masking :It involve appropriation of one bit in the data representation to locally indicate the null status of a value. 2. Choosing a sentinel value that indicate a missing value like putting -999 or anything else. """ import numpy as np import pandas as pd val_o = np.array([1,None,2,3,45,6]) val_o """ This dtype object means that the best common type representation NumPy could infer for the contents of the array is that they are python objects Output array([1, None, 2, 3, 45, 6], dtype=object) """ """ Use of python object in an array also means that if you perform aggregations like sum() or min() across an array with a None value, you will generally get error val_o.sum() """ val_f = np.array([1,np.nan,2,3,45,6]) val_f # print the array and notice the difference that this time an array type is create not an object val_f.sum() """ output nan """ """ Handling missing values in Pandas NaN and None both have their place, and pandas is built to handle the two of the them interchanageably Operating on Null values There are several useful methods for detecting, removing, and replacing null values in Pandas data structures. They are: 1. isnull() : Generate a boolean masking indicating missing values 2. notnull(): opposite of isnull() 3. dropna() : Return a filtered version of the data 4. fillna() : Return a copy of the data with missing values filled or imputed Detecting Null values: Pandas data structure have two useful methods for detecting null data: 1. isnull() 2. notnull() """ data_miss = pd.Series([1,np.nan,2 ,3,np.nan,5]) data_miss.isnull() """ Output: 0 False 1 True 2 False 3 False 4 True 5 False dtype: bool """ data_miss.notnull() """ Output: 0 True 1 False 2 True 3 True 4 False 5 True dtype: bool """ """ Dropping null values """ data_miss.dropna() """ Output: 0 1.0 2 2.0 3 3.0 5 5.0 dtype: float64 """ """ Dropping columns in a matrix """ df=pd.DataFrame([[np.nan,1,2],[2,3,4],[3,np.nan,5]]) df.dropna() # drop all the rows containing null values df.dropna(axis=1) # drop all the columns containing null values """ This will drop all the columns if any value present in the column is null and thus it leads to loss of information. The default is how="any", such that any row or column containing null value will be dropped. We can specify how="all" , which will only drop rows or columns if all are null values. """ df.dropna(how="all") """ Output 0 1 2 0 NaN 1.0 2 1 2.0 3.0 4 2 3.0 NaN 5 """ """ Filling null values fillna() method return copy of the array with the null values replaced """ df.fillna(0) """ Outout--> Null values replaced by zero, we can replace it with any other value depending on circumstances 0 1 2 0 0.0 1.0 2 1 2.0 3.0 4 2 3.0 0.0 5 """ """ Other method: Forward fill --> to propagate the previous value forward : df.fillna(method='ffill') Back fill --> to propagate the next values backward : df.fillna(method='bfill') """
#importing modules (pygame,random,randint,time,os) import pygame ,random from random import randint #The randint() method returns an integer number selected element from the specified range import time import os #The OS module in python provides functions for interacting with the operating system. #initialize all imported pygame modules pygame.init() #dimensions of the window width=1366 height=768 pause_music=0 #Input_details name=input("Enter your Name:-") num=input("Enter your Number with country Code.For ex:- 9177******76:-") print("Loading Please Wait",end="") #time_delay loop for x in range(15): time.sleep(0.2) print(". ",end="") clock=pygame.time.Clock() #used to limit the runtime speed of the game game_screen=pygame.display.set_mode((width,height),pygame.FULLSCREEN) #for full screen #game_screen=pygame.display.set_mode((width,height)) #for screen of mentioned dimensions pygame.display.set_caption("The Hungry Snake ") icon=pygame.image.load("images/bg_imgs/icon.png") pygame.display.set_icon(icon) pygame.display.update() #Load Images #snake head Green_head = pygame.image.load('images/snake/Green_head.png') Orange_head = pygame.image.load('images/snake/Orange_head.png') snake_head_1 = Green_head snake_head_2 = Orange_head #snake food(fruits) Apple = pygame.image.load('images/food/Apple.png') green_apple = pygame.image.load('images/food/green_apple.png') pine_apple = pygame.image.load('images/food/pine_apple.png') blueberry = pygame.image.load('images/food/blueberry.png') strawberry = pygame.image.load('images/food/strawberry.png') #snake food(eggs) Green_egg = pygame.image.load('images/food/Green_egg.png') red_egg = pygame.image.load('images/food/red_egg.png') yellow_egg = pygame.image.load('images/food/yellow_egg.png') #snake food(humans) abhay_food = pygame.image.load('images/food/abhay_food.png') arjun_food = pygame.image.load('images/food/arjun_food.png') Ravi_food = pygame.image.load('images/food/Ravi_food.png') #About pics about_pic=pygame.image.load("images/bg_imgs/about_pic.jpg") LPU_logo=pygame.image.load("images/bg_imgs/LPU-logo.png") ravi=pygame.image.load("images/bg_imgs/ravi.jpg") abhay=pygame.image.load("images/bg_imgs/abhay.jpg") arjun=pygame.image.load("images/bg_imgs/arjun.jpg") #back_ground imgs welcome=pygame.image.load("images/bg_imgs/welcome.jpg") menu_pic=pygame.image.load("images/bg_imgs/menu_pic.jpg") options_pic=pygame.image.load("images/bg_imgs/options_pic.jpg") opening_pic=pygame.image.load("images/bg_imgs/opening_pic.jpg") water = pygame.image.load('images/bg_imgs/water.jpg') game_over_1 = pygame.image.load('images/bg_imgs/game_over_1.jpg') game_over_2 = pygame.image.load('images/bg_imgs/game_over_2.jpg') snake_right = pygame.image.load('images/bg_imgs/snake_right.png') snake_left = pygame.image.load('images/bg_imgs/snake_left.png') #assigning snake food food_pic=Ravi_food#Ravi_food #if u want to change the food then just replace the assigned food pic with any other food pic mentioned above. #colors black=(10,10,10) white=(250,250,250) red= (255,0,0) light_red = (255, 49, 16) b_red=(240,0,0) green=(0,200,0) b_green=(0,230,0) blue=(0,0,200) grey=(50,50,50) yellow=(255,192,0) light_yellow = (255, 255, 0) purple=(43,3,132) light_purple=(251,8,224) sky_blue=(54,250,234) back_color=sky_blue#background color of 2 players mode #fonts font = pygame.font.SysFont("comicsansms", 50) smallfont = pygame.font.SysFont("comicsansms", 25) bigfont = pygame.font.SysFont("comicsansms", 85) #variables FPS = 12 #frames per second block_size = 30 food_size = 32 food_count = 1 direction = "right" foods = set([]) score=0 Score="" #music #pygame.mixer is a module for loading and playing sounds pygame.mixer.init()#initialize the mixer modules class Snake: def __init__(self, pos, vel, angle, image, color=green): self.pos = pos self.vel = vel self.angle = angle self.img = image self.list = [] self.lenght = 1 self.head = self.img self.color = color def score_display(self, pos): score(self.lenght-1, pos, self.color) def key_event(self, direction): self.angle = direction def eat(self): for food in foods: if self.pos[0] > food.pos[0] and self.pos[0] < food.pos[0] + food_size or self.pos[0] + block_size > food.pos[0] and self.pos[0] < food.pos[0] + food_size: if self.pos[1] > food.pos[1] and self.pos[1] < food.pos[1] + food.size or self.pos[1] + block_size > food.pos[1] and self.pos[1] < food.pos[1] + food.size: foods.remove(food) foods.add(randFoodGen()) self.lenght += 1 def update(self): gameOver = False if (self.angle == "right") and (self.vel[0] != -block_size): self.vel[0] = +block_size self.vel[1] = 0 self.head = pygame.transform.rotate(self.img, 270) if (self.angle == "left") and (self.vel[0] != block_size): self.vel[0] = -block_size self.vel[1] = 0 self.head = pygame.transform.rotate(self.img, 90) if (self.angle == "up") and (self.vel[1] != block_size): self.head = self.img self.vel[1] = -block_size self.vel[0] = 0 if (self.angle == "down") and (self.vel[1] != -block_size): self.vel[1] = +block_size self.vel[0] = 0 self.head = pygame.transform.rotate(self.img, 180) # update movement self.pos[0] += self.vel[0] self.pos[1] += self.vel[1] # build the snake snakeHead = [] snakeHead.append(self.pos[0]) snakeHead.append(self.pos[1]) self.list.append(snakeHead) if len(self.list) > self.lenght: del self.list[0] if snakeHead in self.list[:-1]: gameOver = True # draw the snake for XnY in self.list[:-1]: pygame.draw.rect(game_screen, self.color, [XnY[0], XnY[1], block_size, block_size]) # draw the snake's head game_screen.blit(self.head, (self.list[-1][0], self.list[-1][1])) # check if out of boundries if self.pos[0] < 0 or self.pos[0] >= width or self.pos[1] < 0 or self.pos[1] >= height: gameOver = True return gameOver class Food: def __init__(self, pos, size, image = None): self.pos = pos self.img = image self.size = size def draw(self): game_screen.blit(self.img, self.pos) #to calculate score def score(score, pos, color): text = smallfont.render("Score: "+str(score), True, color) game_screen.blit(text, pos) #to display text def text_screen(text,color,x,y): screen_text= font.render(text,True,color) game_screen.blit(screen_text,[x,y]) #display snake def plot_snake(game_screen,color,snk_list,snake_size): for x,y in snk_list: pygame.draw.circle(game_screen,yellow,(x ,y),snake_size) #Message displaying for buttons def message_display(text,x,y,fs): largeText = pygame.font.Font('freesansbold.ttf',fs) TextSurf, TextRect = text_objects(text, largeText) TextRect.center = (x,y) game_screen.blit(TextSurf, TextRect) def text_objects(text, font): textSurface = font.render(text, True,white) return textSurface, textSurface.get_rect() #Message displaying for field def message_display1(text,x,y,fs,c): largeText = pygame.font.Font('freesansbold.ttf',fs) TextSurf, TextRect = text_objects1(text, largeText) TextRect.center = (x,y) game_screen.blit(TextSurf, TextRect) def text_objects1(text, font,c): textSurface = font.render(text, True,c) return textSurface, textSurface.get_rect() def game_controls(): controlls = True game_screen.fill(white) message_screen("Controls", green, -120, "large") message_screen("Green movement: Arrow keys", green, -30, "small") message_screen("Purple movement: W, A, S, D keys", purple, 10, "small") message_screen("Pause: P", black, 60, "small") while controlls: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: controlls = False elif event.key == pygame.K_ESCAPE: exit() controlls = button("Main Menu", (width/2-70, height-150, 140, 50), yellow, light_yellow, action = "switch") button("exit", (width/2+120, height-150, 100, 50), red, light_red, action = "quit") clock.tick(30) pygame.display.update() def text_objects10(text, color, size = "small"): #change if size == "small": textSurface = smallfont.render(text, True, color) elif size == "medium": textSurface = font.render(text, True, color) elif size == "large": textSurface = bigfont.render(text, True, color) return textSurface, textSurface.get_rect() def text_to_button(msg, color, pos, size = "small"): text_surf, text_rect = text_objects10(msg, color, size) #change text_rect.center = (pos[0]+(pos[2]/2), pos[1]+(pos[3]/2)) game_screen.blit(text_surf, text_rect) def message_screen(msg, color, y_displace=0, size = "small"): text_surf, text_rect = text_objects10(msg, color, size) text_rect.center = (width/2), (height/2)+y_displace game_screen.blit(text_surf, text_rect) def randFoodGen(): new_food = Food([round(random.randrange(food_size, width-food_size)/10)*10, round(random.randrange(food_size, height-food_size)/10)*10], food_size, food_pic) return new_food #for mute and unmute def button2(text,xmouse,ymouse,x,y,width,height,i,a,fs): #mouse pos mouse=pygame.mouse.get_pos() click=pygame.mouse.get_pressed() if x+width>xmouse>x and y+height>ymouse>y: pygame.draw.rect(game_screen,a,[x-2.5,y-2.5,width+5,height+5]) if pygame.mouse.get_pressed()==(1,0,0): return True else: pygame.draw.rect(game_screen,i,[x,y,width,height]) message_display(text,(x+width+x)/2,(y+height+y)/2,fs) def music(): flag=True while flag==True: for event in pygame.event.get(): if event.type==pygame.QUIT: exit() if event.type== pygame.KEYDOWN: if event.key== pygame.K_ESCAPE: exit() mouse=pygame.mouse.get_pos()#get the mouse cursor position click=pygame.mouse.get_pressed()#get the state of the mouse buttons game_screen.blit(options_pic,(0,0))#draw one image onto another if button2("Stop Background Music",mouse[0],mouse[1],(width/2-150),200,300,70,green,purple,25): pygame.mixer.music.pause() pause_music=1 if button2("Play Background Music",mouse[0],mouse[1],(width/2-150),400,300,70,green,purple,25): pygame.mixer.music.unpause() pause_music=0 button("Back",mouse[0],mouse[1],0,10,200,50,red,b_red,30,8) pygame.display.update() def about(): flag=True while flag==True: for event in pygame.event.get(): if event.type==pygame.QUIT: exit() if event.type== pygame.KEYDOWN: if event.key== pygame.K_ESCAPE: exit() mouse=pygame.mouse.get_pos() click=pygame.mouse.get_pressed() game_screen.blit(about_pic,(0,0)) game_screen.blit(LPU_logo,(996,0)) game_screen.blit(ravi,(280,420)) game_screen.blit(arjun,(280,530)) game_screen.blit(abhay,(280,630)) button("Back",mouse[0],mouse[1],0,10,200,50,red,light_purple,30,8) pygame.display.update() #Options Menu: def options(): flag=True while flag==True: for event in pygame.event.get(): if event.type==pygame.QUIT: exit() if event.type== pygame.KEYDOWN: if event.key== pygame.K_ESCAPE: exit() #mouse pos mouse=pygame.mouse.get_pos() click=pygame.mouse.get_pressed() game_screen.blit(options_pic,(0,0)) #Single player button button("Single Player",mouse[0],mouse[1],(width/2-150),250,300,50,green,b_green,30,5) #2 player button button("2 Players",mouse[0],mouse[1],(width/2)-150,350,300,50,green,b_green,30,6) button("Back",mouse[0],mouse[1],0,650,200,50,red,light_purple,30,8) pygame.display.update() def settings(): flag=True while flag==True: for event in pygame.event.get():#get events from the queue if event.type==pygame.QUIT: exit() if event.type== pygame.KEYDOWN: if event.key== pygame.K_ESCAPE: exit() mouse=pygame.mouse.get_pos() click=pygame.mouse.get_pressed() game_screen.blit(options_pic,(0,0)) button("Background music",mouse[0],mouse[1],(width/2)-250,250,500,70,green,purple,30,9) button("Back",mouse[0],mouse[1],0,650,200,50,red,purple,30,8) pygame.display.update() #Buttons: def button(text,xmouse,ymouse,x,y,width,height,i,a,fs,b): if x+width>xmouse>x and y+height>ymouse>y: pygame.draw.rect(game_screen,a,[x-2.5,y-2.5,width+5,height+5]) if pygame.mouse.get_pressed()==(1,0,0): if b==1: options() elif b==2: settings() elif b==3: about() elif b==4: exit() elif b==5: play_single() elif b==6: play_multi() elif b==8: main() elif b==9: music() else :return True else: pygame.draw.rect(game_screen,i,[x,y,width,height]) message_display(text,(x+width+x)/2,(y+height+y)/2,fs) def play_single(): pygame.mixer.music.load("music/single_player.mp3") pygame.mixer.music.play() exit_game = False game_over = False snake_x=600 snake_y=500 velocity_x=0 velocity_y=0 snake_size=20 score=0 init_velocity=15 food_x=random.randint(20,width/2) food_y=random.randint(20,height/2) score=0 snk_list=[] snk_length=1 fps=30 while not exit_game: if game_over: for event in pygame.event.get(): if event.type==pygame.QUIT: exit() if event.type== pygame.KEYDOWN: if event.key== pygame.K_RETURN: exit() mouse=pygame.mouse.get_pos() click=pygame.mouse.get_pressed() game_screen.blit(game_over_1,(0,0)) global Score Score=str(score) text_screen(Score,black,790,280) button("Back",mouse[0],mouse[1],1166,650,200,50,red,light_purple,30,1) button("Restart",mouse[0],mouse[1],600,650,200,50,(255,192,0),light_purple,30,5) button("main",mouse[0],mouse[1],0,650,200,50,(85,239,22),light_purple,30,8) pygame.display.update() else: for event in pygame.event.get(): # print(event) if event.type==pygame.QUIT: exit_game=True if event.type==pygame.KEYDOWN: if event.key==pygame.K_RIGHT: velocity_x=init_velocity velocity_y=0 if event.key==pygame.K_LEFT: velocity_x=-init_velocity velocity_y=0 if event.key==pygame.K_UP: velocity_y=-init_velocity velocity_x=0 if event.key==pygame.K_DOWN: velocity_y=init_velocity velocity_x=0 if event.key==pygame.K_q: score+=10 snk_length+=5 if event.key==pygame.K_SPACE: fps+=10 snake_x=snake_x+velocity_x snake_y=snake_y+velocity_y if abs(snake_x-food_x)<15 and abs(snake_y-food_y)<15: # pygame.mixer.music.load("music/Beep.mp3") # crash_sound = pygame.mixer.Sound("music/Beep.mp3") # pygame.mixer.Sound.play(crash_sound) score+=10 food_x=random.randint(5,width-5) food_y=random.randint(5,height-5) snk_length+=5 game_screen.blit(water,(0,0)) text_screen('Score: '+str(score),red ,5,3) pygame.draw.circle(game_screen,red,(food_x ,food_y),15) head=[] head.append(snake_x) head.append(snake_y) snk_list.append(head) if len(snk_list)>snk_length: del snk_list[0] if head in snk_list[:-1]: game_over=True pygame.mixer.music.load('music/Crash.mp3') pygame.mixer.music.play() if snake_x<0 or snake_x>width or snake_y<0 or snake_y>height: game_over=True pygame.mixer.music.load('music/Crash.mp3') pygame.mixer.music.play() plot_snake(game_screen,yellow,snk_list,snake_size) pygame.display.update() clock.tick(fps) pygame.quit() quit() def play_multi(): pygame.mixer.music.load("music/multi_player.mp3") pygame.mixer.music.play() ravi = True while ravi: l=False s=False time=3000 mouse=pygame.mouse.get_pos() for event in pygame.event.get(): if event.type == pygame.QUIT: quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: ravi = False elif event.key == pygame.K_ESCAPE: quit() pygame.display.update() gameLoop() def gameLoop(): check=0 global food_count gameExit = False gameOver = False while food_count > len(foods): food = randFoodGen() foods.add(food) snake1 = Snake([((width/2-5*block_size)/10)*10, (height/20)*10], [0, 0], None, snake_head_1) snake2 = Snake([((width/2-5*block_size)/10)*10, (height/20)*10], [0, 0], None, snake_head_2, red) while not gameExit: if food_count > len(foods): food = randFoodGen() foods.add(food) elif food_count < len(foods): foods.pop() if gameOver == True: check=10 for event in pygame.event.get(): if event.type==pygame.QUIT: exit() if event.type== pygame.KEYDOWN: if event.key== pygame.K_RETURN: exit() mouse=pygame.mouse.get_pos() click=pygame.mouse.get_pressed() game_screen.blit(game_over_2,(0,0)) button("Back",mouse[0],mouse[1],1166,650,200,50,red,light_purple,30,1) button("Restart",mouse[0],mouse[1],600,650,200,50,(255,192,0),light_purple,30,6) button("main",mouse[0],mouse[1],0,650,200,50,(85,239,22),light_purple,30,8) pygame.display.update() flag2=10 for event in pygame.event.get(): # Events LEAD if event.type == pygame.QUIT: gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: # Snake1 snake1.key_event("left") if event.key == pygame.K_RIGHT: snake1.key_event("right") if event.key == pygame.K_DOWN: snake1.key_event("down") if event.key == pygame.K_UP: snake1.key_event("up") if event.key == pygame.K_a: # Snake2 snake2.key_event("left") if event.key == pygame.K_d: snake2.key_event("right") if event.key == pygame.K_s: snake2.key_event("down") if event.key == pygame.K_w: snake2.key_event("up") if event.key == pygame.K_e: food_count += 1 if event.key == pygame.K_q: food_count = 100 if check==0: game_screen.fill(back_color) #game_screen.blit(game_over_2,(0,0)) for food in foods: food.draw() if snake1.update() or snake2.update(): gameOver = True pygame.mixer.music.load('music/Crash.mp3') pygame.mixer.music.play() snake1.score_display([50, 2]) snake1.eat() snake2.score_display([width-150, 2]) snake2.eat() pygame.display.update()#Update portions of the screen for software displays clock.tick(FPS) exit() def intro(): pygame.mixer.music.load("music/intro.mpeg") pygame.mixer.music.play(-1) time=pygame.time.get_ticks() while pygame.time.get_ticks()-time<2500: game_screen.blit(opening_pic,(0,0)) pygame.display.update() while True: game_screen.blit(welcome,(0,0)) game_screen.blit(snake_left, (10, 450)) game_screen.blit(snake_right, (1096, 450)) text_screen(name,(211,84,0),600,320) text_screen('Press Enter To Play ',(108,52,131),420,450) for event in pygame.event.get(): if event.type==pygame.QUIT: exit() if event.type==pygame.KEYDOWN: if event.key==pygame.K_RETURN: return pygame.display.update() #Main Menu def main(): if pause_music==0: pygame.mixer.music.load("music/intro.mpeg") pygame.mixer.music.play(-1) menu=True while menu: for event in pygame.event.get(): if event.type==pygame.QUIT: exit() if event.type== pygame.KEYDOWN: if event.key== pygame.K_RETURN: exit() #mouse pos mouse=pygame.mouse.get_pos() click=pygame.mouse.get_pressed() game_screen.blit(menu_pic,(0,0)) button("Start Game",mouse[0],mouse[1],(width/2-200),120,400,80,(85,239,22),light_purple,60,1) button("Settings",mouse[0],mouse[1],(width/2-200),240,400,80,(255,192,0),light_purple,60,2) button("About",mouse[0],mouse[1],(width/2-200),370,400,80,(136,80,9),light_purple,60,3) button("Exit",mouse[0],mouse[1],(width/2-200),500,400,80,red,light_purple,60,4) pygame.display.update() def exit(): twiliox() pygame.quit() quit() def twiliox(): from twilio.rest import Client x = #account_sid y = #auth_token client = Client(x, y) body_msg="Hi "+name+".Your Score is : "+Score from_whatsapp_number='whatsapp:+14155238886', to_whatsapp_number='whatsapp:+'+num message = client.messages.create(body=body_msg, from_=from_whatsapp_number, to=to_whatsapp_number) intro() main()
''' Given a binary tree, find its maximum depth. The maximum depth of a binary tree is the number of nodes along the longest path from the root node down to the farthest leaf node. ''' ### COMPARE WITH crackingCode : 4.1_isBalancedBinaryTree class Node: def __init__(self,item): self.val=item self.left=None self.right=None class Solution(): def maxDepth(self, A): if A is None: return 0 # go down until the node is None (i.e. base condition) return 1 + max(self.maxDepth(A.left), self.maxDepth(A.right)) bt = Node(5) bt.left=Node(3) bt.right=Node(2) bt.left.left=Node(1) bt.left.left.right=Node(7) sol=Solution() print(sol.maxDepth(bt)) ''' # crackingCode : 4.1_isBalancedBinaryTree class Solution(): def is_balanced(self, root): if self.checkHeight(root) == -1: return False else: return True def checkHeight(self,node): # None tree is balanced if node is None: return 0 leftHeight=self.checkHeight(node.left) #if the left subtree is not balanced, then the whole tree is not balanced if leftHeight == -1: return -1 rightHeight=self.checkHeight(node.right) # if the left subtree is not balanced, then the whole tree is not balanced if rightHeight == -1: return -1 #if the difference in heights is greater than 1, the whole tree is not balanced heightDiff= leftHeight-rightHeight if abs(heightDiff) > 1: return -1 else : return max(leftHeight,rightHeight) +1 '''
''' Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses of length 2*n.\ For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" Make sure the returned list of strings are sorted. https://www.youtube.com/watch?v=LxwiwlUDOk4 https://www.youtube.com/watch?v=sz1qaKt0KGQ ''' class Solution: # @param A : integer # @return a list of strings def __init__(self): self.result = [] def generateParenthesis(self, n): self.paren_helper(n, 0, "") return self.result def paren_helper(self, open_avail, close_avail, paren): #base condition if open_avail == 0: # I used all the available open bracket paren += ")" * close_avail self.result.append(paren[::]) # copy by value the string return # 1 recursion elif close_avail == 0: # definately should start wih open bracket self.paren_helper(open_avail - 1, close_avail + 1, paren + "(") #used open # 2 recursion else: self.paren_helper(open_avail - 1, close_avail + 1, paren + "(") self.paren_helper(open_avail, close_avail - 1, paren + ")") #used close sol= Solution() print(sol.generateParenthesis(3)) # ['((()))', '(()())', '(())()', '()(())', '()()()']
''' *LinkedList 1) data structure linked with Nodes 2) create Node class, LinkedList class 3) [tip] save head (don't use directly) ex) cur = self.head 4) [initialize] linkedlist = LinkedList(1) (linkedlist = LinkedList() (X)) 5) remove method : 5-1) the target is self.head 5-2) the target is in between 5-3) the target is in the end ''' class Node: def __init__(self,item): self.val = item self.next = None class LinkedList: def __init__(self,item): self.head=Node(item) def add(self,item): cur=self.head while cur.next is not None: cur=cur.next cur.next=Node(item) def remove(self,item): #3 cases if self.head.val == item: #1)the target is self.head self.head = self.head.next else : #2) the target is in between cur=self.head while cur.next is not None: if cur.val ==item: self.removeItem(item) return if (cur.next.next is None) and cur.next.val == item: #the target is in the end cur.next=None return cur=cur.next print("item does not exist in linked list") def removeItem(self,item): cur=self.head while cur.next.next is not None: #link with the next.next node if cur.next.val == item: nextnode = cur.next.next cur.next = nextnode break cur=cur.next def reverse(self): cur = self.head prev = None while cur is not None: next = cur.next cur.next = prev prev = cur cur = next self.head = prev #reset the head of reversed linkedlist def printlist(self): cur =self.head while cur is not None: print(cur.val) cur=cur.next # linkedlist = LinkedList() #wrong linkedlist = LinkedList(1) linkedlist.add(2) linkedlist.add(3) linkedlist.add(4) linkedlist.remove(3) linkedlist.printlist() print('********************') linkedlist.reverse() linkedlist.printlist()
''' Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). 'n' vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Your program should return an integer which corresponds to the maximum area of water that can be contained ( Yes, we know maximum area instead of maximum volume sounds weird. But this is 2D plane we are working with for simplicity ). ''' class Solution(): def maxArea(self, A): best = 0 area = 0 i=0 #starting from the left j=len(A)-1 #starting from the right while (i < j) : #STOP when i == j area = min(A[i], A[j])* (j-i) best=max(area, best) if A[i] < A[j]: #A[i] smaller so move A[i] and hope to find taller one i+=1 else : j-=1 return best solution = Solution() print(solution.maxArea([1, 5, 4, 3])) ''' ### Complexity : O(N^2) def maxArea(self, A): best = 0 for i in range(len(A) - 1): if A[i] != 0: for j in range(i + 1, len(A), 1): if A[j] != 0: if min(A[i], A[j]) * (j - i) > best: best = min(A[i], A[j]) * (j - i) return best '''
''' Implement wildcard pattern matching with support for '?' and '*'. '?' : Matches any single character. '*' : Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). The function prototype should be: int isMatch(const char *s, const char *p) Examples : isMatch("aa","a") → 0 isMatch("aa","aa") → 1 isMatch("aaa","aa") → 0 isMatch("aa", "*") → 1 isMatch("aa", "a*") → 1 isMatch("ab", "?*") → 1 isMatch("aab", "c*a*b") → 0 Return 1/0 for this problem. ''' class Solution: # @param A : string # @param B : string # @return an integer def isMatch(self, A, B): curA = 0 curB = 0 star = -1 match = -1 # order might be 1) 1st and 3rd OR 2) 2nd and 3rd while curA < len(A): if curB < len(B) and (B[curB] in (A[curA],"?")): curA += 1 curB += 1 elif curB < len(B) and B[curB] == "*": star = curB match = curA # 2 reasons needed : 1) in case they wander around the 1st clause 2) update match that might have been updated from the 3rd clause curB += 1 #WILL KEEP TO BACK AND FORTH WITH 2nd AND 3rd CLAUSE elif star != -1: #2 reasons needed : 1) in case they wandered around the 1st clause 2) updated as * in above but next one wasn't a match curB = star # reset curB into star position, WILL KEEP TO BACK AND FORTH WITH 2nd AND 3rd CLAUSE match += 1 curA = match # reset curA into the match (but updated) else: return 0 # False ##Assuming that all A has been traversed while curB < len(B): if B[curB] != "*": return 0 curB += 1 return 1 #True when passed while clause solution = Solution() #True # print(solution.isMatch("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "a**************************************************************************************")) # print(solution.isMatch("cc", "?")) #False, go to "else" # print(solution.isMatch("bbcbabca", "*bcba?")) #False, curB==0 (thought * covered all the strings before but there was "bcba?" left) # print(solution.isMatch("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "*")) #True # print(solution.isMatch("bcaabccaacc", "*c")) # True (can understand back and forth of 2nd, 3rd clause) print(solution.isMatch("aabbaaabbbaa", "a*bbb*aa")) # True
''' Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. ex) babad -> bab (aba) babaab, babab cbbd -> bb baabdd -> baab babababab ''' ## SHOULD USE DYNAMIC PROGRAMMING! class Solution(object): #use dict to save the first visited index def longestPalindrome(self, s): dict={} maxlength=0 result="" if len(s) == 1: return s # step1: going through each character from the first element for i in range(len(s)): if s[i] not in dict: dict[s[i]]=i #save index of first visited ### should compare from the first else: #step2: if s[i] in dict (i.e. the character is revisited) # print(s[dict[s[i]] : i+1]) #original appeared index ~ current index (CAREFUL! NEED TO ADD +1) # print(s[i : dict[s[i]]-1 : -1]) #current index ~ original appeared index BACKWARD (CAREFUL! NEED TO ADD -1) # print("**************") if s[dict[s[i]] : i+1] == s [i : dict[s[i]]-1 : -1]: #step3: If the substr is palindrome (should +1 and should -1) # step4: update maximum length if len(s[ dict[s[i]] : i+1]) > maxlength: #should +1 because should include the last index i as well maxlength=len(s[ dict[s[i]] : i+1]) #update maxlength result = s[ dict[s[i]] : i+1] #update result return result def longestPalindrome2(self, s): dict={} maxlength=0 result="" if len(s) == 1: return s # step1: going through each character from the first element for i in range(len(s)): if s[i] not in dict: dict[s[i]]=i #save index of first visited ### should compare from the first else: #step2: if s[i] in dict (i.e. the character is revisited) print(s[dict[s[i]] : i+1]) #original appeared index ~ current index (CAREFUL! NEED TO ADD +1) print(s[i : dict[s[i]]-1 : -1]) #current index ~ original appeared index BACKWARD (CAREFUL! NEED TO ADD -1) print("**************") if s[dict[s[i]] : i+1] == s [i : dict[s[i]]-1 : -1]: #step3: If the substr is palindrome (should +1 and should -1) # step4: update maximum length if len(s[ dict[s[i]] : i+1]) > maxlength: #should +1 because should include the last index i as well maxlength=len(s[ dict[s[i]] : i+1]) #update maxlength result = s[ dict[s[i]] : i+1] #update result return result sl=Solution() print(sl.longestPalindrome("babababab")) #babababab print(sl.longestPalindrome("a"))
''' Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] Given word = "ABCCED", return true. Given word = "SEE", return true. Given word = "ABCB", return false. ''' ### RECURSION ### EXTRA CONDITION TO BE CONSIDERED : NEED TO KEEP TRACK OF VISITED # FROM the board, RECURSIVE "ABCCED" -> A FOUND + "BCCED" class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ for i in range(len(board)): for j in range(len(board[0])): if self.exist_helper(board, word, i,j): return True return False def exist_helper(self, board, word, row, col): #base condition: when it is reached the end (True) if len(word) == 0: return True #base condition : outside of board or not matched (False) if row <0 or row >=len(board) or col <0 or col >=len(board[0]) or board[row][col] != word[0]: return False # if reached at this point: board[row][col] == word[0] and it should be checked to say it is visited temp = board[row][col] board[row][col]='' # send word one character forward (keep slicing the word) # or can be used so that if 2 of them is False and 2 is True, still it is True result = self.exist_helper(board, word[1:], row+1, col) or\ self.exist_helper(board, word[1:], row - 1, col) or\ self.exist_helper(board, word[1:], row, col + 1) or\ self.exist_helper(board, word[1:], row, col - 1) board[row][col]=temp #return it back regardless of the result return result #result is boolean (True/False) connected by or sol=Solution() # print(sol.exist([ # ['A','B','C','E'], # ['S','F','C','S'], # ['A','D','E','E'] # ], "SEE")) # print(sol.exist([ # ['A','B','C','E'], # ['S','F','C','S'], # ['A','D','E','E'] # ], "ABCB")) print(sol.exist( [["A","B","C","E"], ["S","F","E","S"], ["A","D","E","E"]], "ABCESEEEFS")) ''' ### SIMILAR TO THE MAX ISLAND?! BUT SO MUCH EXCEPTION TO TAKE CARE IN ITERATIVE WAY.. WHAT A MESS!!!! # DATA STRUCTURE : STACK stack = [] ### DO I NEED TO TRACK WHAT IS VISITED? curstack = [] for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == word[0]: # finally found the first letter so lets trick it down print("*********") print((i,j)) visited = [] # reset curstack.append(0) stack.append((i, j)) # save it as tuple (2-dim) visited.append((i, j)) #### SAME LETER CELL MAY NOT BE USED MORE THAN ONCE!! MAYBE I SHOULD MAKE EXTRA MEMORY while stack: print(stack) print(curstack) print(visited) (ai, aj) = stack.pop() wordcur=curstack.pop() for (ni, nj) in ((ai - 1, aj), (ai + 1, aj), (ai, aj - 1), (ai, aj + 1)): #only 4 search if wordcur == len(word)-1: return True if 0<=ni < len(board) and 0<=nj < len(board[0]) and (ni, nj) not in visited and board[ni][nj] == word[wordcur+1]: ### should take care of index out of range ###ALSO SHOULD PUT 0<= or else it can become - and look for the index from the back print((ni,nj)) print(wordcur+1) # wordcur += 1 ## SHOULD NOT UPDATE WORDCUR curstack.append(wordcur+1) ## SHOULD ALSO MAKE STACK FOR WORDCUR TO KEEP TRACK OF IT AS WELL stack.append((ni, nj)) # save it as tuple (2-dim) visited.append((ni, nj)) else : #need to research if len(visited) != 0: visited.pop() # break NEVER! I NEED TO RUN ALL 4 SEARCH TO TRACK IT BACK!! # if wordcur == len(word): # return True return False # didnt found after full loop '''