text
stringlengths
37
1.41M
# Write a Python program to convert a list of tuples into a dictionary t1 = [("x", 1), ("x", 2), ("x", 3), ("y", 1), ("y", 2), ("z", 1)] d = {} for a,b in t1: d.setdefault(a,[]).append(b) print(d)
from itertools import groupby from collections import defaultdict import os class Connecting_Cities: def __init__(self, source, dest, textFile): self.source = source self.dest = dest self.textFile = textFile """ Paired cities fetched line wise from textfile and converted to adjacency matrix/graph. Pair reverse also appended to the graph. """ def process_file(self): kv = [] with open(self.textFile) as f: for s in f.readlines(): if s.strip() != '': try: kv.append(((s.split(','))[0].strip() ,(s.split(','))[1].strip())) kv.append(((s.split(','))[1].strip() ,(s.split(','))[0].strip())) # Reverse pair except: print('Error Handler: Invalid input line found! Line skipped.') graph = defaultdict(list) for k,v in groupby(kv, lambda x:x[0]): graph[k].append([i[1] for i in list(v)][0]) #print(graph) f.close() return graph """ Traverse graph using Depth-first search starting from source city ending on destination city Return False if no destination found. """ def connectivity(self, graph): flag = 0 visited = set() def dfs(visited, graph, source, dest): if source == dest: return True if source in visited: return False else: visited.add(source) for next_city in graph[source]: if dfs(visited, graph, next_city, dest): return True return (dfs(visited,graph,self.source,self.dest)) def process_result(self, result): if result: return ('There is a connection between '+ self.source+ ' and ' + self.dest + '!') else: return ('No connection between '+ self.source+ ' and ' + self.dest + '!')
# ์ปคํ”ผ ํ•จ์ˆ˜ num=0; num=int(input("์–ด๋–ค ์ปคํ”ผ ๋“œ๋ฆด๊นŒ์š”? (1:๋ณดํ†ต 2:์„คํƒ• 3:๋ธ”๋ž™) ")) print("# 1. ๋œจ๊ฑฐ์šด ๋ฌผ์„ ์ค€๋น„ํ•œ๋‹ค.") print("# 2. ์ข…์ด์ปต์„ ์ค€๋น„ํ•œ๋‹ค.") if num==1: print("# 3.๋ณดํ†ต์ปคํ”ผ๋ฅผ ํƒ„๋‹ค.") elif num==2: print("# 3. ์„คํƒ•์ปคํ”ผ๋ฅผ ํƒ„๋‹ค.") elif num==3: print("# 3. ๋ธ”๋ž™์ปคํ”ผ๋ฅผ ํƒ„๋‹ค.") else: print("# 3. ์•„๋ฌด ์ปคํ”ผ๋‚˜ ํƒ„๋‹ค.") print("# 4. ๋ฌผ์„ ๋ถ“๋Š”๋‹ค.") print("# 5. ์Šคํ‘ผ์œผ๋กœ ์ €์–ด์„œ ๋…น์ธ๋‹ค.") if num==1: print("์†๋‹˜ ๋ณดํ†ต์ปคํ”ผ ์—ฌ๊ธฐ ์žˆ์Šต๋‹ˆ๋‹ค.") elif num==2: print("์†๋‹˜ ์„คํƒ•์ปคํ”ผ ์—ฌ๊ธฐ ์žˆ์Šต๋‹ˆ๋‹ค.") elif num==3: print("์†๋‹˜ ๋ธ”๋ž™์ปคํ”ผ ์—ฌ๊ธฐ ์žˆ์Šต๋‹ˆ๋‹ค.") else: print("์†๋‹˜ ์•„๋ฌด์ปคํ”ผ ์—ฌ๊ธฐ ์žˆ์Šต๋‹ˆ๋‹ค.")
number=int(input("์ฐธ์„์ž์˜ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์‹œ์˜ค:")) chickens=number beers=number*2 cakes=number*4 print("์น˜ํ‚จ์˜ ์ˆ˜:",chickens) print("๋งฅ์ฃผ์˜ ์ˆ˜:",beers) print("์ผ€์ต์˜ ์ˆ˜:",cakes)
##๋ณ€์ˆ˜ ์„ ์–ธ ๋ถ€๋ถ„ money, c500, c100, c50, c10=0,0,0,0,0 ##๋ฉ”์ธ(MAIN)์ฝ”๋“œ ๋ถ€๋ถ„ money=int(input("๊ตํ™˜ํ•  ๋ˆ์„ ์–ผ๋งˆ ์ž…๋‹ˆ๊นŒ?")) c500=money//500 money%=500 c100=money//100 money%=100 c50=money//50 money%=50 c10=money//10 money%=10 print("\n ์˜ค๋ฐฑ์›์งœ๋ฆฌ==> %d ๊ฐœ์ž…๋‹ˆ๋‹ค." %c500) print(" ๋ฐฑ์›์งœ๋ฆฌ==> %d ๊ฐœ์ž…๋‹ˆ๋‹ค." %c100) print(" ์˜ค์‹ญ์›์งœ๋ฆฌ==> %d ๊ฐœ์ž…๋‹ˆ๋‹ค." %c50) print(" ์‹ญ์›์งœ๋ฆฌ==> %d ๊ฐœ์ž…๋‹ˆ๋‹ค." %c10) print(" ๋ฐ”๊พธ์ง€ ๋ชปํ•œ ์ž”๋ˆ์€ ==> %d ๊ฐœ์ž…๋‹ˆ๋‹ค." %money) print(" ๊ณ„์‚ฐ์ข…๋ฃŒ ")
# ๋ณ€์ˆ˜ ์„ ์–ธ ๋ถ€๋ถ„ i,k, heartNum=0,0,0 numStr,ch, heartStr="","","" ## ๋ฉ”์ธ(main) ์ฝ”๋“œ ๋ถ€๋ถ„ numStr=input("์ˆซ์ž๋ฅผ ์—ฌ๋Ÿฌ ๊ฐœ ์ž…๋ ฅํ•˜์„ธ์š” : ") print("") i=0 ch=numStr[i] while True: heartNum=int(ch) heartStr="" for k in range(0,heartNum): heartStr+="\u2665" k+=1 print(heartStr) i+=1 if(i>len(numStr)-1): break ch=numStr[i]
#gugudan chart reverse ##๋ณ€์ˆ˜ ์„ ์–ธ ๋ถ€๋ถ„ i,k,guguLine=0,0,"" ## main code for i in range(9,1,-1): guguLine=guguLine+(" #%d๋‹จ "%i) print(guguLine) for i in range(1,10): guguLine="" for k in range(9,1,-1): guguLine=guguLine+str("%dX%d=%2d "%(k,i,k*i)) print(guguLine)
#1~100๊นŒ์ง€์˜ ํ•ฉ์„ ๊ตฌํ•˜๋˜ 3์˜ ๋ฐฐ์ˆ˜๋ฅผ ๊ฑด๋„ˆ๋›ฐ๊ณ  ๋”ํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ hap=0 for i in range(1,101): if i%3==0: continue hap+=i print("1~100๊นŒ์ง€์˜ ํ•ฉ %d"%hap)
##find a string between two strings. #return the string or None def find_substring( s, first, last ): try: start = s.find( first ) + len( first ) end = s.find( last, start ) if start >= 0 and end >= 0: return s[start:end] else: return None except ValueError: return None
#!/usr/bin/env python # coding: utf-8 # In[1]: #!/usr/bin/env python # coding: utf-8 # In[2]: import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy import stats # Assumptions: # # Two potential outcome per trial # # Probability of success is same across all trials # # Each trial is independent # # fixed number of observations # ### Coin toss interview question # # - how do you insure a fair toss when either you dont know that coin is fair /ubnfair or assuming the coin is unfair? # # - Just toss the coin twice!! # p(T)= 1/4 # p(H)=3/4 # # # P(H,H) = 3/4 * 3/4 # # P(H,T) = 3/4 * 1/4 # # P(T,H) = 1/4 * 3/4 # # P(T,T) = 1/4 * 1/4 # ### 1.)A bank found that the average number of cars waiting during the noon hour at a drive-up window follows a Poisson distribution with a mean of 2 cars. Make a chart of this distribution and answer these questions concerning the probability of cars waiting at the drive-up window. # # # In[4]: ฮป = 2 #cars at noon # In[7]: x = np.arange(0,12) y = stats.poisson(ฮป).pmf(x) plt.bar(x,y) plt.title('Poisson dist with $lambda = 2$') plt.xlabel('Number of cars') plt.ylabel('P(X)'); # a.) What is the probability that no cars drive up in the noon hour? # In[8]: stats.poisson(ฮป).pmf(0) # b.) What is the probability that 3 or more cars come through the drive through? # In[6]: stats.poisson(ฮป).sf(2) # c.) How likely is it that the drive through gets at least 1 car? means one or more # In[9]: stats.poisson(ฮป).sf(0).round(2) # In[ ]: # ### 2.)Grades of State University graduates are normally distributed with a mean of 3.0 and a standard deviation of .3. Calculate the following: # # In[ ]: # - a.) What grade point average is required to be in the top 5% of the graduating class? # In[11]: #top 15 % mean = 3 stddev = .3 stats.norm(mean,stddev).isf(.05).round(2) # - b.) What GPA constitutes the bottom 15% of the class? # can use ppf # In[27]: mean = 3 stddev = .3 stats.norm(mean,stddev).isf(.85) # In[13]: stats.norm(mean,stddev).ppf(.15) # - c.)An eccentric alumnus left scholarship money for students in the third decile from the bottom of their class. Determine the range of the third decile. Would a student with a 2.8 grade point average qualify for this scholarship? # In[21]: mean = 3 stddev = .3 stats.norm(mean,stddev).isf(.70) # In[ ]: # In[31]: stats.norm(mean,stddev).isf(.80) # In[15]: stats.norm(mean,stddev).ppf([0.2,0.3]) # In[33]: # They would qualify! # - d.) If I have a GPA of 3.5, what percentile am I in? # In[39]: #They are in 95 percentile stats.norm(mean,stddev).isf(.05) # In[16]: stats.norm(mean,stddev).cdf(3.5) # In[17]: (np.random.normal(3,0.3,100_000) < 3.5).mean() # ### 3.)A marketing website has an average click-through rate of 2%. One day they observe 4326 visitors and 97 click-throughs. # # - a.)How likely is it that this many people or more click through? # In[19]: #binomal ct = 97 n_trials = 4326 p = .02 clicks = stats.binom(n_trials, p) clicks.sf(96) # In[20]: #using simulation clicks = np.random.choice([0,1], (100_000, 4326), p = [0.98, 0.02]) clicks # In[21]: (clicks.sum(axis =1) >96).mean() # In[23]: # using poisson ฮป = n_trials * p stats.poisson(ฮป).sf(96) # ### 4.)You are working on some statistics homework consisting of 100 questions where all of the answers are a probability rounded to the hundreths place. Looking to save time, you put down random probabilities as the answer to each question. # # - a.) What is the probability that at least one of your first 60 answers is correct? # In[29]: #binom h_trials = 60 pt =0.01 chance = stats.binom(h_trials,pt).sf(0) chance # In[31]: #by simulation ((np.random.choice([0,1], (100_000, 60), p =[0.99, 0.01])).sum(axis=1) >0).mean() # ### 5.)The codeup staff tends to get upset when the student break area is not cleaned up. Suppose that there's a 3% chance that any one student cleans the break area when they visit it, and, on any given day, about 90% of the 3 active cohorts of 22 students visit the break area. # # - a.) How likely is it that the break area gets cleaned up each day? # In[33]: number_of_students = (.90 * (3*22)) p = 0.03 # In[35]: number_of_students = round(number_of_students) number_of_students # In[37]: cd_trials = stats.binom(number_of_students, p).sf(0) cd_trials # In[42]: x = np.arange(0,10) y = stats.binom(number_of_students, p).pmf(x) plt.bar(x,y) plt.xlabel('Number of time are is cleaned per day') # - b.) How likely is it that it goes two days without getting cleaned up? All week? # In[46]: never_cleaned = 1-cd_trials never_cleaned # In[49]: # two_days cd_trials_2_days = stats.binom(number_of_students * 2, p).pmf(0) cd_trials_2_days # In[50]: #all week cd_trials_5_days = stats.binom(number_of_students * 5, p).pmf(0) cd_trials_5_days # ### 6.)You want to get lunch at La Panaderia, but notice that the line is usually very long at lunchtime. After several weeks of careful observation, you notice that the average number of people in line when your lunch break starts is normally distributed with a mean of 15 and standard deviation of 3. If it takes 2 minutes for each person to order, and 10 minutes from ordering to getting your food, what is the likelihood that you have at least 15 minutes left to eat your food before you have to go back to class? Assume you have one hour for lunch, and ignore travel time to and from La Panaderia. # In[ ]: # In[54]: line_stdev = 3 line_mean = 15 #number of people on average in line lunch_break = 60 #min for lunch order_time_person = 2 #min time_cook = 10 #min eat_time = 15 #max amount of time without being late. 60- 15 eat - 10 food prep time_to_get_order = lunch_break - time_cook - eat_time time_to_get_order # In[52]: #convert mean and std from ppl to min mean_line = (15*2) #mins std_line = (3*2) # In[55]: stats.norm(mean_line, std_line).cdf(time_to_get_order) # In[56]: mean = 15 std_dev = 3 stats.norm(mean,std_dev).cdf(17.5) # In[57]: (np.random.normal(30,6,100_000) < 35).mean() # ### 7.)Connect to the employees database and find the average salary of current employees, along with the standard deviation. For the following questions, calculate the answer based on modeling the employees salaries with a normal distribution defined by the calculated mean and standard deviation then compare this answer to the actual values present in the salaries dataset. # # # In[6]: from env import host, user, password def get_db_url(user, host, password, db): return f'mysql+pymysql://{user}:{password}@{host}/{db}' # In[7]: url = f'mysql+pymysql://{user}:{password}@{host}/employees' # In[11]: salaries_db = pd.read_sql("SELECT * FROM salaries WHERE to_date = '9999-01-01'", url) # In[12]: salaries_db # In[29]: salary_mean = salaries_db.salary.mean() salary_mean # In[30]: salary_std = salaries_db.salary.std() salary_std # - a.)What percent of employees earn less than 60,000? # In[20]: salaries_mean = salaries_db.describe() salaries_mean = 72012.235857 salaries_std = 17309.995380 # In[21]: sixitybelow =stats.norm(salaries_mean,salaries_std).cdf(60_000) # - b.)What percent of employees earn more than 95,000? # In[22]: ninetyfive = stats.norm(salaries_mean,salaries_std).sf(94999) # - c.)What percent of employees earn between 65,000 and 80,000? # In[23]: sixity_five = stats.norm(salaries_mean,salaries_std).cdf(65000) sixity_five # In[24]: eighty = stats.norm(salaries_mean,salaries_std).sf(79999) eighty # In[25]: 1-sixity_five - eighty between_six_eig = np.diff(stats.norm(salaries_mean,salaries_std).cdf([65000, 80000])) between_six_eig # - d.)What do the top 5% of employees make? # In[27]: stats.norm(salaries_mean,salaries_std).isf(.05)
welcome = "Welcome to my Nightmare", "Alice Cooper", 1975 bad = "Bad Company", "Bad Company", 1974 budgie = "Nightflight", "Budgie", 1981 imelda = "More Mayehm", "Imilda May", 2011 metallica = "Ride the Lightning", "Metallica", 1984 metallica2 = ["Ride the Lightning", "Metallica", 1984] # title, artist, year = imelda # Tuple unpacking # print(title) # print(artist) # print(year) # Lists can cause problems though when you try to do this # For example, if the list is ever made a different length than it may be defined elsewhere, say with .append() metallica2.append("Rock") try: title, artist, year = metallica2 print(title) print(artist) print(year) except ValueError: print("ERROR: too many values to unpack (expected 3)") print() # There is no appending a tuple: try: imelda.append("Jazz") except AttributeError: print("ERROR: 'tuple' object has no attribute 'append'") print() imelda = "More Mayehm", "Imilda May", 2011, ( (1, "Pulling the Rug"), (2, "Psycho"), (3, "Mayhem"), (4, "Kentish Town Waltz")) print(imelda) title, artist, year, tracks = imelda print() print(title) print(artist) print(year) # print(tracks) # print() for track, song_title in tracks: print("\t", track, song_title) print() imelda = "More Mayehm", "Imilda May", 2011, 1, "Pulling the Rug", 2, "Psycho", 3, "Mayhem", 4, "Kentish Town Waltz" # Note the importance of datatype structure: try: title, artist, year, track1, track2, track3, track4 = imelda except ValueError: print("ERROR: too many values to unpack (expected 7)") print() # Note that just because a tuple cannot be changed, if an element of a tuple is mutable, that element in the # tuple can be changed imelda = "More Mayehm", "Imilda May", 2011, ( [(1, "Pulling the Rug"), (2, "Psycho"), (3, "Mayhem"), (4, "Kentish Town Waltz")]) # The element at index 3 is the tuple of list of tuples of tracks and song titles imelda[3].append((5, "All For You")) # We can append a track and song title here title, artist, year, tracks = imelda print() print(title) print(artist) print(year) # print(tracks) # print() for track, song_title in tracks: print("\t", track, song_title) print()
# The escape character split_string = "This string has been \nsplit over\nseveral\nlines" print(split_string) print() tabbed_string = "1\t2\t3\t4\t5" print(tabbed_string) print() print('The pet shop owner said "No, no, \'e\'s uh, ... he\'s resting".') print("The pet shop owner said \"No, no, \'e\'s uh, ... he's resting\".") print("""The pet shop owner said "No, no, 'e's uh, ... he's resting".""") print("""The pet shop owner said "No, no, \ 'e's uh, ... he's resting".""") print() print(split_string) print() another_split_string = """This string has been split over several lines""" print(another_split_string) print() yass = another_split_string = """This string has been \ split over \ several \ lines""" print(yass) print() # Can see problems with \U, \t, \n # print("C:\Users\tim\notes.txt") print("C:\\Users\\tim\\notes.txt") # Raw string: print(r"C:\Users\tim\notes.txt") print()
__author__ = 'dev' fruit = {"orange": "a sweet, orange, citrus fruit", "apple": "good for making cider", "lemon": "a sour, yellow, citrus fruit", "grape": "a small, sweet, fruit growing in bunches", "lime": "a sour, green, citrus fruit"} print(fruit) # fruitKeys = fruit.keys() # print(fruitKeys) # # fruit["tomato"] = "not nice with ice cream" # print(fruitKeys) print(fruit.items()) fTuple = tuple(fruit.items()) print(fTuple) print('-'*40) for snack in fTuple: item, description = snack print(item + ' is ' + description) print('-' * 40) print(dict(fTuple)) print('-' * 40)
__author__ = 'dev' string = '1234567890' # for char in string: # print(char) # myIter = iter(string) # print(myIter) # # 1 # print(next(myIter)) # # 2 # print(next(myIter)) # # 3 # print(next(myIter)) # # 4 # print(next(myIter)) # # 5 # print(next(myIter)) # # 6 # print(next(myIter)) # # 7 # print(next(myIter)) # # 8 # print(next(myIter)) # # 9 # print(next(myIter)) # # 0 # print(next(myIter)) # # Next one won't work # print(next(myIter)) # # # This is what a for loop does and ceases when it gets "stop iteration error" # # # This implicitly creates an iterable from the string # for char in string: # print(char) # print() # # # This one has an iterator explictly defined so the for loop itself is not creating this # for char in iter(string): # print(char) """Challenge Create a list of items (you may use either strings or numbers in the list), then create an iterator using the iter() function. Use a for loop to loop "n" times, where n is the number of items in your list. Each time round the loop, use next() on your list to print the next item. hint: use the len() function rather than counting the number of items in the list """ # My solution itemList = ['a1', 'b2', 'c3', 'd4', 'e5', 'f6', 'g7'] iterList = iter(itemList) for i in range(len(itemList)): print(next(iterList)) print() for i in itemList: print(i)
__author__ = 'dev' # # Tuples are an ordered set of data # # A tuple is imutable, unlike lists # # Tuples are not necessarily parenthesis where lists are square brackets # # but parenthesis are often used to remove ambiguity # # t = 'a', 'b', 'c' # # t is a tuple # print(t) # # but this print statement doesn't display as a tuple # print('a', 'b', 'c') # # so we add parenthesis to set the items as a tuple # print(('a', 'b', 'c')) # Notice we have different data types on one line welcome = "Welcome to my Nightmare", "Alice Cooper", 1975 bad = "Bad Company", "Bad Company", 1974 budgie = "Nightflight", "Budgie", 1981 imelda = "More Mayhem", "Emilda May", 2011 metallica = "Ride the Lightning", "Metallica", 1984 # # print(metallica) # print(metallica[0]) # print(metallica[1]) # print(metallica[2]) # # # This won't work as tuples are imutable # # metallica[0] = 'Master of Puppets' # # But you can do other things... like completely recreating it # # (Because expressions on the RHS of the "=" are always evaluated before the LHS) # imelda = imelda[0], "Imelda May", imelda[2] # print(imelda) # # A type being imutable means that you can't change the contents of an object once you've created it # # But it doesn't mean that your variable, in this case a tuple, can't be assigned a new object of that type # # # In the list, we can easily change the items in the list because it is mutable # # Note however, lists are meant to hold objects of the same type (homogeneous), # # tuples are useful for heterogenous items metallica2 = ["Ride the Lightning", "Metallica", 1984] # print(metallica2) # metallica2[0] = "Master of Puppets" # print(metallica2) # Good to use tuples for things you dont think shou'd ever be changed in your code (like SSN or album names, etc) imelda = "More Mayhem", "Imelda May", 2011 # # Here is tuple unpacking! # title, artist, year = imelda # print(title) # print(artist) # print(year) # print() # # title, artist, year = metallica2 # print(title) # print(artist) # print(year) # print() # # # # This fails # metallica2.append('Rock') # # title, artist, year, = metallica2 # # print(title) # # print(artist) # # print(year) # # # This succeeds # title, artist, year, genre = metallica2 # print(title) # print(artist) # print(year) # # A tuple can contain elements which are also tuples # imelda = "More Mayhem", "Imilda May", 2011, ( # (1, "Pulling the Rug"), (2, "Psycho"), (3, "Mayhem"), (4, "Kentish Town Walts")) # print(imelda) # # title, artist, year, tracks = imelda # print(title) # print(artist) # print(year) # print(tracks) # print() # # imelda = "More Mayhem", "Imilda May", 2011, (1, "Pulling the Rug"),\ # (2, "Psycho"), (3, "Mayhem"), (4, "Kentish Town Walts") # # We need to make sure we have the number of elements in the tuple or we wont be able to assign them to variables # title, artist, year, track1, track2, track3, track4 = imelda # # print(title) # print(artist) # print(year) # print(track1) # print(track2) # print(track3) # print(track4) # print() # imelda = "More Mayhem", "Imilda May", 2011, 1, "Pulling the Rug", \ # 2, "Psycho", 3, "Mayhem", 4, "Kentish Town Walts" # # This will cause a failure now because we have indicated tuple unpacking with a number of variables less than # # the number of elements in the tuple # title, artist, year, track1, track2, track3, track4 = imelda # # print(title) # print(artist) # print(year) # print(track1) # print(track2) # print(track3) # print(track4) # print() """Challenge Given the tuple below that represents the Imelda May album 'More Mayhem', write code to print the album details, followed by a listing of all the tracks in the album. Indent the tracks by a single tav stop when printing them (remember that you can pass more than one item to the print function, separating them with a comma""" # imelda = "More Mayhem", "Imilda May", 2011, ( # (1, "Pulling the Rug"), (2, "Psycho"), (3, "Mayhem"), (4, "Kentish Town Walts")) # print(imelda) # # # My solution # album, artist, year, tracks = imelda # print(album) # print(artist) # print(year) # for i in tracks: # print('\t', i) # print() # # # print(album + ', ' + artist + ', ' + str(year) + ', ', str(['{}'.format(i) for i in tracks])) # # Tim's solution # album, artist, year, tracks = imelda # print(album) # print(artist) # print(year) # for song in tracks: # track, title = song # print('\tTrack number {}, Title: {}'.format(track, title)) # print() # Addressing a tuple with a list as an element: imelda = "More Mayhem", "Imilda May", 2011, ( [(1, "Pulling the Rug"), (2, "Psycho"), (3, "Mayhem"), (4, "Kentish Town Walts")]) print(imelda) # Select the element of the tuple that is a list imelda[3].append((5, "All For You")) album, artist, year, tracks = imelda # After performing tuple unpacking, we can append only that element instead of the previous method tracks.append((6, "Eternity")) print(album) print(artist) print(year) for song in tracks: track, title = song print('\tTrack number {}, Title: {}'.format(track, title)) print()
__author__ = 'dev' # print('Hello World!') # print() # print(1 + 2) # print() # print(3*'hello') # print() # print(7*6) # print() # print('The End') # print() # print('Hello' + 'World') # print() # print("'Allo World") # print() # print('"hello" world...') # # greeting = 'Hello' # name = 'Chris' # print(greeting + ' ' + name) # print() # greeting = "Hello" # name = input("Please enter your name: ") # print() # print(greeting + ' ' + name) # print() # splitString = "This string has been\nsplit over\nseveral\nlines" # print(splitString) # print() # # tabbedString = "1\t2\t3\t4\t5\t" # print(tabbedString) # print('The pet shop owner said "No, no, he\'s uh,\n ... he\'s resting."') # print() # print("The pet shop owner said \"No, no, he's uh,\n... he's resting\"") # anotherSplitString = """This string has been # split over # several lines""" # print(anotherSplitString) print('''The pet shop owner said "No, no, he's uh \n... he's resting"''') print("""The pet shop owner said "No, no, he's uh \n... he's resting" """)
decimals = range(0, 100) my_range = decimals[3:40:3] print(my_range == range(3, 40, 3)) print(range(0, 5, 2) == range(0, 6, 2)) print(list(range(0, 5, 2))) print(list(range(0, 6, 2))) r = range(0, 100) print(r) for i in r[::-2]: print(i) print() for i in range(99, 0, -2): print(i) print() print(range(0, 100)[::-2] == range(99, 0, -2)) print() back_string = "egaugnal lufrewop yrev a si nohtyP" print(back_string[::-1]) print() r = range(0, 10) for i in r[::-1]: print(i) # Challenge o = range(0, 100, 4) # defines a sequence generation from 0 up to 100 by 4s print(o) # range(0, 100, 4) p = o[::5] print(p) # range(0, 100, 20) print(list(p)) # [0, 20, ... 80]
import typ @typ.typ(items=[int]) def radix_sort(items): """ >>> radix_sort([]) [] >>> radix_sort([1]) [1] >>> radix_sort([2,1]) [1, 2] >>> radix_sort([1,2]) [1, 2] >>> radix_sort([1,2,2]) [1, 2, 2] """ radix = 10 max_len = False tmp, placement = -1, 1 while not max_len: max_len = True # declare and initialize buckets buckets = [list() for _ in range( radix )] # split items between lists for i in items: tmp = i / placement buckets[tmp % radix].append( i ) if max_len and tmp > 0: max_len = False # empty lists into items array a = 0 for b in range( radix ): buck = buckets[b] for i in buck: items[a] = i a += 1 # move to next digit placement *= radix return items
import typ @typ.typ(items=[int]) def quick_sort(items): """ >>> quick_sort([]) [] >>> quick_sort([1]) [1] >>> quick_sort([2,1]) [1, 2] >>> quick_sort([1,2]) [1, 2] >>> quick_sort([1,2,2]) [1, 2, 2] """ if len(items) == 0: return [] left = 0 right = len(items) -1 temp_stack = [] temp_stack.append((left,right)) #Main loop to pop and push items until stack is empty while temp_stack: pos = temp_stack.pop() right, left = pos[1], pos[0] #-------------------------- #Pivot first element in the array p = items[left] i = left + 1 j = right while 1: while i <= j and items[i] <= p: i +=1 while j >= i and items[j] >= p: j -=1 if j <= i: break #Exchange items items[i], items[j] = items[j], items[i] #Exchange pivot to the right position items[left], items[j] = items[j], items[left] piv = j #-------------------------- #If items in the left of the pivot push them to the stack if piv-1 > left: temp_stack.append((left,piv-1)) #If items in the right of the pivot push them to the stack if piv+1 < right: temp_stack.append((piv+1,right)) return items
import typ @typ.typ(items=[int]) def cocktail_sort(items): """ >>> cocktail_sort([]) [] >>> cocktail_sort([1]) [1] >>> cocktail_sort([2,1]) [1, 2] >>> cocktail_sort([1,2]) [1, 2] >>> cocktail_sort([1,2,2]) [1, 2, 2] """ for k in range(len(items)-1, 0, -1): swapped = False for i in range(k, 0, -1): if items[i]<items[i-1]: items[i], items[i-1] = items[i-1], items[i] swapped = True for i in range(k): if items[i] > items[i+1]: items[i], items[i+1] = items[i+1], items[i] swapped = True if not swapped: return items return items
import typ @typ.typ(items=[int]) def heap_sort(items): """ >>> heap_sort([]) [] >>> heap_sort([1]) [1] >>> heap_sort([2,1]) [1, 2] >>> heap_sort([1,2]) [1, 2] >>> heap_sort([1,2,2]) [1, 2, 2] """ # in pseudo-code, heapify only called once, so inline it here for start in range((len(items)-2)/2, -1, -1): siftdown(items, start, len(items)-1) for end in range(len(items)-1, 0, -1): items[end], items[0] = items[0], items[end] siftdown(items, 0, end - 1) return items @typ.typ(items=[int], start=int, end=int) def siftdown(items, start, end): root = start while True: child = root * 2 + 1 if child > end: break if child + 1 <= end and items[child] < items[child + 1]: child += 1 if items[root] < items[child]: items[root], items[child] = items[child], items[root] root = child else: break
# source: http://danishmujeeb.com/blog/2014/01/basic-sorting-algorithms-implemented-in-python import typ import random @typ.typ(items=[int]) def bubble_sort(items): """ >>> bubble_sort([]) [] >>> bubble_sort([1]) [1] >>> bubble_sort([2,1]) [1, 2] >>> bubble_sort([1,2]) [1, 2] >>> bubble_sort([1,2,2]) [1, 2, 2] """ for i in range(len(items)): for j in range(len(items)-1-i): if items[j] > items[j+1]: items[j], items[j+1] = items[j+1], items[j] # Swap! return items @typ.typ(items=[int]) def insertion_sort(items): """ >>> insertion_sort([]) [] >>> insertion_sort([1]) [1] >>> insertion_sort([2,1]) [1, 2] >>> insertion_sort([1,2]) [1, 2] >>> insertion_sort([1,2,2]) [1, 2, 2] """ for i in range(1, len(items)): j = i while j > 0 and items[j] < items[j-1]: items[j], items[j-1] = items[j-1], items[j] j -= 1 return items @typ.typ(items=[int]) def merge_sort(items): """ >>> merge_sort([]) [] >>> merge_sort([1]) [1] >>> merge_sort([2,1]) [1, 2] >>> merge_sort([1,2]) [1, 2] >>> merge_sort([1,2,2]) [1, 2, 2] """ if len(items) > 1: mid = len(items) / 2 # Determine the midpoint and split left = items[0:mid] right = items[mid:] merge_sort(left) # Sort left list in-place merge_sort(right) # Sort right list in-place l, r = 0, 0 for i in range(len(items)): # Merging the left and right list lval = left[l] if l < len(left) else None rval = right[r] if r < len(right) else None if (lval and rval and lval < rval) or rval is None: items[i] = lval l += 1 elif (lval and rval and lval >= rval) or lval is None: items[i] = rval r += 1 else: raise Exception('Could not merge, sub arrays sizes do not match the main array') return items @typ.typ(items=[int]) def quick_sort(items): """ >>> quick_sort([]) [] >>> quick_sort([1]) [1] >>> quick_sort([2,1]) [1, 2] >>> quick_sort([1,2]) [1, 2] >>> quick_sort([1,2,2]) [1, 2, 2] """ if len(items) > 1: pivot_index = len(items) / 2 smaller_items = [] larger_items = [] for i, val in enumerate(items): if i != pivot_index: if val < items[pivot_index]: smaller_items.append(val) else: larger_items.append(val) quick_sort(smaller_items) quick_sort(larger_items) items[:] = smaller_items + [items[pivot_index]] + larger_items return items @typ.typ(items=[int]) def heap_sort(items): """ >>> heap_sort([]) [] >>> heap_sort([1]) [1] >>> heap_sort([2,1]) [1, 2] >>> heap_sort([1,2]) [1, 2] >>> heap_sort([1,2,2]) [1, 2, 2] """ # in pseudo-code, heapify only called once, so inline it here for start in range((len(items)-2)/2, -1, -1): siftdown(items, start, len(items)-1) for end in range(len(items)-1, 0, -1): items[end], items[0] = items[0], items[end] siftdown(items, 0, end - 1) return items @typ.typ(items=[int], start=int, end=int) def siftdown(items, start, end): root = start while True: child = root * 2 + 1 if child > end: break if child + 1 <= end and items[child] < items[child + 1]: child += 1 if items[root] < items[child]: items[root], items[child] = items[child], items[root] root = child else: break @typ.typ(items=[int]) def shell_sort(items): """ >>> shell_sort([]) [] >>> shell_sort([1]) [1] >>> shell_sort([2,1]) [1, 2] >>> shell_sort([1,2]) [1, 2] >>> shell_sort([1,2,2]) [1, 2, 2] """ inc = len(items) // 2 while inc: for i, el in enumerate(items): while i >= inc and items[i - inc] > el: items[i] = items[i - inc] i -= inc items[i] = el inc = 1 if inc == 2 else int(inc * 5.0 / 11) return items @typ.typ(items=[int]) def comb_sort(items): """ >>> comb_sort([]) [] >>> comb_sort([1]) [1] >>> comb_sort([2,1]) [1, 2] >>> comb_sort([1,2]) [1, 2] >>> comb_sort([1,2,2]) [1, 2, 2] """ gap = len(items) swaps = True while gap > 1 or swaps: gap = max(1, int(gap / 1.25)) # minimum gap is 1 swaps = False for i in range(len(items) - gap): j = i+gap if items[i] > items[j]: items[i], items[j] = items[j], items[i] swaps = True return items @typ.typ(items=[int]) def selection_sort(items): """ >>> selection_sort([]) [] >>> selection_sort([1]) [1] >>> selection_sort([2,1]) [1, 2] >>> selection_sort([1,2]) [1, 2] >>> selection_sort([1,2,2]) [1, 2, 2] """ for i in range(0,len(items)-1): mn = min(range(i,len(items)), key=items.__getitem__) items[i],items[mn] = items[mn],items[i] return items @typ.typ(items=[int]) def radix_sort(items): """ >>> radix_sort([]) [] >>> radix_sort([1]) [1] >>> radix_sort([2,1]) [1, 2] >>> radix_sort([1,2]) [1, 2] >>> radix_sort([1,2,2]) [1, 2, 2] """ radix = 10 max_len = False tmp, placement = -1, 1 while not max_len: max_len = True # declare and initialize buckets buckets = [list() for _ in range( radix )] # split items between lists for i in items: tmp = i / placement buckets[tmp % radix].append( i ) if max_len and tmp > 0: max_len = False # empty lists into items array a = 0 for b in range( radix ): buck = buckets[b] for i in buck: items[a] = i a += 1 # move to next digit placement *= radix return items @typ.typ(items=[int]) def binary_sort(items): """ >>> binary_sort([]) [] >>> binary_sort([1]) [1] >>> binary_sort([2,1]) [1, 2] >>> binary_sort([1,2]) [1, 2] >>> binary_sort([1,2,2]) [1, 2, 2] """ initial_left = 0 initial_right = len(items) - 1 new_list = [] if initial_right > initial_left: new_list.append(items[initial_left]) for pivot in items[initial_left + 1:]: new_list_len_minus_1 = len(new_list) - 1 left_for_binary_search = 0 right_for_binary_search = new_list_len_minus_1 assert left_for_binary_search <= right_for_binary_search while left_for_binary_search < right_for_binary_search: midpoint = (left_for_binary_search + right_for_binary_search) / 2 if pivot < new_list[midpoint]: right_for_binary_search = midpoint else: left_for_binary_search = midpoint + 1 assert left_for_binary_search == right_for_binary_search if new_list[left_for_binary_search] < pivot: # we are >= new_list.insert(left_for_binary_search + 1, pivot) else: # we are <, insert before new_list.insert(left_for_binary_search, pivot) # now copy to the original list for index, value in enumerate(new_list): items[initial_left + index] = value return items @typ.typ(items=[int]) def count_sort(items): """ >>> count_sort([]) [] >>> count_sort([1]) [1] >>> count_sort([2,1]) [1, 2] >>> count_sort([1,2]) [1, 2] >>> count_sort([1,2,2]) [1, 2, 2] """ if items == []: return [] counts = {} for num in items: if num in counts: counts[num] += 1 else: counts[num] = 1 sorted_list = [] for num in range(min(items), max(items) + 1): if num in counts: for j in range(counts[num]): sorted_list.append(num) return sorted_list @typ.typ(items=[int]) def pancake_sort(items): """ >>> pancake_sort([]) [] >>> pancake_sort([1]) [1] >>> pancake_sort([2,1]) [1, 2] >>> pancake_sort([1,2]) [1, 2] >>> pancake_sort([1,2,2]) [1, 2, 2] """ if len(items) <= 1: return items for size in range(len(items), 1, -1): maxindex = max(range(size), key=items.__getitem__) if maxindex+1 != size: # This indexed max needs moving if maxindex != 0: # Flip the max item to the left items[:maxindex+1] = reversed(items[:maxindex+1]) # Flip it into its final position items[:size] = reversed(items[:size]) return items @typ.typ(items=[int]) def pigeonhole_sort(items): """ >>> pigeonhole_sort([]) [] >>> pigeonhole_sort([1]) [1] >>> pigeonhole_sort([2,1]) [1, 2] >>> pigeonhole_sort([1,2]) [1, 2] >>> pigeonhole_sort([1,2,2]) [1, 2, 2] """ if items == []: return items # size of range of values in the list (ie, number of pigeonholes we need) my_min = min(items) my_max = max(items) size = my_max - my_min + 1 # our list of pigeonholes holes = [0] * size # Populate the pigeonholes. for x in items: holes[x - my_min] += 1 # Put the elements back into the array in order. i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 items[i] = count + my_min i += 1 return items @typ.typ(items=[int]) def bucket_sort(items): """ >>> bucket_sort([]) [] >>> bucket_sort([1]) [1] >>> bucket_sort([2,1]) [1, 2] >>> bucket_sort([1,2]) [1, 2] >>> bucket_sort([1,2,2]) [1, 2, 2] """ buckets = {} m = 100 # buckets n = len(items) for j in range(m): buckets[j] = 0 for i in range(n): buckets[items[i]] += 1 i = 0 for j in range(m): for k in range(buckets[j]): items[i] = j i += 1 return items @typ.typ(items=[int]) def cocktail_sort(items): """ >>> cocktail_sort([]) [] >>> cocktail_sort([1]) [1] >>> cocktail_sort([2,1]) [1, 2] >>> cocktail_sort([1,2]) [1, 2] >>> cocktail_sort([1,2,2]) [1, 2, 2] """ for k in range(len(items)-1, 0, -1): swapped = False for i in range(k, 0, -1): if items[i]<items[i-1]: items[i], items[i-1] = items[i-1], items[i] swapped = True for i in range(k): if items[i] > items[i+1]: items[i], items[i+1] = items[i+1], items[i] swapped = True if not swapped: return items return items @typ.typ(items=[int]) def counting_sort(items): """ >>> counting_sort([]) [] >>> counting_sort([1]) [1] >>> counting_sort([2,1]) [1, 2] >>> counting_sort([1,2]) [1, 2] >>> counting_sort([1,2,2]) [1, 2, 2] """ """in-place counting sort""" maxval = 10000 m = maxval + 1 count = [0] * m # init with zeros for a in items: count[a] += 1 # count occurences i = 0 for a in range(m): # emit for c in range(count[a]): # - emit 'count[a]' copies of 'a' items[i] = a i += 1 return items @typ.typ(items=[int]) def gnome_sort(items): """ >>> gnome_sort([]) [] >>> gnome_sort([1]) [1] >>> gnome_sort([2,1]) [1, 2] >>> gnome_sort([1,2]) [1, 2] >>> gnome_sort([1,2,2]) [1, 2, 2] """ i = 0 n = len(items) while i < n: if i and items[i] < items[i-1]: items[i], items[i-1] = items[i-1], items[i] i -= 1 else: i += 1 return items def teleportinggnome_sort(items): """ >>> teleportinggnome_sort([]) [] >>> teleportinggnome_sort([1]) [1] >>> teleportinggnome_sort([2,1]) [1, 2] >>> teleportinggnome_sort([1,2]) [1, 2] >>> teleportinggnome_sort([1,2,2]) [1, 2, 2] """ i = j = 0 n = len(items) while i < n: if i and items[i] < items[i-1]: items[i], items[i-1] = items[i-1], items[i] i -= 1 else: if i < j: # teleport! i = j j = i = i+1 return items import bisect, heapq @typ.typ(items=[int]) def patience_sort(items): """ >>> patience_sort([]) [] >>> patience_sort([1]) [1] >>> patience_sort([2,1]) [1, 2] >>> patience_sort([1,2]) [1, 2] >>> patience_sort([1,2,2]) [1, 2, 2] """ piles = [] for x in items: new_pile = [x] i = bisect.bisect_left(piles, new_pile) if i != len(piles): piles[i].insert(0, x) else: piles.append(new_pile) # priority queue allows us to retrieve least pile efficiently for i in range(len(items)): small_pile = piles[0] items[i] = small_pile.pop(0) if small_pile: heapq.heapreplace(piles, small_pile) else: heapq.heappop(piles) return items @typ.typ(items=[int]) def strand_sort(items): """ >>> strand_sort([]) [] >>> strand_sort([1]) [1] >>> strand_sort([2,1]) [1, 2] >>> strand_sort([1,2]) [1, 2] >>> strand_sort([1,2,2]) [1, 2, 2] """ nitems = len(items) sortedBins = [] while( len(items) > 0 ): highest = float("-inf") newBin = [] i = 0 while( i < len(items) ): if( items[i] >= highest ): highest = items.pop(i) newBin.append( highest ) else: i=i+1 sortedBins.append(newBin) sorted = [] while( len(sorted) < nitems ): lowBin = 0 for j in range( 0, len(sortedBins) ): if( sortedBins[j][0] < sortedBins[lowBin][0] ): lowBin = j sorted.append( sortedBins[lowBin].pop(0) ) if( len(sortedBins[lowBin]) == 0 ): del sortedBins[lowBin] return sorted # @typ.typ(items=[int]) # def cycle_sort(items): # """ # >>> cycle_sort([]) # [] # >>> cycle_sort([1]) # [1] # >>> cycle_sort([2,1]) # [1, 2] # >>> cycle_sort([1,2]) # [1, 2] # >>> cycle_sort([1,2,2]) # [1, 2, 2] # """ # for i in range(len(items)): # if i != items[i]: # n = i # while 1: # tmp = items[int(n)] # if n != i: # items[int(n)] = last_value # else: # items[int(n)] = None # last_value = tmp # n = last_value # if n == i: # items[int(n)] = last_value # break # return items # def columns(l): # return [filter(None, x) for x in zip_longest(*l)] # try: # from itertools import izip_longest as zip_longest # except: # zip_longest = lambda *args: map(None, *args) # # @typ.typ(items=[int]) # def bead_sort(items): # """ # >>> bead_sort([]) # [] # >>> bead_sort([1]) # [1] # >>> bead_sort([2,1]) # [1, 2] # >>> bead_sort([1,2]) # [1, 2] # >>> bead_sort([1,2,2]) # [1, 2, 2] # """ # x = columns([[1] * e for e in items]) # return rev(map(len, columns(x))) #
# Changes a written number into an actual number. # assumes no things like "thousand million" or "billion billion" # commas and hyphens OK as long as there are spaces or hypnens between words def num_word(num): """Convert word to number Ok with hyphens, commas, ands : as long as there are spaces or hyphens between all words """ general_numbers = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11, "twelve": 12, "thirteen": 13, "fourteen": 14, "fifteen": 15, "sixteen": 16, "seventeen": 17, "eighteen": 18, "nineteen": 19, "twenty": 20, "thirty": 30, "fourty": 40, "fifty": 50, "sixty": 60, "seventy": 70, "eighty": 80, "ninety": 90 } multiplier_numbers = {"hundred": 100, "thousand": 1000, "million": 1000000, "billion": 1000000000, "trillion":10000000000 } # turn the string into a list of individual words num = num.split() for i in range(len(num)): if "-" in num[i]: both_numbers = num[i].split("-") num[i] = both_numbers[0] num.insert(i+1, both_numbers[1]) # remove any commas for d in range(len(num)): if num[d][-1] == ",": num[d] = num[d][0:-1] # answer starts at 0, and decimal status starts at no answer = 0 is_decimal = "no" # Tests for a decimal if "point" in num: is_decimal = "yes" decimal = num.index("point") after_decimal = num[decimal+1:] num = num[:decimal] #find the current multiplier def current_multiplier(place, num_list): # if it's not in the last place if place < (len(num_list) - 1): #print("{} not in last index".format(num[place])) # check every position after for a multiplier for x in range(place + 1, len(num_list)): #print("checking for multipliers after {}".format(num[place])) # if there is a multiplier if num_list[x] in multiplier_numbers: #print("multiplier found") # check for special case of "hundred" as that can combo with other multipliers if num_list[x] == "hundred" and place < len(num_list) - 2: #print("multiplier = hundred") # see if there is a second multiplier for j in range(x + 1, len(num_list)): #print("looking for second multiplier") if num[j] in multiplier_numbers: #if there is a second multiplier, return 100 * second multiplier return 100 * multiplier_numbers[num_list[j]] else: # there was no second multiplier to combo with, so return 100 return 100 else: #the multiplier wasn't "hundred" so it couldn't combo with another multiplier return multiplier_numbers[num_list[x]] else: #no multiplier found return 1 else: #it's in last position, no multiplier possible return 1 for c in range(len(num)): if num[c] in general_numbers: current_number = general_numbers[num[c]] * current_multiplier(c, num) answer += current_number if is_decimal == "yes": for g in range(len(after_decimal)): decimal_multiplier = 1/ 10**(g+1) current_number = decimal_multiplier * general_numbers[after_decimal[g]] answer += current_number if num[0] == "negative": answer *= -1 return answer a = "negative four million, five hundred and sixty-three thousand point three two five" print (num_word(a))
import math #V1 """ iใ‚’๏ผ‘ใฅใคๅข—ใ‚„ใ—็…งๅˆใ™ใ‚‹ใ€‚ {num % i, i++} """ def is_prime_v1(num: int) -> bool: if num <= 1: return False for i in range(2, num): if num % i == 0: return False return True #V2 """ ็ด ๆ•ฐใฎ็…งๅˆใ‚’โˆšiใพใงใซใ™ใ‚‹ใ€‚ {num % โˆši, i++} """ def is_prime_v2(num: int) -> bool: if num <= 1: return False for i in range(2, math.floor(math.sqrt(num) + 1)): if num % i == 0: return False # math้–ขๆ•ฐใ‚’ไฝฟใ‚ใš่กŒใ†ๅ ดๅˆ # i = 2 # while i * i <= num: # if num % i == 0: # return False # i += 1 return True #V3 """ 2ใฎๅ€ๆ•ฐ(ๅถๆ•ฐ)ใ‚’ใ‚ใ‚‰ใ‹ใ˜ใ‚็…งๅˆๅฏพ่ฑกใ‹ใ‚‰้™คใใ€‚ {num % 2, False} """ def is_prime_v3(num: int) -> bool: if num <= 1: return False if num == 2: return True if num % 2 == 0: return False for i in range(3, math.floor(math.sqrt(num) + 1), 2): if num % i == 0: return False # math้–ขๆ•ฐใ‚’ไฝฟใ‚ใš่กŒใ†ๅ ดๅˆ # i = 3 # while i * i <= num: # if num % i == 0: # return False # i += 2 return True #V4 """ ็ด ๆ•ฐใฏ 6k ยฑ 1(k โ‰ฅ 6)ใ‹ใค 6k ยฑ 1 โ‰ค โˆšn ใงๅ‰ฒใ‚Šๅˆ‡ใ‚Œใชใ„ใ‚‚ใฎใงใ‚ใ‚‹ใ€‚ {num % 6โˆšnum ยฑ 1, num + 6} """ def is_prime_v4(num: int) -> bool: if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False for i in range(5, math.floor(math.sqrt(num) + 1), 6): if num % i == 0 or num % (i+2) == 0: return False # ไธญๅคฎๅ€ค(6)ใ‚’ๅ–ใ‚Šยฑ1ใ‚’ๅ–ใ‚‹ใƒใƒผใ‚ธใƒงใƒณ # for i in range(6, math.floor(math.sqrt(num) + 1), 6): # if num % (i-1) == 0 or num % (i+1) == 0: # return False # math้–ขๆ•ฐใ‚’ไฝฟใ‚ใš่กŒใ†ๅ ดๅˆ # i = 5 # while i * i <= num: # if num % i == 0 or num % (i+2) == 0: # return False # i += 6 return True if __name__ == '__main__': import time import random numbers = [random.randint(0, 1000) for _ in range(100000)] start = time.time() for num in numbers: is_prime_v1(num) print('v1', time.time() - start) start = time.time() for num in numbers: is_prime_v2(num) print('v2', time.time() - start) start = time.time() for num in numbers: is_prime_v3(num) print('v3', time.time() - start) start = time.time() for num in numbers: is_prime_v4(num) print('v4', time.time() - start)
time = int(input('enter the number : ')) day = time // 86400 z = time % 86400 hrs = z // 3600 y = z % 3600 mn = y // 60 sec = y % 60 print(day, 'days and', hrs, 'hours and', mn, 'min and', sec, 'seconde')
#Importing necessary libraries import pandas as pd import streamlit as st from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import StandardScaler #Setting the header components def local_css(file_name): with open(file_name) as f: st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True) local_css("style.css") header = """ <div style="padding:0px;"> <h1 style="color:#ffcc00;text-align:center; font-size:50px;">Cardiac Check</h1> <h6 style="color:#99ff66;text-align:center; font-size:25px;">Get your results instantly!๐Ÿคณ</h6> </div> <br> <br> <br> <br> <br> <br> </body> """ st.markdown(header, unsafe_allow_html=True) #Reading the dataset('heart.csv') heart_df = pd.read_csv('heart.csv') #Seperating the dependent(Y) and Independent(X) features X = heart_df.iloc[:,:-1].values Y = heart_df.iloc[:,-1].values #Preprocessing the data scalar = StandardScaler() X_scaled = scalar.fit_transform(X) #Splitting the data into training and testing sets (Train size: 70%, Test size: 30%) X_train, X_test, Y_train, Y_test = train_test_split(X_scaled,Y,test_size=0.3, random_state=47) #Function to take input from the user def user_input(): header_text = """ <h2 style="color:#ffdb4d; font-size:25px;">Please Enter Your Test Results๐Ÿ‘‡</h2> </div> <br> <br> """ st.markdown(header_text, unsafe_allow_html=True) age_text =""" <h5 style="color:#ff9900; font-size:18px;">Please Enter Your Age</h5> """ st.markdown(age_text, unsafe_allow_html=True) age = st.number_input('',0,100,0) gender_text = """ <br> <h5 style="color:#ff9900; font-size:18px;">Please Select Your Gender</h5> """ st.markdown(gender_text, unsafe_allow_html=True) sex = st.selectbox('',("Male", "Female")) chestpain_text = """ <br> <br> <h5 style="color:#ff9900; font-size:18px;">Please Select Your Chest Pain Type</h5> """ st.markdown(chestpain_text, unsafe_allow_html=True) cp = st.radio('',("Typical angina","Atypical angina","Non-anginal pain","Asymptomatic")) bloodpressure_text = """ <br> <h5 style="color:#ff9900; font-size:18px;">Please Select Your Blood Pressure(mm/Hg) Level</h5> """ st.markdown(bloodpressure_text, unsafe_allow_html=True) trestbps = st.slider('',94,200,100) cholesterol_text = """ <br> <h5 style="color:#ff9900; font-size:18px;">Please Select Your Serum Cholestoral(mg/dl) Level</h5> """ st.markdown(cholesterol_text, unsafe_allow_html=True) chol = st.slider('',100,700,150) fbs_text = """ <br> <h5 style="color:#ff9900; font-size:18px;">Please Select Your Fasting Blood Sugar Level</h5> """ st.markdown(fbs_text, unsafe_allow_html=True) fbs = st.radio('',("Lower than 120 mg/dl", "Greater than 120 mg/dl")) restecg_text = """ <br> <h5 style="color:#ff9900; font-size:18px;">Please Select Your Resting ECG Results</h5> """ st.markdown(restecg_text, unsafe_allow_html=True) restecg = st.radio('',("Normal", "ST-T wave abnormality",'Left ventricular hypertrophy')) thalach_text = """ <br> <h5 style="color:#ff9900; font-size:18px;">Please Select Your Maximum Heart Rate</h5> """ st.markdown(thalach_text, unsafe_allow_html=True) thalach = st.slider('',60,250,100) exang_text = """ <br> <h5 style="color:#ff9900; font-size:18px;">Do You Have Experienced Exercise Induced Angina?</h5> """ st.markdown(exang_text, unsafe_allow_html=True) exang = st.radio('',("No", "Yes")) oldpeak_text = """ <br> <h5 style="color:#ff9900; font-size:18px;">Please Select Your Exercise Induced ST Depression</h5> """ st.markdown(oldpeak_text, unsafe_allow_html=True) oldpeak = st.slider('',0.0,8.0,4.0) slope_text = """ <br> <h5 style="color:#ff9900; font-size:18px;">Please Select Your ST Segment Peak Slope</h5> """ st.markdown(slope_text, unsafe_allow_html=True) slope = st.radio('',("Upsloping", "Flat", "Downsloping")) ca_text = """ <br> <h5 style="color:#ff9900; font-size:18px;">Please Select The Number of major vessels (0-3) colored by Flourosopy</h5> """ st.markdown(ca_text, unsafe_allow_html=True) ca = st.selectbox('',(0,1,3)) thal_text = """ <br> <h5 style="color:#ff9900; font-size:18px;">Please Select Your Thalassemia Type</h5> """ st.markdown(thal_text, unsafe_allow_html=True) thal = st.radio('',('Normal','Fixed defect','Reversable defect')) space_text = """ <br> <br> <br> """ st.markdown(space_text, unsafe_allow_html=True) user_data = {} user_input_data = { 'Age': age, 'Sex': sex, 'Chest Pain Type': cp, 'Resting Blood Pressure(mm/Hg)': trestbps, 'Serum Cholestoral(mg/dl)': chol,'Fasting Blood Sugar':fbs, 'Resting Electrocardiographic Results': restecg,'Maximum heart rate achieved':thalach,'Exercise Induced Angina':exang,'ST depression':oldpeak, 'Slope':slope,'Number of major vessels':ca, 'Thalassemia': thal } user_data['Age'] = age if sex=="Male": user_data['Sex'] = 1 else: user_data['Sex']=0 if cp=="Typical angina": user_data['Chest Pain Type'] = 0 elif cp=="Atypical angina": user_data['Chest Pain Type']=1 elif cp=="Non-anginal pain": user_data['Chest Pain Type']=2 elif cp=="Asymptomatic": user_data['Chest Pain Type']=3 user_data['Resting Blood Pressure(mm/Hg)'] = trestbps user_data['Serum Cholestoral(mg/dl)'] = chol if fbs=="Lower than 120 mg/dl": user_data['Fasting Blood Sugar'] = 0 elif fbs=="Greater than 120 mg/dl": user_data['Fasting Blood Sugar'] = 1 if restecg=='Normal': user_data['Resting Electrocardiographic Results']=0 elif restecg=='ST-T wave abnormality': user_data['Resting Electrocardiographic Results'] = 1 elif restecg == 'Left ventricular hypertrophy': user_data['Resting Electrocardiographic Results'] = 2 user_data['Maximum heart rate achieved'] = thalach if exang=='No': user_data['Exercise Induced Angina'] = 0 elif exang=='Yes': user_data['Exercise Induced Angina'] = 1 user_data['ST depression'] = oldpeak if slope=='Upsloping': user_data['Slope'] = 0 elif slope == 'Flat': user_data['Slope'] = 1 elif slope == 'Downsloping': user_data['Slope'] = 2 user_data['Number of major vessels'] = ca if thal=='Normal': user_data['Thalassemia'] = 1 elif thal=='Fixed defect': user_data['Thalassemia'] = 2 elif thal=='Reversable defect': user_data['Thalassemia']=3 features = pd.DataFrame(user_data, index = [0]) user_input_features = pd.DataFrame(user_input_data, index = [0]) return features, user_input_features user_data_input, user_input_features = user_input() #Initializing the KNN Classifier and do the prediction classifier = KNeighborsClassifier(n_neighbors = 6) classifier.fit(X_train, Y_train) prediction = classifier.predict(user_data_input) #Display the entered data and predicted results to the user if st.button("Show Input Data"): user_input_header = """ <h2 style="color:#ffdb4d; font-size:20px;">Please Check Your Details๐Ÿ‘‡</h2> </div> """ st.markdown(user_input_header, unsafe_allow_html=True) brk = """ <br> """ st.write(user_input_features) st.markdown(brk, unsafe_allow_html=True) st.success("Your details have been loaded successfully!") if(st.button("Show Test Results")): st.subheader('Test Results:') if prediction == 0: success_text = """ <h2 style="color:#99ff33; font-size:20px;">Risk of Heart Disease: NO. Your heart is healthy๐Ÿ˜Ž</h2> """ st.markdown(success_text, unsafe_allow_html=True) st.balloons() elif prediction == 1: fail_text= """ <h2 style="color:#ff1a1a; font-size:20px;">Risk of Heart Disease: YES. Please consult a doctor๐Ÿ˜ฐ</h2> """ st.markdown(fail_text, unsafe_allow_html=True)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 6 19:30:49 2021 @author: ironman """ class BST: def __init__(self,value): self.value=value self.left=None self.right=None def insert(self,value): currentnode=self while True: if value<currentnode.value: if currentnode.left is None: currentnode.left=BST(value) break else: currentnode=currentnode.left else: if currentnode.right is None: currentnode.right=BST(value) break else: currentnode=currentnode.right return self def contain(self,value): currentnode=self while currentnode is not None: if value<currentnode.value: currentnode=currentnode.left elif value>currentnode.value: currentnode=currentnode.right else: return True return False def findClosestValueInBst(target,tree): return findClosestValueInBstHelper(target,tree,float("inf")) def findClosestValueInBstHelper(target,tree,closest): currentnode=tree while currentnode is not None: if abs(target-closest)>abs(target-currentnode.value): closest=currentnode.value if target>currentnode.value: currentnode=currentnode.right elif target<currentnode.value: currentnode=currentnode.left else: break return closest tree=BST(10) tree.insert(5) tree.insert(15) tree.insert(2) tree.insert(5) tree.insert(1) ans=findClosestValueInBst(9,tree) print(ans)
#! /usr/bin/env python import random def insertion_sort(unsorted_list): if len(unsorted_list) == 1: return unsorted_list j = 1 while j < len(unsorted_list): key = unsorted_list[j] i = j - 1 while i >= 0 and unsorted_list[i] > key: unsorted_list[i+1] = unsorted_list[i] i -= 1 unsorted_list[i+1] = key j += 1 return unsorted_list unsorted_list = [random.randint(0, 100) for x in range(50)] print(insertion_sort(unsorted_list))
class DoubleLinkNode(object): def __init__(self, data=None): self.data = data self.front = None self.back = None class DoubleLink(object): def __init__(self, l=None): if l == None: self.data = DoubleLinkNode() pass else: self.head = DoubleLinkNode() t = self.head for i in l: n = DoubleLinkNode(i) t.front = n n.back = t t = n t.front = self.head self.head.back = t def __len__(self): n = self.head.front c = 0 while n.data is not None: c += 1 n = n.front return c def printl(self): n = self.head.front while n.data is not None: print n.data n = n.front n = self.head.back while n.data is not None: print n.data n = n.back def append(self, data): if self.head.front.data is not None: n = self.head.back n.front = DoubleLinkNode(data) n.front.back = n n.front.front = self.head self.head.back = n.front else: self.head.front = DoubleLinkNode(data) self.head.back = self.head.front self.head.front.back = self.head self.head.front.front = self.head def find(self, data): n = self.head.front f = False while n.data is not None: if n.data == data: f = True break n = n.front if f == True: return n else: return None def insert(self, node, data): n = self.head.front f = False while n.data is not None: if n == node: f = True break n = n.front if f == False: return False m = DoubleLinkNode(data) m.back = n n.front.back = m m.front = n.front n.front = m return True def remove(self, node): n = self.head.front if n == node: self.head.front = self.head.front.front n.front.back = self.head return while n.data is not None: if n.front == node: break n = n.front if n.data is None: return False n.front.front.back = n n.front = n.front.front return True def invert(self): n = self.head.front while n.data is not None: t = n.front n.front = n.back n.back = t n = n.back t = self.head.front self.head.front = self.head.back self.head.back = t
## Dictionary # dict = {1:"one", 2:"two", 3:"four", 4:"five"} dict['3'] = "three" del dict[4] if(4 in dict): print("dict contains 4") else: print("dict doesn't contain 4") for k in dict.keys(): print(k,":",dict[k]) for tuple in dict.items(): print(tuple)
# For reduce from functools import reduce ## Lambda a = [1, 2, 3, 4] print(a) b = list(map(lambda x: x ** 2, a)) print(b) c = list(map(lambda x, y: x + y, a, b)) print(c) ## Filters ##condition d = list(filter(lambda x: x % 2 == 0, b)) print(d) ## Reduce e = reduce(lambda x,y: x+y, d) print(e)
from Student import Student s = Student("melwin",123,25) s.display() s.course='python' #instance variable # Python's garbage collector runs during program execution # and is triggered when an object's reference count reaches # zero. An object's reference count changes as the number # of aliases that point to it changes. # An object's reference count increases when it is assigned # a new name or placed in a container (list, tuple, or # dictionary). The object's reference count decreases when # it's deleted with del, its reference is reassigned, or its # reference goes out of scope. When an object's reference # count reaches zero, Python collects it automatically. del s
def bad_fibonacci(n): """Return the nth Fibonacci number.""" if n <= 1: return n else: return bad_fibonacci(n - 2) + bad_fibonacci(n-1) def fibonacci(n): if n <= 1: return n else: fib = [] for j in range(0, n): fib.append(fibonacci(j)) return fib[-2] + fib[-1] def good_fibonacci(n): """Return pair of Fibonacci numbers, F(n) and F(n-1).""" if n <= 1: return (n, 0) else: (a,b) = good_fibonacci(n - 1) return (a+b, a) [bad_fibonacci(k) for k in range(0, 11)] [fibonacci(k) for k in range(0, 11)] [good_fibonacci(k) for k in range(0, 11)]
import Progression class GeometricProgression(Progression): """Iterator producing a geometric progression.""" def __init__(self, base=2, start=1): """Create a new geometric progression. base the fixed constant multiplied to each term (default 2) start the first term of the progression (default 1) """ super().__init__(start) self._base = base def _advance(self): """Update current value by multiplying it by the base value.""" self._current *= self._base def main(): p = GeometricProgression() for n in range(0,10): print('n: {0} value: {1}'.format(n, p.__next__())) # next 10 p.print_progression(10) main()
# Write a short recursive Python function that determines if a string s is a palindrome, that is, # it is equal to its reverse. For example, racecar and gohangasalamiimalasagnahog are palindromes. def is_palindrome(s): if len(s) <= 1: return True else: return s[0] == s[-1] and is_palindrome(s[1:-1]) is_palindrome("12") is_palindrome("gohangasalamiimalasagnahog") is_palindrome("racecar") is_palindrome("brandon")
# Write a pseudo-code description of a function that reverses a list of n integers, # so that the numbers are listed in the opposite order than they were before, # and compare this method to an equivalent Python function for doing the same thing. seq = [ k for k in range(0,10)] def reverse(data): for i in range(len(data) - 1, 0, -1): yield data[i] list(reverse(seq))
# Write a short Python function that takes a sequence of integer values and determines # if there is a distinct pair of numbers in the sequence whose product is odd. data = [k for k in range(0, 10)] cross_product = [(a, b) for a in data for b in data] results = {} for i in cross_product: n = i[0] * i[1] if n != 0 and n % 2 == 1: if n in results: results[n] = results[n] + i else: results[n] = i results
# Describe a recursive algorithm to compute the integer part of the base-two logarithm # of n using only addition and integer division. def binary_log(n): if n < 2: return 1 else: return binary_log(n/2) + 1 binary_log(8)
# Write a Python class, Flower, that has three instance variables of type # str, int, and float, that respectively represent the name of the flower, # its number of petals, and its price. Your class must include a constructor # method that initializes each variable to an appropriate value, and your # class should include methods for setting the value of each type, and # retrieving the value of each type. class Flower: def __init__(self, name, petals, price): self._name = name self._petals = petals self._price = price def get_name(self): return self._name def set_name(self, name): self._name = name def get_petals(self): return self._petals def set_petals(self, petals): self._petals = petals def get_price(self): return self._price def set_price(self, price): self._price = price def print_inst(self): print("Name: {0}, Petals: {1}, Price: {2}".format(self._name, self._petals, self._price)) def main(): f = Flower("Dilly", 10, 3.50) f.print_inst() f.set_name("Red Dilly") f.set_petals(3) f.set_price(12.35) f.print_inst() main()
def score(word): scores = { 1: 'aeioulnrst', 2: 'dg', 3: 'bcmp', 4: 'fhvwy', 5: 'k', 8: 'jx', 10: 'qz' } letters = {} for score, group in scores.items(): for l in group: letters[l] = score return sum([letters[l] for l in word.lower()])
cube = lambda x: x**3 #lambda function def fibonacci(n): #iterable li = [0,1] a,b = 0,1 if n == 0 : return [] elif n == 1: return [0] else: while len(li) < n: s = a + b li.append(s) a = b b = s return li # return a list of fibonacci numbers if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n))))
q = input("Do you agree? : ") if q.lower() in ["y", "yes"]: print("Agreed!") elif q.lower() in ["n", "no"]: print("Not Agreed!") else : print("Please write Yes or No!")
# Looping over a list names = ["Bastav", "Sam", "Johny"] for name in names: print(name) # Looping over a string name = "Bastav" for character in name: print(character)
fno = int(input("Enter the first number: ")) sno = int(input("Enter the second number: ")) if fno> sno : print(f"{fno} is greater than{sno}") elif sno>fno: print(f"{sno} is greater than {fno}") else: print("Both the number are equal!")
import numpy as np import scipy as np import pandas as pd import matplotlib.pyplot as plt def rv(value_list): return np.array([value_list]) def cv(value_list): return np.transpose(rv(value_list)) def f1(x): return float((2 * x + 3)**2) def df1(x): return 2 * 2 * (2 * x + 3) def f2(v): x = float(v[0]); y = float(v[1]) return (x - 2.) * (x - 3.) * (x + 3.) * (x + 1.) + (x + y -1)**2 def df2(v): x = float(v[0]); y = float(v[1]) return cv([(-3. + x) * (-2. + x) * (1. + x) + \ (-3. + x) * (-2. + x) * (3. + x) + \ (-3. + x) * (1. + x) * (3. + x) + \ (-2. + x) * (1. + x) * (3. + x) + \ 2 * (-1. + x + y), 2 * (-1. + x + y)]) def gd(f, df, x0, step_size_fn, max_iter): """ :f: a function whose input is x, a column vector, and returns a scalar. :df: a function whose input is x, a column vector, and returns a column vector representing the gradient of f at x. :x0: an initial value of x, a column vector. :step_size_fn: a function that is given the iteration index (an integer) and returns a step size. :max_iter: the number of iterations to perform """ fs = [] xs = [] x = x0 for i in range(max_iter): eta = step_size_fn(i) fx = f(x) fs.append(fx) xs.append(np.copy(x)) x -= eta * df(x) return x, fs, xs def num_grad(f, delta=0.001): def df(x): x = x.reshape(-1) grad = [] for ix, i in enumerate(x): shifted_x_plus = np.copy(x) shifted_x_plus[ix] = i + delta shifted_x_plus = cv(shifted_x_plus) shifted_x_minus = np.copy(x) shifted_x_minus[ix] = i - delta shifted_x_minus = cv(shifted_x_minus) grad.append((f(shifted_x_plus) - f(shifted_x_minus)) / (2 * delta)) grad = np.array(grad).reshape(-1, 1) return grad return df def minimize(f, x0, step_size_fn, max_iter): df = num_grad(f) return gd(f, df, x0, step_size_fn, max_iter) def hinge(v): return np.maximum(0, 1 - v) def hinge_loss(x, y, th, th0): """ :x: (d x n) :y: (1 x n) :th: (d x 1) :th0: (1 x 1) """ margins = y * (np.matmul(th.T, x) + th0) return hinge(margins) def svm_obj(x, y, th, th0, lam): """ :x: :y: :th: :th0: """ regularization = np.asscalar(lam * np.matmul(th.T, th)) mean = np.asscalar(np.mean(hinge_loss(x, y, th, th0))) return mean + regularization # Returns the gradient of hinge(v) with respect to v. def d_hinge(v): return np.where(v >= 1, 0, -1) # Returns the gradient of hinge_loss(x, y, th, th_0) with respect to th def d_hinge_loss_th(x, y, th, th0): return x * y * d_hinge(y * (np.matmul(th.T, x) + th0)) # Returns the gradient of hinge_loss(x, y, th, th_0) with respect to th0 def d_hinge_loss_th0(x, y, th, th0): return y * d_hinge(y * (np.matmul(th.T, x) + th0)) # Returns the gradient of svm_obj(x, y, th, th_0) with respect to th def d_svm_obj_th(x, y, th, th0, lam): reg = 2 * lam * th mean = np.mean(d_hinge_loss_th(x, y, th, th0), axis=1, keepdims=True) return mean + reg # Returns the gradient of svm_obj(x, y, th, th_0) with respect to th0 def d_svm_obj_th0(x, y, th, th0, lam): return np.mean(d_hinge_loss_th0(x, y, th, th0), axis=1, keepdims=True) # Returns the full gradient as a single vector def svm_obj_grad(X, y, th, th0, lam): d_th = d_svm_obj_th(X, y, th, th0, lam) d_th0 = d_svm_obj_th0(X, y, th, th0, lam) return np.vstack([d_th, d_th0]) def batch_svm_min(data, labels, lam): def svm_min_step_size_fn(i): return 2 / (i+1) ** 0.5 d, n = data.shape th = np.zeros((d, 1)) th0 = np.zeros((1, 1)) x0 = np.vstack([th, th0]) print("x0", x0) J = lambda theta: svm_obj(data, labels, theta[:-1, :], theta[-1, :], lam) dJ = lambda theta: svm_obj_grad(data, labels, theta[:-1, :], theta[-1, :], lam) return gd(J, dJ, x0, svm_min_step_size_fn, 10) def super_simple_separable(): X = np.array([[2, 3, 9, 12], [5, 2, 6, 5]]) y = np.array([[1, -1, 1, -1]]) return X, y x_1, y_1 = super_simple_separable() ans = batch_svm_min(x_1, y_1, 0.0001)
import numpy as np class Module(): pass class ReLU(Module): """ ReLU """ def forward(self, Z, dropout_pct=0.): # Z is a column vector of pre-activations; # return A a column vector of activations keep_pct = 1 - dropout_pct mask = np.random.binomial(1, keep_pct, Z.shape) zero_out = np.where((mask == 0) | (Z < 0)) if keep_pct < 1e-10: raise Exception("Dropout percentage too high") self.A = Z / keep_pct self.A[zero_out] = 0 return self.A class Linear(Module): """ Fully-connected layer """ def __init__(self, m, n): """ m () W (m x n matrix): W.T@data """ self.m, self.n = m, n # (in size, out size) self.W0 = np.zeros(shape=[self.n, 1]) # (n x 1) self.W = np.random.normal(0, 1.0 * m ** (-.5), size=[m, n]) # (m x n) self.dLdW = None self.dLdW0 = None # Your initialization code for Adadelta here self.gamma = 0.9 self.epsilon = 1e-8 self.G = np.zeros_like(self.W) self.G0 = np.zeros_like(self.W0) def sgd_step(self, lrate): """ Gradient descent step """ # Assume that self.dldW and self.dLdW0 have been set by 'backward' # Your code for Adadelta here self.G = self.gamma * self.G + (1 - self.gamma) * self.dLdW ** 2 self.G0 = self.gamma * self.G0 + (1 - self.gamma) * self.dLdW0 ** 2 self.W -= lrate * self.dLdW / (np.sqrt(self.G) + self.epsilon) self.W0 -= lrate * self.dLdW0 / (np.sqrt(self.G0) + self.epsilon) print(ReLU().forward(np.full(10, -1), dropout_pct=0.0))
from time import sleep #because we want to print simultaneously both(Hello,Hi) from threading import * class Hello(Thread): #first thread def run(self): for i in range(5): print("Hello") sleep(1) class Hi(Thread): #second thread def run(self): for i in range(5): print("Hi") sleep(1) t1 = Hello() t2 = Hi() t1.start() sleep(0.2) t2.start() t1.join() t2.join() print("Bye") ''' OUTPUT Hello Hi Hello Hi Hello Hi Hello Hi Hello Hi Bye '''
from functools import reduce nums = [3,2,3,4,5,8,6,7,5] #filter is a in built function in python evens = list(filter(lambda n : n%2==0,nums)) doubles = list(map(lambda n : n*2,evens)) print(doubles) sum = reduce (lambda a,b : a+b,doubles) print(sum) print(evens) ''' Output [4, 8, 16, 12] 40 [2, 4, 8, 6] '''
class A: def __init__(self): print("in A Init") def feature1(self): print("Feature 1-A working") def feature2(self): print("Feature 2 working") class B: def __init__(self): print("in B Init") def feature1(self): print("Feature 1-B working") def feature4(self): print("Feature 4 working") class C(A,B): def __init__(self): super().__init__() #Because of this we can access Class A method print("in C init") def feat(self): super().feature2() #We can also access methods with the help of super() a1 = C() a1.feat()
class Car: wheels = 4 #Class Variable def __init__(self): self.mil = 10 #Insrance Variable self.com = "BMW" #Insrance Variable c1 = Car() c2 = Car() c1.mil = 8 print(c1.com , c1.mil, c1.wheels) print(c2.com , c2.mil, c2.wheels)
input_list = [int(i) for i in input("ะกะฟะธัะพะบ ั‡ะธัะตะป ").split()] def reverse(list): if len(list) > 0: print(list[-1]) reverse(list[:-1]) else: print() reverse(input_list) input()
# ะšะพั€ะธัั‚ัƒะฒะฐั‡ ะฒะฒะพะดะธั‚ัŒ ะดะพะฒะถะธะฝะธ ะดะฒะพั… ะบะฐั‚ะตั‚ั–ะฒ kat1 = float(input()) kat2 = float(input()) # ะŸั€ะพั€ะฐะผะฐ ะฒะธะฒะพะดะธั‚ัŒ ะฟะปะพั‰ัƒ ั†ัŒะพะณะพ ะฟั€ัะผะบัƒั‚ะฝะพะณะพ ั‚ั€ะธะบัƒั‚ะฝะธะบะฐ print (kat1 * kat2 / 2)
point_1 = [int(i) for i in input('ะ’ะฒะตะดะธั‚ะต ั‡ะตั€ะตะท ะฟั€ะพะฑะตะป \ ะดะฒะต ะบะพะพั€ะดะธะฝะฐั‚ั‹ 1ะพะน ั‚ะพั‡ะบะธ: ').split()] point_2 = [int(i) for i in input('ะ’ะฒะตะดะธั‚ะต ั‡ะตั€ะตะท ะฟั€ะพะฑะตะป \ ะดะฒะต ะบะพะพั€ะดะธะฝะฐั‚ั‹ 2ะพะน ั‚ะพั‡ะบะธ: ').split()] def distance(point1, point2): return (((point2[0] - point1[0])**2) + (point2[1] - point1[1])**2)**0.5 print(distance(point_1, point_2))
from graphics import * win = GraphWin("Bresenham",1000,1000) def midPoint(X1,Y1,X2,Y2): # calculate dx & dy dx = X2 - X1 dy = Y2 - Y1 d = dy - (dx/2) x = X1 y = Y1 #print(x,",",y,"\n") while (x < X2): x=x+1 if(d < 0): d = d + dy else: d = d + (dy - dx) y=y+1 #print(x,",",y,"\n") pt= Point(round(x),round(y)) pt.setFill('blue') pt.draw(win) def main(): midPoint(420,410,410,570) main()
import json JSON_FILE ='./data.json' def Find_Index(_list, id): for i in _list: if i["id"] == id: return i return "data don't here" with open(JSON_FILE,'r') as fr: data = json.load(fr) INP = input("Enter your ID:") Value = Find_Index(data["Bio"],INP) print(Value)
#!/c/Users/christian/AppData/Local/Programs/Python/Python36/python import time import random import os low = 10 high = 101 def getBetween (low, high): return random.randint (low, high+1) def get1_10_1 (): return random.randint (1, 11) def get1_100_1 (): return random.randint (1, 101) def get1_100_10 (): return random.randint (1, 11) * 10 getNum = get1_10_1 def stats (num_list): for idx, num in enumerate (num_list): print ('%3d --> %4d' % (num, sum (num_list [:idx+1]))) print ('Result: ', sum (num_list)) def main (): num_list = [] while True: os.system ('cls') num = getNum () num_list.append (num) print (num, '\t\tinsert \'q\' to exit!!!') ins = input () if (ins == 'q'): break stats (num_list) if __name__ == "__main__": main ()
# sisendid vanus = int(input("Sisesta enda vanus: ")) sugu = input("Sisesta oma sugu: ") treening = int(input("Sisesta treeningu tรผรผp: ")) # sugu kontroll ja max_pulsi_sageduse arvutamine if sugu == "M" or sugu == "m": max_pulsi_sagedus = 220 - vanus if sugu == "N" or sugu == "n": max_pulsi_sagedus = 206 - vanus * 0.88 # treeningu tรผรผbi kontroll ja min ning max pulsi arvutamine if treening == 1: min_puls = max_pulsi_sagedus * 0.5 max_puls = max_pulsi_sagedus * 0.7 elif treening == 2: min_puls = max_pulsi_sagedus * 0.7 max_puls = max_pulsi_sagedus * 0.8 elif treening == 3: min_puls = max_pulsi_sagedus * 0.8 max_puls = max_pulsi_sagedus * 0.87 # min ja max pulsi รผmmardamine tรคisarvuks min_puls = round(min_puls) max_puls = round(max_puls) # vรคljund print("Pulsisagedus peab olema vahemikus " + str(min_puls) + " ja " + str(max_puls) + " vahel.")
from kitchen import Rosemary from kitchen.utensils import Bowl, Oven, Plate, BakingTray from kitchen.ingredients import Flour, Egg, Salt, Butter, Sugar, ChocolateChips, BakingPowder oven = Oven.use() #Remember to preheat the oven before we start oven.preheat(degrees=175) bowl = Bowl.use (name='batter') # Cream together the butter and the sugar bowl.add(Butter.take("200g")) for i in range(4): bowl.add(Sugar.take('50g')) bowl.mix() # Mix in each egg for i in range(2): egg = Egg.take() egg.crack() bowl.add(egg) bowl.mix() # Add the salt and chocolate chips bowl.add(Salt.take('pinch')) bowl.add(ChocolateChips.take('200g')) #Add the flour in stages for i in range(6): bowl.add (Flour.take('50g')) bowl.mix() #Add the baking soda bowl.add(BakingPowder.take('some')) #Mix it all together one last time for good luck bowl.mix() tray = BakingTray.use (name='cookies') #Put 16 cookies on the baking tray for i in range(16): tray.add(bowl.take(1/16)) #Put the tray in the oven oven.add(tray) #Bake the cookies oven.bake(10) #Take the cookies out of the oven oven.take() cookies = tray.take() #Plate the cookies plate = Plate.use() plate.add(cookies) Rosemary.serve(plate)
import math from math import sqrt import numbers def zeroes(height, width): """ Creates a matrix of zeroes. """ g = [[0.0 for _ in range(width)] for __ in range(height)] return Matrix(g) def identity(n): """ Creates a n x n identity matrix. """ I = zeroes(n, n) for i in range(n): I.g[i][i] = 1.0 return I class Matrix(object): # Constructor def __init__(self, grid): self.g = grid self.h = len(grid) self.w = len(grid[0]) # # Primary matrix math methods ############################# def determinant(self): """ Calculates the determinant of a 1x1 or 2x2 matrix. """ determinant = 0 if not self.is_square(): raise(ValueError, "Cannot calculate determinant of non-square matrix.") if self.h > 2: raise(NotImplementedError, "Calculating determinant not implemented for matrices largerer than 2x2.") # TODO - your code here if self.h == 1: #1x1 matrix determinant = 1/self.g[0][0] elif self.h == 2: # 2x2 matrix if self.g[0][0]*self.g[1][1] == self.g[0][1]*self.g[1][0]: raise ValueError('The matrix is not invertible') else: determinant = self.g[0][0]*self.g[1][1]-self.g[0][1]*self.g[1][0] return determinant def trace(self): """ Calculates the trace of a matrix (sum of diagonal entries). """ trace = 0 if not self.is_square(): raise(ValueError, "Cannot calculate the trace of a non-square matrix.") # TODO - your code here if self.h == 1 : #1x1 matrix trace = self.g[0][0] elif self.h > 1 : #any size greater than 1x1 matrix for i in range(self.h):# 'i' represents both column and row of self trace += self.g[i][i] return trace def inverse(self): """ Calculates the inverse of a 1x1 or 2x2 Matrix. """ inverse = []; if not self.is_square(): raise(ValueError, "Non-square Matrix does not have an inverse.") if self.h > 2: raise(NotImplementedError, "inversion not implemented for matrices larger than 2x2") # TODO - your code here if self.h == 1:# 1x1 matrix for j in range(self.w): # width row = [] for i in range(self.h): #height row.append(1/self.g[i][j]) #this has row = [#] which is a list inverse.append(row) # this puts inverse as = [[#]] which is a list inside a list # the problem that i was running into were two cases: # 1) when put return Matrix(inverse): it gave me an error since i was not appending a list (row) inside the other (inverse) # I was only creating a list inverse and never creating the list row. then would say: inverse.append(1/self[0][0]) # would even put a bracket inside to make it list inside a list, but this doesn't work # 2) when put return inverse: this gave me the error "list object has no attribute g". This is because a list cannot have # an attribute. Only an object or instance, so should have put Matrix(inverse) in this case elif self.h == 2 : #2x2 matrix a = self.g[0][0] b = self.g[0][1] c = self.g[1][0] d = self.g[1][1] #determinant factor f = 1/self.determinant() # reorganized matrix inverse = [[d,-b],[-c,a]] #print('inverse:',inverse) #multiply matrix by factor to get real value of inverse matrix for i in range(self.h): for j in range(self.h):#self.h since it's a square matrix inverse[i][j] = inverse[i][j]*f return Matrix(inverse) def T(self): """ Returns a transposed copy of this Matrix. """ # TODO - your code here #accept to transpose matrices of 2x2 3x3 3x2 2x3 selfTransp = zeroes(self.w, self.h)# sets dimensions of transpose matrix for col in range(selfTransp.w): #could be 1,2,3... rows of self matrix. Col represents the self column and SelfTranp rows in this self_row = [] self_row = self.g[col] for row in range(selfTransp.h): # row represents the self's rows and selfTranp's columns selfTransp[row][col] = self_row[row] # column of list matches with row in transposed matrix return selfTransp def is_square(self): return self.h == self.w # # Begin Operator Overloading ############################ def __getitem__(self,idx): """ Defines the behavior of using square brackets [] on instances of this class. Example: > my_matrix = Matrix([ [1, 2], [3, 4] ]) > my_matrix[0] [1, 2] > my_matrix[0][0] 1 """ return self.g[idx] def __repr__(self): """ Defines the behavior of calling print on an instance of this class. """ s = "" for row in self.g: s += " ".join(["{} ".format(x) for x in row]) s += "\n" return s def __add__(self,other): """ Defines the behavior of the + operator """ if self.h != other.h or self.w != other.w: raise(ValueError, "Matrices can only be added if the dimensions are the same") # # TODO - your code here newSelf = zeroes(self.h,self.w) #initiates matrix of same dimension as the input with zeroes in it #adds matrices with help of loop for i in range(self.h): for k in range(self.w): newSelf[i][k] = self[i][k] + other[i][k] return newSelf def __neg__(self): """ Defines the behavior of - operator (NOT subtraction) Example: > my_matrix = Matrix([ [1, 2], [3, 4] ]) > negative = -my_matrix > print(negative) -1.0 -2.0 -3.0 -4.0 """ # # TODO - your code here negative = zeroes(self.h,self.w) #initiates matrix of same dimension as the input with zeroes in it #puts a negative to each element in matrix for i in range(self.h): for k in range(self.w): negative[i][k] = -self[i][k] return negative def __sub__(self, other): """ Defines the behavior of - operator (as subtraction) """ # # TODO - your code here if self.h != other.h or self.w != other.w: raise(ErrorValue, "Matrices cannot be subtracted if they have different dimensions") newSelf = zeroes(self.h,self.w) for i in range(self.h): for k in range(self.w): newSelf[i][k] = self[i][k] - other[i][k] # return newSelf def __mul__(self, other): """ Defines the behavior of * operator (matrix multiplication) """ # # TODO - your code here if self.w != other.h: raise(ValueError,'Matrices are not able to be multiply. the number of columns in Self and number of row in Other matrix must match') else:# if they do match, then multiply newSelf = zeroes(self.h,other.w) otherTransp = other.T() for i in range(self.h):# i represents the number of rows of self # j represents number of rows otherTransp (notice:they are not always equal with number of rows of self) for j in range(otherTransp.h): for col in range(self.w): # col represents number of columns in self and otherTransposed (they are always equal) self_row = self[i] otherTransp_row = otherTransp[j] # Self's row count 'i' equals to row counting of newSelf. Selftranp's row count 'j' equals newSelf's columns newSelf[i][j]= newSelf[i][j] + (self_row[col]*otherTransp_row[col]) return newSelf def __rmul__(self, other): """ Called when the thing on the left of the * is not a matrix. Example: > identity = Matrix([ [1,0], [0,1] ]) > doubled = 2 * identity > print(doubled) 2.0 0.0 0.0 2.0 """ if isinstance(other, numbers.Number): pass # # TODO - your code here newSelf = zeroes(self.h,self.w) for i in range(self.h): #repeats as many number of rows as self has for k in range(self.w): # repeats as many number of columns as self has newSelf[i][k] = other*self[i][k] return newSelf #
def check_brackets(input_string): br_opening = '{[(' br_closing = '}])' br_closes = dict(zip(br_closing, br_opening)) br_stack = [] for ch in input_string: if ch in br_opening: br_stack.append(ch) if ch in br_closing: if br_stack and br_closes[ch] == br_stack[-1]: br_stack.pop() else: return False return br_stack == []
def flatten(iterable, flattened=None): if flattened == None: flattened = [] for it in iterable: if type(it) in (list, set, tuple): flatten(it, flattened) else: flattened.append(it) return [el for el in flattened if el is not None]
def rotate(text, rot): alphabet = 'abcdefghijklmnopqrstuvwxyz' alow = [c for c in alphabet] aupp = [c for c in alphabet.upper()] cipher_dict = dict(zip(alow + aupp, alow[rot:] + alow[:rot] + aupp[rot:] + aupp[:rot])) return ''.join([cipher_dict[c] if c.isalpha() else c for c in text])
from selenium import webdriver from selenium.webdriver.support.ui import Select import time import math def calc(sum): return str(x+y) link = "http://suninjuly.github.io/selects1.html" browser = webdriver.Chrome() browser.get(link) num1 = browser.find_element_by_id("num1") x = int(num1.text) num2 = browser.find_element_by_id("num2") y = int(num2.text) result = calc(sum) print("sum: ", result) select = Select(browser.find_element_by_id("dropdown")) select.select_by_value(result) submit = browser.find_element_by_class_name("btn-default") submit.click() # ะพะถะธะดะฐะฝะธะต ั‡ั‚ะพะฑั‹ ะฒะธะทัƒะฐะปัŒะฝะพ ะพั†ะตะฝะธั‚ัŒ ั€ะตะทัƒะปัŒั‚ะฐั‚ั‹ ะฟั€ะพั…ะพะถะดะตะฝะธั ัะบั€ะธะฟั‚ะฐ time.sleep(30) # ะทะฐะบั€ั‹ะฒะฐะตะผ ะฑั€ะฐัƒะทะตั€ ะฟะพัะปะต ะฒัะตั… ะผะฐะฝะธะฟัƒะปัั†ะธะน browser.quit()
#!/usr/bin/python import sys sys.setrecursionlimit(922331728) denominations = [1, 5, 10, 25, 50] def making_change(amount, denominations, cache=None, current_amount=1): if amount == 0: return 1 if amount < 0: return 0 # init the cache if cache == None: # for each amount have an array for that coin cache = [[0 for i in range(len(denominations))] for i in range(amount + 1)] for i in range(len(denominations)): cache[0][i] = 1 for i, denomination in enumerate(denominations): y = 0 x = 0 # check if can use the coin if denomination <= current_amount: amount_left = current_amount - denomination y = cache[amount_left][i] if i > 0: x = cache[current_amount][i - 1] cache[current_amount][i] = x + y # base case if current_amount == amount: return cache[amount][len(denominations) - 1] return making_change(amount, denominations, cache, current_amount + 1) making_change(0, denominations) if __name__ == "__main__": # Test our your implementation from the command line # with `python making_change.py [amount]` with different amounts if len(sys.argv) > 1: denominations = [1, 5, 10, 25, 50] amount = int(sys.argv[1]) print("There are {ways} ways to make {amount} cents.".format( ways=making_change(amount, denominations), amount=amount)) else: print("Usage: making_change.py [amount]") # def making_change(amount, denominations): # cache = [0 for i in range(amount + 1)] # cache[0] = 1 # if amount == 0: # return 1 # i = 1 # totalused = [0 for i in range(len(denominations))] # return handle_make_change(amount, denominations, i, lastchange, cache) # def handle_make_change(amount, denominations, i, lastchange, cache): # diffrence = i - lastchange # totalnew = 0 # for coin in denominations: # if coin == 1: # pass # else: # totalnew += diffrence//coin # # if coin <= diffrence: # # totalnew += 1 # if totalnew > 0: # cache[i] = cache[i-1] + totalnew # lastchange = i # else: # cache[i] = cache[i-1] # # base case # if amount == i: # return cache[i] # return handle_make_change(amount, denominations, i + 1, lastchange, cache) # print(making_change(300, denominations))
from room import Room from player import Player # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons", 'N'), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east.""", 'S', 'N', 'E'), 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm. There is a chest near the door to the south""", 'S'), 'narrow': Room("Narrow Passage", """The narrow passage bends here from west to north. The smell of gold permeates the air.""", 'W', 'N'), 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers, but you might find something if you look around. The only exit is to the south.""", 'S'), } # Add items to rooms room['overlook'].addItem('key' ,"You pick up the key, best to hold on to it, it might come in handy later.") room['treasure'].addItem('rock', 'You pick up the jagged rock, maybe you can throw it at something?') room['treasure'].addItem('note', 'You pick up old note, "captivated by the view over the cliff, you never even notice what\'s above you"') # Link rooms together def connectRooms(r1, to, r2): # r1 goes (N, S, E, W, U, or D) to r2 r1.connect(r2, to) if to is 'N': r2.connect(r1, "S") elif to is 'E': r2.connect(r1, "W") elif to is 'S': r2.connect(r1, "N") elif to is 'W': r2.connect(r1, "E") elif to is 'U': r2.connect(r1, "D") elif to is 'D': r2.connect(r1, "U") # room['outside'].n_to = room['foyer'] # room['foyer'].s_to = room['outside'] connectRooms(room['outside'], 'N', room['foyer']) # room['overlook'].s_to = room['foyer'] # room['foyer'].n_to = room['overlook'] connectRooms(room['overlook'], 'S', room['foyer']) # room['narrow'].w_to = room['foyer'] # room['foyer'].e_to = room['narrow'] connectRooms(room['narrow'], 'W', room['foyer']) # room['narrow'].n_to = room['treasure'] # room['treasure'].s_to = room['narrow'] connectRooms(room['narrow'], 'N', room['treasure']) # # Main # # Make a new player object that is currently in the 'outside' room. # Write a loop that: # # * Prints the current room name # * Prints the current description (the textwrap module might be useful here). # * Waits for user input and decides what to do. # # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. # # If the user enters "q", quit the game. direction = [ 'N', 'E', 'S', 'W', 'U', 'D' ] hideRoomDesciption = 'false' player = Player( input("\nWhat is your name?: ") , room['outside']) print (f'\nWelcome, {player.name}!\n') while 'true': if hideRoomDesciption is 'true': hideRoomDesciption = 'false' else: print(f'\n{player.roomDescription()}\n') inputList = input("\nWhat would you like to do?: ").upper().split(' ') if inputList[0] == 'Q': break elif inputList[0] in direction: if player.move(inputList[0]) == 'false': hideRoomDesciption = 'true' print('\nYou cannot go that way!') elif inputList[0] == 'SEARCH' or 'OPEN': hideRoomDesciption = 'true' if len(player.location.items) == 0: print('you don\'t find anything') elif len(player.location.items) == 1: for item in player.location.items: print(f'You find a {item}\n') elif len(player.location.items) > 1: print('You find some items: ') for item in player.location.items: print(item)
# Stepanov Nikita from random import randrange def start(): print( 'ะฃ ะพะดะฝะพะณะพ ะธะท ัƒั‡ะตะฝะธะบะพะฒ ะฝะต ะฟะพะปัƒั‡ะฐะตั‚ัั ะดะพะผะฐัˆะบะฐ ะธ ' 'ะฝัƒะถะฝะพ ะฟะพะผะพั‡ัŒ ะตะผัƒ ะธ ั€ะฐะทะพะฑั€ะฐั‚ัŒ ะพัˆะธะฑะบะธ. ะ”ะปั ัั‚ะพะณะพ ะตัั‚ัŒ ะฒั‹ั…ะพะด - ' 'ะฝะฐะผ ะฝัƒะถะตะฝ ะผะตะฝั‚ะพะฝ ะฃั‚ะบะฐ-ั‚ะธะฒ ๐Ÿฆ† ๐Ÿ•ต๏ธ , ะฟะพะผะพะถะตะผ?' ) option = '' options = {'ะดะฐ': True, 'ะฝะตั‚': False} while option not in options: print('ะ’ั‹ะฑะตั€ะธั‚ะต: {}/{}'.format(*options)) option = input() if options[option]: return quiz() return stay() def quiz(): print("ะฃั‡ะตะฝะธะบ ะฝะต ะดะพ ะบะพะฝั†ะฐ ั€ะฐะทะพะฑั€ะฐะป ะฟะตั€ะฒัƒัŽ ะปะตะบั†ะธัŽ ะธ ัƒ ะฝะตะณะพ ะตัั‚ัŒ ะฟะฐั€ะฐ ะฒะพะฟั€ะพัะพะฒ" "ะธ ะฝัƒะถะฝะฐ ะฟะพะผะพั‰ัŒ, ะฟะพัั‚ะพะผัƒ ะบะฐะบ ะณะพะฒะพั€ะธั‚ัั - 'ะšั€ั-ะบั€ั'") score = 0 questions = {"ะ”ะพะฟัƒัะบะฐะตั‚ัั ะปะธ ะฒ ะบะพะดะต ะผะฝะพะถะตัั‚ะฒะพ ะดะปะธะฝะฝั‹ั… ัั‚ั€ะพะบ," " ะธ ะธัะฟะพะปัŒะทะพะฒะฐะฝะธะต ั‚ะฐะฑะพะฒ?.": {'a': ('\na. ะะธั‡ะตะณะพ ัั‚ั€ะฐัˆะฝะพะณะพ, ะผะพะถะฝะพ ะธ ั‚ะฐะบ ะพัั‚ะฐะฒะธั‚ัŒ. ', False), 'b': ('\nb. ะกะพะบั€ะฐั‰ะฐะตะผ ะดะพ 99 ัะธะผะฒะพะปะพะฒ ัั‚ั€ะพะบะธ ะธ ะดะตะปะฐะตะผ 4 ะฟั€ะพะฑะตะปะฐ', True), 'c': ('\nc. ะœะพะถะฝะพ ัะพะบั€ะฐั‚ะธั‚ัŒ ะดะพ 77 ัะธะผะฒะพะปะพะฒ ' 'ะธ ะทะฐะผะตะฝะธั‚ัŒ ั‚ะฐะฑัƒะปัั†ะธัŽ ะฝะฐ 4 ะฟั€ะพะฑะตะปะฐ', True)}, "ะฃั‚ะบะฐ-ั‚ะธะฒ ะทะฐะผะตั‚ะธะป, ั‡ั‚ะพ ัƒั‡ะตะฝะธะบ ะฟั‹ั‚ะฐะตั‚ัั ัั€ะฐะฒะฝะธั‚ัŒ 2 ะฟะตั€ะตะผะตะฝะฝั‹ะต " "ั‚ะธะฟะฐ float, ะผะพะถะฝะพ ะปะธ ั‚ะฐะบ ะดะตะปะฐั‚ัŒ?": {'a': ('\na. ะ”ะฐ, ะฒะตะดัŒ ั‡ะธัะปะฐ ะผะพะถะฝะพ ัั€ะฐะฒะฝะธะฒะฐั‚ัŒ ะผะตะถะดัƒ ัะพะฑะพะน', False), 'b': ('\nb. ะะตั‚, ะฒะตะดัŒ ะฝะตะบะพั‚ะพั€ะฐั ั‚ะพั‡ะฝะพัั‚ัŒ ั‚ะตั€ัะตั‚ัั', True)}, "ะฏะฒะปัะตั‚ัั ะปะธ set ัƒะฟะพั€ัะดะพั‡ะตะฝะฝั‹ะผ?": {'a': ('\na. ะ”ะฐ', False), 'b': ('\nb. ะะตั‚', True)}, "ะŸะพั‡ะตะผัƒ python ะฝะฐะทั‹ะฒะฐะตั‚ัั ะธะผะตะฝะฝะพ ั‚ะฐะบ? ": { 'a': ('\na. ะะฐะทะฒะฐะฝะธะต ะฟะพัˆะปะพ ะพั‚ ัะตะผะตะนัั‚ะฒะฐ ะฟั€ะตัะผั‹ะบะฐัŽั‰ะธั…ัั', False), 'b': ('\nb. ะะฐะทะฒะฐะปะธ ะฒ ั‡ะตัั‚ัŒ ะฑั€ะธั‚ะฐะฝัะบะพะณะพ ั‚ะตะปะตัˆะพัƒ', True)}} for question, answer_options in questions.items(): user_choice = '' while user_choice not in answer_options.keys(): print(question) for answer in answer_options.values(): print(answer[0]) print('ะ’ั‹ะฑะตั€ะธั‚ะต ะพะดะธะฝ ะธะท ะฒะฐั€ะธะฐะฝั‚ะพะฒ: ', *answer_options) user_choice = input() if answer_options[user_choice][1]: score += 1 print("ะ‘ะปะฐะณะพะดะฐั€ั ะฃั‚ะบะฐ-ั‚ะธะฒัƒ ะบะพะปะธั‡ะตัั‚ะฒะพ ะฟั€ะฐะฒะธะปัŒะฝั‹ั… ะพั‚ะฒะตั‚ะพะฒ ัƒ ัƒั‡ะตะฝะธะบะฐ: ", score) return web() def stay(): print( 'ะžััƒะดะธั‚ะตะปัŒะฝะพะต ะบั€ั-ะบั€ั-ะบั€ั ๐Ÿฆ†, ' 'ะฃั‚ะบะฐ-ั‚ะธะฒ ัะฒะปัะตั‚ัั ะพะดะฝะธะผ ะธะท ะผะตะฝั‚ะพั€ะพะฒ ะะะ, ะฐ ะบะฐะบ ะธะทะฒะตัั‚ะฝะพ ะผะตะฝั‚ะพั€ั‹ ะฒ ' 'ะะะ ะฑะพั€ะพั‚ัŒัั ั ะฟั€ะพะฑะปะตะผะฐะผะธ, ะฐ ะฝะต ะธะทะฑะตะณะฐัŽั‚ ะธั….' 'ะขะฐะบ ั‡ั‚ะพ ะดะฐะฒะฐะน ะฟะพะฒั‚ะพั€ะธะผ.' ) return start() def web(): print('ะ”ะฒะธะณะฐะตะผัั ะดะฐะปัŒัˆะต, ะฝะฐัˆะธ ะบัƒั€ะฐั‚ะพั€ั‹ ัะพะพะฑั‰ะธะปะธ ะพ ั‚ะพะผ, ั‡ั‚ะพ ะฝะตะบะพั‚ะพั€ั‹ะต ัั‚ัƒะดะตะฝั‚ั‹ ะฝะต ะผะพะณัƒั‚ ะฒะบะปัŽั‡ะธั‚ัŒ ะฒะตะฑะบะฐะผะตั€ั‹,' 'ะฟะพัั‚ะพะผัƒ ะฝัƒะถะฝะพ ะฟะพะผะพั‡ัŒ ะธะผ ะธ ะฒะบะปัŽั‡ะธั‚ัŒ ะธั…, ะดะปั ัั‚ะพะณะพ ะฝัƒะถะฝะพ ะฝะฐะฟะธัะฐั‚ัŒ ะธั… ะฝะพะผะตั€' '(X - ะฒั‹ะบะปัŽั‡ะตะฝะฝะฐั,O - ะฒะบะปัŽั‡ะตะฝะฝะฐั), ะบะพะณะดะฐ ะทะฐะบะพะฝั‡ะธั‚ะต ะฒะฒะตะดะธั‚ะต #') student_cameras = [] number_of_students = 5 for i in range(number_of_students): if not randrange(2): student_cameras.append('X') else: student_cameras.append('O') user_choice = '' while user_choice != '#': print(student_cameras) user_choice = input("ะ’ะฒะตะดะธั‚ะต ะฟะพั€ัะดะบะพะฒั‹ะน ะฝะพะผะตั€ ัั‚ัƒะดะตะฝั‚ะฐ(ั ะฝัƒะปั): ") try: is_camera_turned_on = student_cameras[int(user_choice)] == 'O' except (IndexError, ValueError): continue if is_camera_turned_on: student_cameras[int(user_choice)] = 'X' else: student_cameras[int(user_choice)] = 'O' all_cameras_turned_on = True for student_camera in student_cameras: if student_camera == 'X': all_cameras_turned_on = False break if all_cameras_turned_on: print("ะกะฟะฐัะธะฑะพ, ะฃั‚ะบะฐ-ั‚ะธะฒ ๐Ÿฆ† ๐Ÿ•ต๏ธ, ะฒั‹ ัƒัะฟะตัˆะฝะพ ะบั€ัะบะฝัƒะปะธ ะฒัะต ะบะฐะผะตั€ั‹!") else: print("ะะตะบะพั‚ะพั€ั‹ะต ะบะฐะผะตั€ั‹ ะพัั‚ะฐะปะธััŒ ะฒั‹ะบะปัŽั‡ะตะฝะฝั‹ะผะธ, ั‚ะพั‡ะฝะพ ะปะธ ะฒั‹ ะฃั‚ะบะฐ-ั‚ะธะฒ?") print("ะžั‚ะปะธั‡ะฝะฐ ั€ะฐะฑะพั‚ะฐ, ะฃั‚ะบะฐ-ั‚ะธะฒ, ั‚ะตะฟะตั€ัŒ ะฝะฐะบะพะฝะตั† ะผะพะถะฝะพ ะทะฐะนั‚ะธ ะฒ ะฟะฐะฑ, ะฒะพะฟั€ะพั " "ะปะธัˆัŒ ะฒ ั‚ะพะผ ะฒะทัั‚ัŒ ะปะธ ะทะพะฝั‚ะธะบ โ˜‚๏ธ?") if __name__ == '__main__': start()
def addition(num_list, index_first_num, index_second_num): # print(num_list) # print(num_list[index_first_num]) # print(num_list[index_second_num]) return num_list[index_first_num] + num_list[index_second_num] def multiple(num_list, index_first_num, index_second_num): return num_list[index_first_num] * num_list[index_second_num] with open("02/input", mode="r") as f: data = f.read().strip().split(",") data = [int(num) for num in data] data[1] = 12 data[2] = 2 # data = [1, 1, 1, 4, 99, 5, 6, 0, 99] for i in range(0, len(data), 4): opcode = data[i] if opcode == 1: data[data[i+3]] = addition(data, data[i+1], data[i+2]) elif opcode == 2: data[data[i+3]] = multiple(data, data[i+1], data[i+2]) elif opcode == 99: break print(data[0])
import cv2 import numpy as np import os import canny def edge_mask(img, line_size, blur_value): ''' This functions creates an edge mask for given image using canny and dilation Input: img numpy array given image to create its edge mask Output: edges numpy array the edge mask of the image, with dilation ''' ##################### start part of try using canny ##################### ''' # sigma, L_th, H_th = 1, 0.05, 0.27 # edges = canny.cannyEdges(gray, sigma, L_th, H_th) # edges = edges.astype(np.uint8) # edges = np.logical_not(edges) # edges = edges*255 # edges = edges.astype(np.uint8) ''' ##################### end part of try usin canny ##################### gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray_blur = cv2.medianBlur(gray, blur_value) edges = cv2.adaptiveThreshold(gray_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, line_size, blur_value) return edges def color_quantization(img, k=9): ''' This functions reduce the number of colors to a given image Input: img numpy array image to reduce its colors k int number of new different colors Output: result numpy array image recolored to k different colors ''' # Transform the image data = np.float32(img).reshape((-1, 3)) # Determine criteria criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 0.001) # Implementing K-Means ret, label, center = cv2.kmeans(data, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) center = np.uint8(center) result = center[label.flatten()] result = result.reshape(img.shape) return result def cartoonify(img, total, output_folder): ''' This functions make a cartoon out of a given image and saves the cartoon in a given path Input: img numpy array image to create is cartoon total int counter of number of selfies - used as id output_folder string path to save the selfies in ''' line_size = 7 blur_value = 7 edges = edge_mask(img, line_size, blur_value) img = color_quantization(img) ##################### start part of try using canny ##################### ''' # edges = np.repeat(edges[:, :, np.newaxis], 3, axis=2) # cartoon = np.bitwise_and(img, edges) ''' ##################### end part of try using canny ##################### blurred = cv2.bilateralFilter(img, d=7, sigmaColor=200, sigmaSpace=200) cartoon = cv2.bitwise_and(blurred, blurred, mask=edges) img_name = os.path.join(output_folder, "selfie_cartoon_{}.png".format(total)) cv2.imwrite(img_name, cartoon) print("{} written!".format(img_name))
#csv and pickle module import import csv, pickle #definition of readcsv function that takes CSV's and processes information back to the user as variable a ###ONLY WORKS WHEN FILES ARE FORMATED AS CSV'S!!! def readcsv(filename): try: ###opens passed parameter filename and sorts using comma separation ifile = open(filename, "r") reader = csv.reader(ifile, delimiter=",") next(reader) a = [] ###loop that iterates over rows in CSV for row in reader: unit_request = { "PO": row[0], "Serial Number": row[1], "Asset": row[2], "Manufacturer": row[3], "Platform": row[4], "Site": row[5], "Floor": row[6], "Role": row[7], "name": row[8] } ###adds unit request dictionaries to list a a.append(unit_request) ifile.close() ###file is closed and variable is returned to the program return a ###error checking for common errors except FileNotFoundError: print("file not found please check tracking.csv location and try again") except IndexError: print("please ensure that CSV consists of 9 columns") def output_check(): try: x = pickle.load(open("tommy_pickles.p", "rb")) print("saved pickle output : " + str(x)) except FileNotFoundError: print("File not found please make sure tommy_pickles is in the right directory") ###imported file input file = "tracking.csv" ###returned csv output as pickle_output pickle_output = readcsv(file) ###start of pickle.dump method to take the processed output from the readcsv function and save it as a pickle pickle.dump(pickle_output, open("tommy_pickles.p", "wb")) #checking output for user output_check()
# -*- coding: utf-8 -*- """ Created on Tue Oct 8 19:56:04 2019 Nathan Marshall An animated random walk where each step of the particle is in the direction of a random unit vector. """ #%% import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from random import gauss from matplotlib.animation import FuncAnimation as animate def rand_vector(): vec = [gauss(0, 1) for i in range(3)] mag = sum(x**2 for x in vec) ** 0.5 return [x/mag for x in vec] num_steps = 1000 dx = 1 dy = 1 dz = 1 x0 = 0 y0 = 0 z0 = 0 x = [x0] y = [y0] z = [z0] for i in range(0, num_steps): dx, dy, dz = rand_vector() x.append(x[-1] + dx) y.append(y[-1] + dy) z.append(z[-1] + dz) fig1 = plt.figure() ax = fig1.add_subplot(111, projection='3d') line, = ax.plot([], [], []) ax.set_xlabel('X Displacement (m)') ax.set_ylabel('Y Displacement (m)') ax.set_zlabel('Z Displacement (m)') ax.set_title('3D Random Walk') ax.set_xlim3d(-20, 20) ax.set_ylim3d(-20, 20) ax.set_zlim3d(-20, 20) frame_rate = 1/24 * 1000 num_frames = 1000 fstep = round(num_steps/num_frames) def animation(frame): line.set_xdata(x[0:frame*fstep]) line.set_ydata(y[0:frame*fstep]) line.set_3d_properties(z[0:frame*fstep]) return(line,) anim = animate(fig1, animation, frames=num_frames, interval=frame_rate)
# -*- coding: utf-8 -*- """ Created on Tue Oct 29 13:38:36 2019 @author: David Engel The point of this code is to solve the LaPlace equation for a square in a square. """ #import necessary code import numpy as np import matplotlib.pyplot as plt #size of matix z=100 #creates the matrix with zeros sheet=np.zeros((z,z)) #this fills the matrix with random values of 1 or -1 #counter for row n=0 for i in range(z): #counter for columns m=0 #loop to fill specific element for i in range(z): sheet[n,m]=np.random.choice([-1.0,1.0],p=[0.5,0.5]) m+=1 n+=1 #this sets values for edges sheet[0,:]=1.0 sheet[99,:]=1.0 sheet[:,0]=1.0 sheet[:,99]=1.0 #sets values for square sheet[44,44:54]=2.0 sheet[54,44:54]=2.0 sheet[44:54,44]=2.0 sheet[44:54,54]=2.0 #dispaly initial plot inital=np.copy(sheet) plt.figure(1) plt.imshow(inital) #intial time t=0 #final time tf=500 #loop to perform the calculations while t<=tf: nc=0 mc=0 #loop to go through cloums while nc<=z-1: mc=0 #loop to go through rows while mc<=z-1: #adjusts for elements not in the matrix ncd=nc-1 if ncd==-1 : ncd=0 ncu=nc+1 if ncu==z: ncu=z-1 mcd=mc-1 if mcd==-1 : mcd=0 mcu=mc+1 if mcu==z: mcu=z-1 #calculates the values sheet[nc,mc]=.25*(sheet[nc,mcu]+sheet[nc,mcd]+sheet[ncu,mc]+sheet[ncd,mc]) #keeps edge values constant sheet[0,:]=1.0 sheet[99,:]=1.0 sheet[:,0]=1.0 sheet[:,99]=1.0 #keeps square values constant sheet[44,44:54]=2.0 sheet[54,44:54]=2.0 sheet[44:54,44]=2.0 sheet[44:54,54]=2.0 #counts for row mc+=1 #counts for column nc+=1 #counts for interations t+=1 #plots the values plt.figure(2) plt.imshow(sheet)
# -*- coding: utf-8 -*- """ Created on Mon Sep 02 21:21:28 2019 @author: Vandi this doesn't work """ import numpy as np number = 600851475143 maximum = round(number**(1/2)) def isprime(number): prime = True for i in range(2, int(number**(1/2))): if number % i == 0: prime = False break return(prime) factors = [] for i in range(2, maximum+1): if number % i == 0: factors.append(i) factors.append(int(number/i)) factors = np.sort(factors)[::-1] for i in factors: if isprime(i) == True: print(i, 'is the largest prime factor of', number) break
# -*- coding: utf-8 -*- """ Created on Tue Aug 27 15:30:14 2019 Nathan Marshall Solution to Project Euler Problem 7 """ #%% def primefind(num, primes): ''' Updated prime number finder. Checks divisibility of a number by a list of prime numbers up to its square root. If it is not divisible by any of the prime numbers, True is returned. If it is divisible by one of the numbers, False is returned. ''' prime = True sqrtmax = round((num)**(1/2)) for i in primes: if i > sqrtmax: break if num % i == 0: prime = False break return(prime) primes = [2] #list for storing primes, starting with two num = 3 #number to check, starting with 3 while len(primes) != 10001: #generate primes up to the 10001st if primefind(num, primes) == True: primes.append(num) num += 2 #incrementing by two to avoid testing any even number print('The 10001st prime number is', primes[-1]) #display the 10001st
# -*- coding: utf-8 -*- """ Created on Tue Oct 8 13:10:43 2019 Nathan Marshall Random walk in 1D """ #%% import numpy as np import matplotlib.pyplot as plt num_steps = 1000 dx = 1 x0 = 0 t = np.arange(0, num_steps+1) x = [x0] for i in range(0, num_steps): x.append(x[-1] + np.random.choice([-dx, dx])) fig1 = plt.figure() plt.plot(t, x) plt.xlabel('Time (s)') plt.ylabel('Displacement (m)') plt.title('Random Walk 1D')
# -*- coding: utf-8 -*- """ Created on Thu Oct 24 13:55:18 2019 @author: David Engel The point of this code is to simulate particles with spins flipping up or down based off of the spin of nearby particles. """ #import necessary code import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation #size of matic z=100 #temperature t=.1 #creates the matrix with zeros sheet=np.zeros((z,z)) #this fills the matrix with random values of 1 or -1 #counter for row n=0 for i in range(z): #counter for columns m=0 #loop to fill specific element for i in range(z): sheet[n,m]=np.random.choice([-1,1],p=[0.5,0.5]) m+=1 n+=1 #list for row and cloumn selection length=[] #makes a list based off of size z for i in range(z): length.append(i) #list for each row element probability plength=[] #makes a list of probability 1/z for i in range(z): plength.append(1/(z*1.0)) #e e=2.71 #needed for animation fig, ax = plt.subplots() #matrix for animation matrice = ax.imshow(sheet, cmap='viridis',interpolation='none') #function used in animation def update(i): #selects a specific element to update nc=np.random.choice(length,p=plength) mc=np.random.choice(length,p=plength) #this deals with edges treats outside as same values as element ncd=nc-1 if ncd==-1 : ncd=0 ncu=nc+1 if ncu==z: ncu=z-1 mcd=mc-1 if mcd==-1 : mcd=0 mcu=mc+1 if mcu==z: mcu=z-1 #this is to crate values campoaring each neighbor to selected element #energy vales for each pair is calculated eu=sheet[nc,mc]*sheet[ncd,mc] ed=sheet[nc,mc]*sheet[ncu,mc] el=sheet[nc,mc]*sheet[nc,mcd] er=sheet[nc,mc]*sheet[nc,mcu] #total energy et=eu+ed+el+er #exponates for probability calculation nprob=(e**(et/t)) pprob=(e**(-et/t)) #probablilites is element is =1 if sheet[nc,mc]==1: pu=nprob/(nprob+pprob) pd=pprob/(nprob+pprob) #probabilities if element is -1 if sheet[nc,mc]==-1: pu=pprob/(nprob+pprob) pd=nprob/(nprob+pprob) #changes values based off of probabilities sheet[nc,mc]=np.random.choice([-1, 1],p=[pd,pu]) #for animation matrice.set_array(sheet) return[matrice] #animates the matix ani = animation.FuncAnimation(fig, update, frames=100, interval=5) #shows the matrix plt.show()
# -*- coding: utf-8 -*- """ Created on Thu Aug 29 14:12:32 2019 Nathan Marshall This algorithm finds the global minimum in a discrete function. It does this by indexing through the list of the values of the function and saving the minumum number that it finds. It is shown here finding the global minimum of x**2-5*x+6. """ #%% import numpy as np num = 1000 #number of x points to be generated xmin = -5 #minimum x value xmax = 5 #maximum x value x = np.linspace(xmin, xmax, num) #array of x values with above properties fx = x**2-5*x+6 #values of the chosen function f(x) at each x value minimum = fx[0] #initial minimum value set to the first value of f(x) min_idx = 0 #initial minimum index value set to 0 ctr = 0 #counter variable that increments each time through a loop for fxi in fx: #index through each value of fx if fxi < minimum: #if the current value is the smallest yet, save it minimum = fxi #setting new minimum min_idx = ctr #setting new minimum index to the counter number ctr +=1 #increment the counter #display the minimum f(x) value that was found print('The true minimum of x**2-5*x+6 is -1/4 at x = 5/2') print('\nThe algorithm found the minimum to be', minimum, 'at x =', x[min_idx])
# -*- coding: utf-8 -*- """ Created on Sun Oct 13 17:52:15 2019 PHYS 639 >>> Assignments >>> Week 6 >>> ODE III HUYNH LAM """ #%% #(T1-T3) A particle starts at the origin and randomly moves either left or right with equal probability at each step. Write a code that simulates this process. #Plot position vs time and displacement vs time. Experiment with different probabilities (e.g. p_left > p_right). #(T1-T3) Do the same thing but now in 2D (particle can move either up, down, left, or right). #(T3) Do the same thing in 3D. #(T3) Plot average displacement vs time by averaging over many independent instances of this process. #(T3) In 3D, instead of moving on a lattice make your particle move in a random direction with unit step. # Import libraries import numpy as np #math library import matplotlib.pyplot as plt # Plotting library from matplotlib.animation import FuncAnimation as animate from mpl_toolkits.mplot3d import Axes3D #%% #Random walk in 1D #(T1-T3) A particle starts at the origin and randomly moves either left or right with equal probability at each step. Write a code that simulates this process. #Plot position vs time and displacement vs time. Experiment with different probabilities (e.g. p_left > p_right). #Function to make random walk in 1D def rwin1D(x0,Nstep): # Initialize array to save solutions t = np.linspace(0,Nstep,Nstep+1) x = np.zeros(len(t)) #Initial consition x[0]=x0 for i in range(Nstep): #Choose to move left or right step = np.random.choice([-1,1]) # Add step to current position x[i+1]=x[i]+step return x # Input parameters # Initial position x0 = 0 # Number of trials N_trials = 100 # Number of steps per trial N_steps = 1000 # Array to save data x_array = np.zeros((N_trials,N_steps+1)) # Array to save average distance vs. time over all trials x_average = np.zeros(N_steps+1) # Run random walk for all trials for i in range(N_trials): x_array[i,:] = rwin1D(x0,N_steps) # Average over all trials for j in range(N_steps+1): x_average[j] = np.mean(np.abs(x_array[:,j])) # Plot plt.plot(x_array[0,:],label = 'a sample of position vs. time') plt.plot(x_average,label='average distance vs. time') plt.legend() plt.show()
# -*- coding: utf-8 -*- """ Created on Tue Aug 27 13:25:59 2019 Nathan Marshall Solution to Project Euler Problem 1 """ #%% import numpy as np mult3 = [] #lists to contain the multiples of 3 and 5 mult5 = [] for i in range(1, 1000): #loop through i values 1 to 999 if i % 3 == 0: #if i is divisible by three, add to the proper list mult3.append(i) if i % 5 == 0: #if i is divisible by five, add to the proper list mult5.append(i) both = np.concatenate((mult3, mult5)) #concatenate the lists of multiples both = np.unique(both) #keep only the unique values in the concatenation total = 0 #initially set total sum to 0 for i in both: #loop through all the multiples and sum them up total += i print('The sum of the multiples of 3 or 5 up to 1000 is:', total) #display sum
# -*- coding: utf-8 -*- """ Created on Thu Aug 29 13:12:05 2019 Nathan Marshall This algorithm numerically evaluates the integral of a function f(x). Here it is shown evaluating the integral from 0 to pi of sin(x) """ #%% import numpy as np num = 1000 #number of x points to be generated xmin = 0 #minimum x value xmax = np.pi #maximum x value x = np.linspace(xmin, xmax, num) #array of x values with above properties dx = (xmax-xmin)/(num-1) #the width (dx) between each x value fx = np.sin(x) #values of the chosen function f(x) at each x value integral = 0 #intially the integral is set to 0 for i in range(0, num-1): #loop through i values 0 to 999 integral += (fx[i] + fx[i+1])/2*dx #multiply average height of two adjacent f(x) points by dx to find the #area and add this area to the total integral print('The analytical value of this integral is 2, and the numerical value found' ' was:', integral)
# importing libraries import speech_recognition as sr import pandas as pd import os from pydub import AudioSegment from pydub.silence import split_on_silence from rasa.nlu.training_data import load_data from rasa.nlu.config import RasaNLUModelConfig from rasa.nlu.model import Trainer from rasa.nlu import config from rasa.nlu.model import Metadata, Interpreter import re # a function that splits the audio file into chunks # and applies speech recognition def silence_based_conversion(path): k=0 # open the audio file stored in # the local system as a wav file. song = AudioSegment.from_wav(path) # open a file where we will concatenate # and store the recognized text fh = open("recognized.txt", "w+") # split track where silence is 0.5 seconds # or more and get chunks chunks = split_on_silence(song, min_silence_len = 1000, silence_thresh = -50) #print(chunks) # create a directory to store the audio chunks. try: os.mkdir('audio_chunks') except(FileExistsError): pass # move into the directory to # store the audio files. os.chdir('audio_chunks') i = 0 # process each chunk for chunk in chunks: # Create 0.5 seconds silence chunk chunk_silent = AudioSegment.silent(duration = 10) # add 0.5 sec silence to beginning and # end of audio chunk. This is done so that # it doesn't seem abruptly sliced. audio_chunk = chunk_silent + chunk + chunk_silent # export audio chunk and save it in # the current directory. ##------print("saving chunk{0}.wav".format(i)) # specify the bitrate to be 192 k audio_chunk.export("./chunk{0}.wav".format(i), bitrate ='192k', format ="wav") # the name of the newly created chunk filename = 'chunk'+str(i)+'.wav' ##------print("Processing chunk "+str(i)) # get the name of the newly created chunk # in the AUDIO_FILE variable for later use. file = filename # create a speech recognition object r = sr.Recognizer() # recognize the chunk with sr.AudioFile(file) as source: # remove this if it is not working # correctly. r.adjust_for_ambient_noise(source, duration = 0.1) audio_listened = r.listen(source) try: # try converting it to text rec = r.recognize_google(audio_listened) # write the output to the file. #text =+ rec fh.write(rec+". ") # catch any errors. except sr.UnknownValueError: k+=1 except sr.RequestError as e: print("Could not request results. check your internet connection") i += 1 os.chdir('..') def intent_classifier(): model_directory = 'models/pariksha/' interpreter = Interpreter.load(model_directory) file = open('recognized.txt') mystring = file.read() mystring = mystring.lower() text1 = re.sub('[^a-z0-9 ]+', '', mystring) intent = interpreter.parse(text1)['intent']['name'] confidence = interpreter.parse(text1)['intent']['confidence'] return intent, confidence; def test(): df = pd.DataFrame(columns=['filename','intent','confidence']) loc=0 folderpath = 'audio/' for filename in os.listdir(folderpath): filepath = os.path.join(folderpath, filename) fd = open(filepath, 'r') #print(filepath) silence_based_conversion(filepath) intent, confidence = intent_classifier() df = df.append({'filename' : filename,'intent': intent, 'confidence' : confidence} , ignore_index=True) print("Intent: "+intent) print("Confidence: ",confidence) print(df) df.to_csv('Intent.csv',index=False) if __name__ == "__main__": test()
# # @lc app=leetcode id=57 lang=python3 # # [57] Insert Interval # # https://leetcode.com/problems/insert-interval/description/ # # algorithms # Hard (32.73%) # Likes: 1471 # Dislikes: 172 # Total Accepted: 238.6K # Total Submissions: 721.7K # Testcase Example: '[[1,3],[6,9]]\n[2,5]' # # Given a set of non-overlapping intervals, insert a new interval into the # intervals (merge if necessary). # # You may assume that the intervals were initially sorted according to their # start times. # # Example 1: # # # Input: intervals = [[1,3],[6,9]], newInterval = [2,5] # Output: [[1,5],[6,9]] # # # Example 2: # # # Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] # Output: [[1,2],[3,10],[12,16]] # Explanation: Because the new interval [4,8] overlaps with # [3,5],[6,7],[8,10]. # # NOTE:ย input types have been changed on April 15, 2019. Please reset to # default code definition to get new method signature. # # # @lc code=start class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: # return self.O_NlogN(intervals, newInterval) return self.O_N(intervals, newInterval) def O_N(self, intervals, newInterval): # TODO: # pass if not intervals: return [newInterval] if not newInterval: return [intervals] n = len(intervals) i = 0 res = [] # while newInterval.start > intervals[i].start: while i < n and newInterval[0] >= intervals[i][0]: # "equals" for [[1,5]], [1,7] res.append(intervals[i]) i += 1 # if newInterval.start > res[-1].end: if not res: # for [[1,5]], [0, 3] res.append(newInterval) else: if newInterval[0] > res[-1][1]: res.append(newInterval) else: res[-1][1] = max(res[-1][1], newInterval[1]) # print(res) for j in range(i, n): if intervals[j][0] > res[-1][1]: res.append(intervals[j]) else: res[-1][1] = max(res[-1][1], intervals[j][1]) return res def O_NlogN(self, intervals, newInterval): # same as merge Interval intervals.append(newInterval) arr = sorted(intervals, key=lambda interval: interval[0]) res = [] for i in range(len(arr)): if not res or res[-1][1] < arr[i][0]: res.append(arr[i]) else: res[-1][1] = max(res[-1][1], arr[i][1]) return res # @lc code=end
# # @lc app=leetcode id=16 lang=python3 # # [16] 3Sum Closest # # https://leetcode.com/problems/3sum-closest/description/ # # algorithms # Medium (45.73%) # Likes: 1732 # Dislikes: 123 # Total Accepted: 436K # Total Submissions: 953.4K # Testcase Example: '[-1,2,1,-4]\n1' # # Given an array nums of n integers and an integer target, find three integers # in numsย such that the sum is closest toย target. Return the sum of the three # integers. You may assume that each input would have exactly one solution. # # Example: # # # Given array nums = [-1, 2, 1, -4], and target = 1. # # The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). # # # # @lc code=start from typing import List class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: if len(nums) < 3: return [] def helper_bf(nums, target): # res = None g_min_diff = float('inf') res = float('inf') for i in range(0, len(nums)-2): for j in range(i+1, len(nums)-1): for k in range(j+1, len(nums)): diff = abs(nums[i] + nums[j] + nums[k] - target) # print(i, j, k, diff, g_min_diff) if diff < g_min_diff: # print([nums[i], nums[j], nums[k]]) # res = [nums[i], nums[j], nums[k]] g_min_diff = diff res = [nums[i], nums[j], nums[k]] return sum(res) def helper(nums, target): nums.sort(key=lambda x:x) # g_min_diff = float('inf') res = [float('inf')] for i in range(0, len(nums)-2): if i > 0 and nums[i] == nums[i-1]: continue l = i+1 r = len(nums)-1 ## TODO: store sum in advance to make this faster while l < r: arr = [nums[i], nums[l], nums[r]] if abs(sum(arr)-target) < abs(sum(res)-target): res = arr if sum(arr) - target == 0: # break return target elif sum(arr) < target: l += 1 else: r -= 1 return sum(res) return helper(nums, target) # @lc code=end
# # @lc app=leetcode id=126 lang=python3 # # [126] Word Ladder II # # https://leetcode.com/problems/word-ladder-ii/description/ # # algorithms # Hard (20.79%) # Likes: 1701 # Dislikes: 243 # Total Accepted: 181.4K # Total Submissions: 834.8K # Testcase Example: '"hit"\n"cog"\n["hot","dot","dog","lot","log","cog"]' # # Given two words (beginWord and endWord), and a dictionary's word list, find # all shortest transformation sequence(s) from beginWord to endWord, such # that: # # # Only one letter can be changed at a time # Each transformed word must exist in the word list. Note that beginWord is not # a transformed word. # # # Note: # # # Return an empty list if there is no such transformation sequence. # All words have the same length. # All words contain only lowercase alphabetic characters. # You may assume no duplicates in the word list. # You may assume beginWord and endWord are non-empty and are not the same. # # # Example 1: # # # Input: # beginWord = "hit", # endWord = "cog", # wordList = ["hot","dot","dog","lot","log","cog"] # # Output: # [ # โ  ["hit","hot","dot","dog","cog"], # ["hit","hot","lot","log","cog"] # ] # # # Example 2: # # # Input: # beginWord = "hit" # endWord = "cog" # wordList = ["hot","dot","dog","lot","log"] # # Output: [] # # Explanation:ย The endWord "cog" is not in wordList, therefore no possible # transformation. # # # # # # # @lc code=start import string class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: List[List[str]] """ return self.my_again2(beginWord, endWord, wordList) # return self.my_again_one_directional(beginWord, endWord, wordList) # return self.my_again_bi_directional(beginWord, endWord, wordList) """ https://leetcode-cn.com/problems/word-ladder-ii/solution/yan-du-you-xian-bian-li-shuang-xiang-yan-du-you--2/ """ # return self.my_buggy_FAILED(beginWord, endWord, wordList) # return self.findLadders_others_bibfs(beginWord, endWord, wordList) # return self.other_python_clear(beginWord, endWord, wordList) # return self.my_bfs(beginWord, endWord, wordList) # wordSet = set(wordList) # if endWord not in wordSet: # return [] # return self.teacher(beginWord, endWord, wordSet) def my_again2(self, beginWord, endWord, wordList): # https://leetcode-cn.com/problems/word-ladder-ii/solution/ru-guo-ni-fa-xian-kan-bie-ren-de-ti-jie-kan-bu-don/ , SIMILAR TO self.other_python_clear # BTW, level ISSUE in https://leetcode.com/problems/word-ladder-ii/discuss/487138/Python-Easy-Clean-Readable-Code word_set = set(wordList) if endWord not in word_set: return [] level_map = {} word_map = {} Q = collections.deque([beginWord]) visited = set() found = False level = 0 level_map[beginWord] = 0 visited.add(beginWord) while Q: level_size = len(Q) for _ in range(level_size): word = Q.popleft() for i in range(len(word)): for ch in string.ascii_lowercase: new_word = word[:i] + ch + word[i+1:] if new_word not in word_set: continue if new_word in word_map: # parent่ทŸไน‹ๅ‰็š„ไธๅŒ๏ผ›้‚„ๆ˜ฏๅนซๅฎƒๅปบๅœ–๏ผŒๅชๆ˜ฏไธๅ†ๅ…ฅ้šŠ word_map[new_word].append(word) else: word_map[new_word] = [] word_map[new_word].append(word) if new_word in visited: continue if new_word == endWord: found = True level_map[new_word] = level + 1 Q.append(new_word) visited.add(new_word) level += 1 if not found: return [] # print(level_map) # print(word_map) res = [] def dfs(res, path, begin_word, word, word_map, level_map): if word == begin_word: tmp = [begin_word] tmp.extend(path) res.append(tmp[:]) return path.insert(0, word) if word in word_map: for parent in word_map[word]: if level_map[parent] + 1 == level_map[word]: dfs(res, path, begin_word, parent, word_map, level_map) path.pop(0) dfs(res, [], beginWord, endWord, word_map, level_map) return res # def is_valid(self, word, visited): # if def my_again_bi_directional(self, beginWord, endWord, wordList): # ๅ…ˆๅฐ† wordList ๆ”พๅˆฐๅ“ˆๅธŒ่กจ้‡Œ๏ผŒไพฟไบŽๅˆคๆ–ญๆŸไธชๅ•่ฏๆ˜ฏๅฆๅœจ wordList ้‡Œ word_set = set(wordList) res = [] if len(word_set) == 0 or endWord not in word_set: return res successors = defaultdict(set) # ็ฌฌ 1 ๆญฅ๏ผšไฝฟ็”จๅนฟๅบฆไผ˜ๅ…ˆ้ๅކๅพ—ๅˆฐๅŽ็ปง็ป“็‚นๅˆ—่กจ successors # key๏ผšๅญ—็ฌฆไธฒ๏ผŒvalue๏ผšๅนฟๅบฆไผ˜ๅ…ˆ้ๅކ่ฟ‡็จ‹ไธญ key ็š„ๅŽ็ปง็ป“็‚นๅˆ—่กจ found = self.__bidirectional_bfs(beginWord, endWord, word_set, successors) if not found: return res # ็ฌฌ 2 ๆญฅ๏ผšๅŸบไบŽๅŽ็ปง็ป“็‚นๅˆ—่กจ successors ๏ผŒไฝฟ็”จๅ›žๆบฏ็ฎ—ๆณ•ๅพ—ๅˆฐๆ‰€ๆœ‰ๆœ€็Ÿญ่ทฏๅพ„ๅˆ—่กจ path = [beginWord] self.__dfs(beginWord, endWord, successors, path, res) return res def __bidirectional_bfs(self, beginWord, endWord, word_set, successors): visited = set() visited.add(beginWord) visited.add(endWord) begin_visited = set() begin_visited.add(beginWord) end_visited = set() end_visited.add(endWord) found = False forward = True word_len = len(beginWord) while begin_visited: if len(begin_visited) > len(end_visited): begin_visited, end_visited = end_visited, begin_visited forward = not forward next_level_visited = set() for current_word in begin_visited: word_list = list(current_word) for j in range(word_len): origin_char = word_list[j] for k in string.ascii_lowercase: word_list[j] = k next_word = ''.join(word_list) if next_word in word_set: if next_word in end_visited: found = True # ๅœจๅฆไธ€ไพงๆ‰พๅˆฐๅ•่ฏไปฅๅŽ๏ผŒ่ฟ˜้œ€ๆŠŠ่ฟ™ไธ€ๅฑ‚ๅ…ณ็ณปๆทปๅŠ ๅˆฐใ€ŒๅŽ็ปง็ป“็‚นๅˆ—่กจใ€ self.__add_to_successors(successors, forward, current_word, next_word) if next_word not in visited: next_level_visited.add(next_word) self.__add_to_successors(successors, forward, current_word, next_word) word_list[j] = origin_char begin_visited = next_level_visited # ๅ–ไธค้›†ๅˆๅ…จ้ƒจ็š„ๅ…ƒ็ด ๏ผˆๅนถ้›†๏ผŒ็ญ‰ไปทไบŽๅฐ† next_level_visited ้‡Œ็š„ๆ‰€ๆœ‰ๅ…ƒ็ด ๆทปๅŠ ๅˆฐ visited ้‡Œ๏ผ‰ visited |= next_level_visited if found: break return found def __add_to_successors(self, successors, forward, current_word, next_word): if forward: successors[current_word].add(next_word) else: successors[next_word].add(current_word) def __dfs(self, beginWord, endWord, successors, path, res): if beginWord == endWord: res.append(path[:]) return if beginWord not in successors: return successor_words = successors[beginWord] for next_word in successor_words: path.append(next_word) self.__dfs(next_word, endWord, successors, path, res) path.pop() def my_again_one_directional(self, beginWord, endWord, wordList): # ๅ…ˆๅฐ† wordList ๆ”พๅˆฐๅ“ˆๅธŒ่กจ้‡Œ๏ผŒไพฟไบŽๅˆคๆ–ญๆŸไธชๅ•่ฏๆ˜ฏๅฆๅœจ wordList ้‡Œ word_set = set(wordList) res = [] if len(word_set) == 0 or endWord not in word_set: return res successors = defaultdict(set) # ็ฌฌ 1 ๆญฅ๏ผšไฝฟ็”จๅนฟๅบฆไผ˜ๅ…ˆ้ๅކๅพ—ๅˆฐๅŽ็ปง็ป“็‚นๅˆ—่กจ successors # key๏ผšๅญ—็ฌฆไธฒ๏ผŒvalue๏ผšๅนฟๅบฆไผ˜ๅ…ˆ้ๅކ่ฟ‡็จ‹ไธญ key ็š„ๅŽ็ปง็ป“็‚นๅˆ—่กจ found = self.__bfs(beginWord, endWord, word_set, successors) if not found: return res # ็ฌฌ 2 ๆญฅ๏ผšๅŸบไบŽๅŽ็ปง็ป“็‚นๅˆ—่กจ successors ๏ผŒไฝฟ็”จๅ›žๆบฏ็ฎ—ๆณ•ๅพ—ๅˆฐๆ‰€ๆœ‰ๆœ€็Ÿญ่ทฏๅพ„ๅˆ—่กจ path = [beginWord] self.__dfs(beginWord, endWord, successors, path, res) return res def __bfs(self, beginWord, endWord, word_set, successors): queue = deque() queue.append(beginWord) visited = set() visited.add(beginWord) found = False word_len = len(beginWord) next_level_visited = set() while queue: current_size = len(queue) for i in range(current_size): current_word = queue.popleft() word_list = list(current_word) for j in range(word_len): origin_char = word_list[j] for k in string.ascii_lowercase: word_list[j] = k next_word = ''.join(word_list) if next_word in word_set: if next_word not in visited: if next_word == endWord: found = True # ้ฟๅ…ไธ‹ๅฑ‚ๅ…ƒ็ด ้‡ๅคๅŠ ๅ…ฅ้˜Ÿๅˆ—๏ผŒ่ฟ™้‡Œๆ„Ÿ่ฐข https://leetcode-cn.com/u/zhao-da-ming/ ไผ˜ๅŒ–ไบ†่ฟ™ไธช้€ป่พ‘ if next_word not in next_level_visited: next_level_visited.add(next_word) queue.append(next_word) successors[current_word].add(next_word) word_list[j] = origin_char if found: break # ๅ–ไธค้›†ๅˆๅ…จ้ƒจ็š„ๅ…ƒ็ด ๏ผˆๅนถ้›†๏ผŒ็ญ‰ไปทไบŽๅฐ† next_level_visited ้‡Œ็š„ๆ‰€ๆœ‰ๅ…ƒ็ด ๆทปๅŠ ๅˆฐ visited ้‡Œ๏ผ‰ visited |= next_level_visited next_level_visited.clear() return found def __dfs(self, beginWord, endWord, successors, path, res): if beginWord == endWord: res.append(path[:]) return if beginWord not in successors: return successor_words = successors[beginWord] for next_word in successor_words: path.append(next_word) self.__dfs(next_word, endWord, successors, path, res) path.pop() def other_python_clear(self, beginWord, endWord, wordList): def dfs(word): tmp.append(word) if word == endWord: res.append(list(tmp)) tmp.pop() return if word in graph: for nei in graph[word]: if dist[nei] == dist[word]+1: dfs(nei) tmp.pop() wordSet = set(wordList) if endWord not in wordSet: return [] alphabets = 'abcdefghijklmnopqrstuvwxyz' q = collections.deque([(beginWord, 0)]) dist = {} graph = collections.defaultdict(set) seen = set([beginWord]) while q: u, d = q.popleft() dist[u] = d for i in range(len(u)): for alph in alphabets: if alph != u[i]: new = u[:i]+alph+u[i+1:] if new in wordSet: graph[u].add(new) graph[new].add(u) if new not in seen: q.append((new, d+1)) seen.add(new) if endWord not in dist: return [] res = [] tmp = [] dfs(beginWord) return res # https://leetcode.com/problems/word-ladder-ii/discuss/241584/Python-solution def findLadders_others_bibfs(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: tree, words, n = collections.defaultdict(set), set(wordList), len(beginWord) if endWord not in wordList: return [] found, bq, eq, nq, rev = False, {beginWord}, {endWord}, set(), False while bq and not found: words -= set(bq) for x in bq: for i in range(n): first, second = x[:i], x[i+1:] for c in 'qwertyuiopasdfghjklzxcvbnm': y = first + c + second if y in words: if y in eq: found = True else: nq.add(y) tree[y].add(x) if rev else tree[x].add(y) bq, nq = nq, set() if len(bq) > len(eq): bq, eq, rev = eq, bq, not rev def bt(x): return [[x]] if x == endWord else [[x] + rest for y in tree[x] for rest in bt(y)] return bt(beginWord) # https://leetcode.com/problems/word-ladder-ii/discuss/269012/Python-BFS%2BBacktrack-Greatly-Improved-by-bi-directional-BFS def my_bfs(self, beginWord, endWord, wordList): if endWord not in wordList: return [] wordSet = set(wordList) # faster checks against dictionary layer = {} layer[beginWord] = [[beginWord]] # stores current word and all possible sequences how we got to it while layer: # print(layer) newlayer = collections.defaultdict(list) # returns [] on missing keys, just to simplify code for word in layer: if word == endWord: return layer[word] # return all found sequences for i in range(len(word)): # change every possible letter and check if it's in dictionary for c in 'abcdefghijklmnopqrstuvwxyz': newWord = word[:i] + c + word[i+1:] if newWord in wordSet: newlayer[newWord] += [j + [newWord] for j in layer[word]] # add new word to all sequences and form new layer element wordSet -= set(newlayer.keys()) # remove from dictionary to prevent loops layer = newlayer # move down to new layer return [] # https://leetcode.com/problems/word-ladder-ii/discuss/40482/Python-simple-BFS-layer-by-layer ''' "hit -- "["hot"-- "dot" -- "dog" --- "cog"] \ | | / -- "lot" -- "log" -- 1). Is length of each string the same? == >Yes ''' def teacher(self, start, end, dict): dict.add(start) dict.add(end) distance = {} self.bfs(end, distance, dict) results = [] self.dfs(start, end, distance, dict, [start], results) return results def bfs(self, start, distance, dict): distance[start] = 0 queue = deque([start]) while queue: word = queue.popleft() for next_word in self.get_next_words(word, dict): if next_word not in distance: distance[next_word] = distance[word] + 1 queue.append(next_word) def get_next_words(self, word, dict): words = [] for i in range(len(word)): for c in 'abcdefghijklmnopqrstuvwxyz': next_word = word[:i] + c + word[i + 1:] if next_word != word and next_word in dict: words.append(next_word) return words def dfs(self, curt, target, distance, dict, path, results): if curt == target: results.append(list(path)) return for word in self.get_next_words(curt, dict): if distance[word] != distance[curt] - 1: continue path.append(word) self.dfs(word, target, distance, dict, path, results) path.pop() def my_buggy_FAILED(self, beginWord, endWord, wordList): # ISSUES: # 1. early return and the not complete distance dict... """ VERSION 0625, SAME as sisi_bibfs """ if not beginWord or not endWord: return [] """ hit --> h*t ==> hot --> *ot ==> dot --> do* ==> dog --> *og ==> cog ==> lot --> lo* ==> log --> *og ==> cog """ word_set = set(wordList) # for Quick Access later on if endWord not in word_set: return [] # if beginWord in word_set: # word_set.remove(beginWord) # Build Graph map_d = {} # edges for i in range(len(word_set)): word = wordList[i] for j in range(len(word)): pattern = word[:j] + '*' + word[j+1:] map_d[pattern] = map_d.get(pattern, []) + [word] Q = collections.deque() end_Q = collections.deque() distance = {} end_distance = {} Q.append((beginWord, 1)) end_Q.append((endWord, 1)) distance[beginWord] = 1 end_distance[endWord] = 1 path = defaultdict(set) end_path = defaultdict(set) meetup_depth = sys.maxsize while Q and end_Q: begin_meetup_depth = self.bfs2(Q, distance, end_distance, map_d, path) meetup_depth = min(meetup_depth, begin_meetup_depth) if meetup_depth != sys.maxsize: break end_meetup_depth = self.bfs2(end_Q, end_distance, distance, map_d, end_path) meetup_depth = min(meetup_depth, end_meetup_depth) if meetup_depth != sys.maxsize: break print(meetup_depth) # print('path: ', path) # print('end_path: ', end_path) if meetup_depth == sys.maxsize: return [] end_path_reversed = {} for key, val in end_path.items(): for word in val: end_path_reversed[word] = end_path_reversed.get(word, []) + [key] end_res = [] end_path_reversed.update(path) print('end_path_reversd: ', end_path_reversed) self.dfs_mine(endWord, end_path_reversed, [endWord], end_res, meetup_depth) return end_res def dfs_mine(self, end, end_path, item, res, meetup_depth): # if end not in end_path: if len(item) == meetup_depth: res.append(item[::-1].copy()) return if end not in end_path: return for word in end_path[end]: item.append(word) self.dfs_mine(word, end_path, item, res, meetup_depth) item.pop() def bfs2(self, Q, distance, other_distance, map_d, path): meetup_depth = sys.maxsize # for _ in range(len(Q)): len_Q = len(Q) for _ in range(len_Q): now_word, now_depth = Q.popleft() for i in range(len(now_word)): pattern = now_word[:i] + "*" + now_word[i+1:] for next_word in map_d.get(pattern, []): if next_word in other_distance: # path[next_word] = path.get(next_word, []) + [now_word] path[next_word].add(now_word) meetup_depth = now_depth + other_distance[next_word] if next_word not in distance: Q.append((next_word, now_depth+1)) distance[next_word] = now_depth + 1 # path[next_word] = path.get(next_word, []) + [now_word] path[next_word].add(now_word) return meetup_depth # -1 means not meetup yet # return -1 # @lc code=end
# # @lc app=leetcode id=305 lang=python3 # # [305] Number of Islands II # # https://leetcode.com/problems/number-of-islands-ii/description/ # # algorithms # Hard (40.15%) # Likes: 841 # Dislikes: 21 # Total Accepted: 76.8K # Total Submissions: 191.4K # Testcase Example: '3\n3\n[[0,0],[0,1],[1,2],[2,1]]' # # A 2d grid map of m rows and n columns is initially filled with water. We may # perform an addLand operation which turns the water at position (row, col) # into a land. Given a list of positions to operate, count the number of # islands after each addLand operation. An island is surrounded by water and is # formed by connecting adjacent lands horizontally or vertically. You may # assume all four edges of the grid are all surrounded by water. # # Example: # # # Input: m = 3, n = 3, positions = [[0,0], [0,1], [1,2], [2,1]] # Output: [1,1,2,3] # # # Explanation: # # Initially, the 2d grid grid is filled with water. (Assume 0 represents water # and 1 represents land). # # # 0 0 0 # 0 0 0 # 0 0 0 # # # Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. # # # 1 0 0 # 0 0 0 Number of islands = 1 # 0 0 0 # # # Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. # # # 1 1 0 # 0 0 0 Number of islands = 1 # 0 0 0 # # # Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. # # # 1 1 0 # 0 0 1 Number of islands = 2 # 0 0 0 # # # Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. # # # 1 1 0 # 0 0 1 Number of islands = 3 # 0 1 0 # # # Follow up: # # Can you do it in time complexity O(k log mn), where k is the length of the # positions? # # # @lc code=start class UF_w_rank(object): def __init__(self, n): self._parents = [idx for idx in range(n+1)] self._rank = [1 for idx in range(n+1)] def find(self, u): if u != self._parents[u]: self._parents[u] = self.find(self._parents[u]) return self._parents[u] def union(self, u, v): pu, pv = self.find(u), self.find(v) if pu == pv: return False # self._parents[pv] = pu # return True if self._rank[u] > self._rank[v]: self._parents[pv] = pu elif self._rank[u] < self._rank[v]: self._parents[pu] = pv else: self._parents[pv] = pu self._rank[pu] += 1 self._rank[pv] += 1 return True class UF(object): def __init__(self, n): self._parents = [idx for idx in range(n+1)] # self._rank def find(self, u): if u != self._parents[u]: self._parents[u] = self.find(self._parents[u]) return self._parents[u] def union(self, u, v): pu, pv = self.find(u), self.find(v) if pu == pv: return False self._parents[pv] = pu return True class Solution(object): def areSentencesSimilarTwo(self, words1, words2, pairs): """ :type words1: List[str] :type words2: List[str] :type pairs: List[List[str]] :rtype: bool """ m, n = len(words1), len(words2) if m != n or not pairs: return False uf = UF(len(pairs) * 2) # d = collections.defaultdict(int) d = {} for w1, w2 in pairs: # w1--> u # w2--> v # if w1 not in d: # d[w1] = len(d) u = d[w1] = d.get(w1, len(d)) v = d[w2] = d.get(w2, len(d)) # print(w1,u,w2,v) uf.union(u, v) for i in range(m): w1, w2 = words1[i], words2[i] if w1 == w2: # may both not in d, but are same continue # w1--> u # w2--> v if w1 not in d or w2 not in d: return False u, v = d[w1], d[w2] if uf.find(u) != uf.find(v): return False return True def BF(): # Not finished yet m, n = len(words1), len(words2) if m != n or not pairs: return False d = collections.defaultdict(set) for u, v in range(pairs): d[u].add(v) d[v].add(u) for i in range(m): if not self.is_similar(words1[i], words2[i], d): return False return True def is_similar(self, w1, w2, d): if w1 not in d and w2 not in d: return False if w1 in d: return self.is_similar( w2) # ==> many expansion! if w2 in d and w1 in d[w2]: return True # @lc code=end
# # @lc app=leetcode id=200 lang=python3 # # [200] Number of Islands # # https://leetcode.com/problems/number-of-islands/description/ # # algorithms # Medium (45.10%) # Likes: 4620 # Dislikes: 173 # Total Accepted: 609.1K # Total Submissions: 1.3M # Testcase Example: '[["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]' # # Given a 2d grid map of '1's (land) and '0's (water), count the number of # islands. An island is surrounded by water and is formed by connecting # adjacent lands horizontally or vertically. You may assume all four edges of # the grid are all surrounded by water. # # Example 1: # # # Input: # 11110 # 11010 # 11000 # 00000 # # Output:ย 1 # # # Example 2: # # # Input: # 11000 # 11000 # 00100 # 00011 # # Output: 3 # # # @lc code=start ''' 1 1 1 1 0 1 1 0 1 0 1 1 0 1 0 0 0 0 0 0 ''' # for # for # bfs_graph class UnionFindSet: def __init__(self, n): self._parents = [i for i in range(n+1)] self._ranks = [1 for i in range(n+1)] def Find(self, u): if u != self._parents[u]: self._parents[u] = self.Find(self._parents[u]) return self._parents[u] # while u != self._parents[u]: # self._parents[u] = self._parents[self._parents[u]] # u = self._parents[u] # return u def Union(self, u, v): pu = self.Find(u) pv = self.Find(v) if pu == pv: return False if self._ranks[pv] < self._ranks[pu]: self._parents[pv] = pu elif self._ranks[pv] > self._ranks[pu]: self._parents[pu] = pv else: self._parents[pv] = pu self._ranks[pu] += 1 return True ''' 1 1 1 1 0 1 1 0 1 0 1 1 0 1 0 0 0 0 0 0 ''' from collections import deque from typing import List DIRECTIONS = [[0,1], [0,-1], [1,0], [-1,0]] class Solution: def numIslands(self, grid: List[List[str]]) -> int: if not grid or not grid[0]: return 0 # return self.dfs_main(grid) n, m = len(grid), len(grid[0]) uf = UnionFindSet(n*m) count = n * m for i in range(n): for j in range(m): if grid[i][j] == '1': if j < m-1 and grid[i][j+1] == '1': # if uf.Union(grid[i][j], grid[i][j+1]): if uf.Union(i*m+j, i*m+j+1): count -= 1 if i < n-1 and grid[i+1][j] == '1': # if uf.Union(grid[i][j], grid[i+1][j]): if uf.Union(i*m+j, (i+1)*m+j): count -= 1 else:# if grid[i][j] == '0': count -= 1 # print(count) return count def dfs_main(self, grid): n, m = len(grid), len(grid[0]) visited = set() count = 0 for i in range(n): for j in range(m): if grid[i][j] == '1' and (i, j) not in visited: self.dfs(grid, i, j, visited) count += 1 # print('count: ', count) return count def dfs(self, grid, i, j, visited): visited.add((i, j)) # print(i, j) for delta_i, delta_j in DIRECTIONS: next_i = i + delta_i next_j = j + delta_j if self.is_valid(grid, next_i, next_j, visited): self.dfs(grid, next_i, next_j, visited) def is_valid(self, grid, x, y, visited): if x < 0 or y < 0 or x >= len(grid) or y >= len(grid[0]): return False if (x, y) in visited: return False if grid[x][y] == '0': return False return True def method_UF(self, grid): # return self.numIslands_old(grid) # def find(parent, i): # if parent[i] != i: # parent[i] = find(parent[i]) # def union(parent, x, y): # root_X = find(x) # root_Y = find(y) # if root_x != root_y: # n, m = len(grid),len(grid[0]) # if not n or not m: # return 0 # uf = UnionFindSet(n*m) # count = 0 # visited = set() # # visited.add(()) # for i in range(n): # for j in range(m): # if grid[i][j] == '1': # visited.add((i, j)) # for delta_x, delta_y in DIRECTIONS: # next_x = i + delta_x # next_y = j + delta_y # if self.is_valid_uf(next_x, next_y, grid, visited): # uf.Union(m*i+j, m*next_x+next_y) # visited.add((next_x, next_y)) # count += 1 # return count pass def is_valid_uf(self, x, y, grid, visited): if x < 0 or y < 0 or x >= len(grid) or y >= len(grid[0]): return False if grid[x][y] == '0': return False if (x, y) in visited: return False return True def numIslands_old(self, grid: List[List[str]]) -> int: """ Time complexity : O(Mร—N) where M is the number of rows and N is the number of columns. Space complexity : O(min(M,N)) because in worst case where the grid is filled with lands, the size of queue can grow up to min(M,N). """ if not grid or not grid[0]: return 0; # visited = ['X'*len(grid[0]) for i in range(len(grid))] count = 0 for i in range(len(grid)): for j in range(len(grid[0])): # Starts BFS if grid[i][j] == '1': self.helper(i, j, grid) count += 1 return count def helper(self, r, c, grid): Q = deque() Q.append((r, c)) dr = [-1, 0, 1, 0] dc = [0, 1, 0, -1] while Q: I, J = Q.popleft() for idx in range(4): i, j = I+dr[idx], J+dc[idx] if i<0 or j<0 or i>len(grid)-1 or j>len(grid[0])-1 or grid[i][j] != '1': continue Q.append((i, j)) grid[i][j] = 'X' def helper_(self, i, j, grid): Q = deque() # Q.push((grid[i][j], i, j)) Q.append((i, j)) while Q: i, j = Q.popleft() # up, down, left, right if i > 0 and grid[i-1][j] == '1' : Q.append((i-1, j)) grid[i-1][j] = 'X' if j > 0 and grid[i][j-1] == '1': Q.append((i, j-1)) grid[i][j-1] = 'X' if i < len(grid)-1 and grid[i+1][j] == '1': Q.append((i+1, j)) grid[i+1][j] = 'X' if j < len(grid[0])-1 and grid[i][j+1] == '1': Q.append((i, j+1)) grid[i][j+1] = 'X' def numIslands_oldold(self, grid: List[List[str]]) -> int: if not grid or not grid[0]: return 0 # arr = [[0 for j in range(len(grid[0])+1)] for i in range(len(grid)+1)] count = 0 arr = np.pad(grid, ((1,1), (1,1))) print(arr) # for i in range(1, len(arr)): # for j in range(1, len(arr[0])): for i in range(1, len(arr)-1): for j in range(1, len(arr[0])-1): if arr[i][j] == '1': self.bfs((arr[i][j], i, j), arr) count += 1 return count def bfs(self, item, arr): Q = deque() Q.append(item) while Q: val, i, j = Q.popleft() if val == '1': arr[i][j] = '0' if arr[i][j-1] == '1': # '0' is True... Q.append((arr[i][j-1], i, j-1)) arr[i][j-1] = 'x' if arr[i-1][j] == '1': Q.append((arr[i-1][j], i-1, j)) arr[i-1][j] = 'x' if arr[i][j+1] == '1': Q.append((arr[i][j+1], i, j+1)) arr[i][j+1] = 'x' if arr[i+1][j] == '1': Q.append((arr[i+1][j], i+1, j)) arr[i+1][j] = 'x' print(Solution().numIslands([["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]])) # @lc code=end
# # @lc app=leetcode id=77 lang=python3 # # [77] Combinations # # https://leetcode.com/problems/combinations/description/ # # algorithms # Medium (52.54%) # Likes: 1336 # Dislikes: 66 # Total Accepted: 278.5K # Total Submissions: 520.5K # Testcase Example: '4\n2' # # Given two integers n and k, return all possible combinations of k numbers out # of 1 ... n. # # Example: # # # Input:ย n = 4, k = 2 # Output: # [ # โ  [2,4], # โ  [3,4], # โ  [2,3], # โ  [1,2], # โ  [1,3], # โ  [1,4], # ] # # # # @lc code=start class Solution: def combine(self, n: int, k: int) -> List[List[int]]: self.result = [] # self.helper_old(n, k, 0, [], 0) res = [] self.helper(n, k, [], 0, res) return res # EITHER return self.result # EITHER def helper(self, n, k, item, idx, res): # if idx == k: if len(item) == k: res.append(item.copy()) self.result.append(item.copy()) return for i in range(idx, n): item.append(i+1) # self.helper(n, k, item, idx+1) self.helper(n, k, item, i+1, res) item.pop() def helper_old(self, n, k, i, item, level): if len(item) == k: self.result.append(item.copy()) return if i > n: return item.append(i) # 1 self.helper_old(n, k, i+1, item, level+1) item.pop() self.helper_old(n, k, i+2, item, level+1) "" # @lc code=end
# # @lc app=leetcode id=354 lang=python3 # # [354] Russian Doll Envelopes # # https://leetcode.com/problems/russian-doll-envelopes/description/ # # algorithms # Hard (34.98%) # Likes: 981 # Dislikes: 37 # Total Accepted: 62.8K # Total Submissions: 178.5K # Testcase Example: '[[5,4],[6,4],[6,7],[2,3]]' # # You have a number of envelopes with widths and heights given as a pair of # integers (w, h). One envelope can fit into another if and only if both the # width and height of one envelope is greater than the width and height of the # other envelope. # # What is the maximum number of envelopes can you Russian doll? (put one inside # other) # # Note: # Rotation is not allowed. # # Example: # # # # Input: [[5,4],[6,4],[6,7],[2,3]] # Output: 3 # Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] # => [5,4] => [6,7]). # # # # # @lc code=start class Solution: def maxEnvelopes(self, envelopes: List[List[int]]) -> int: if not envelopes: return 0 elif len(envelopes) == 1: return 1 arr = sorted(envelopes, key=lambda envelope: (envelope[0], -envelope[1])) # return self.helper_FAILED(arr) # return self.O_NxN(arr) return self.O_NxlogN(arr) def O_NxlogN(self, envelopes): dp = [] for i in range(len(envelopes)): if not dp: dp.append(envelopes[i][1]) continue # if envelopes[i][0] > dp[-1] and envelopes[i][1] > dp[-1][1]: if envelopes[i][1] > dp[-1]: dp.append(envelopes[i][1]) else: target = envelopes[i][1] start, end = 0, len(dp) # To find elem >= envelopes[i][1] while start + 1 < end: mid = start + (end-start)//2 if dp[mid] >= target: end = mid else: start = mid if dp[start] >= target: dp[start] = target elif dp[end] >= target: dp[end] = target # print(dp) return len(dp) def O_NxN(self, envelopes): dp = [] for i in range(len(envelopes)): if not dp: dp.append(envelopes[i][1]) continue # if envelopes[i][0] > dp[-1] and envelopes[i][1] > dp[-1][1]: if envelopes[i][1] > dp[-1]: dp.append(envelopes[i][1]) else: for j in range(len(dp)): if envelopes[i][1] <= dp[j]: dp[j] = envelopes[i][1] break # print(dp) return len(dp) def helper_FAILED(self, envelopes): dp = [] for envelope in envelopes: if not dp: dp.append(envelope) continue if envelope[0] > dp[-1][0] and envelope[1] > dp[-1][1] : dp.append(envelope) else: for j in range(len(dp)): # NO USE # if envelope[0] <= dp[j][0] and envelope[1] > dp[j][1]: # break # elif envelope[0] > dp[j][0] and envelope[1] <= dp[j][1]: # break if envelope[0] <= dp[j][0] and envelope[1] <= dp[j][1]: dp[j] = envelope break print(dp) return len(dp) # @lc code=end
# # @lc app=leetcode id=64 lang=python3 # # [64] Minimum Path Sum # # https://leetcode.com/problems/minimum-path-sum/description/ # # algorithms # Medium (51.32%) # Likes: 2389 # Dislikes: 52 # Total Accepted: 340.6K # Total Submissions: 655.4K # Testcase Example: '[[1,3,1],[1,5,1],[4,2,1]]' # # Given a m x n grid filled with non-negative numbers, find a path from top # left to bottom right which minimizes the sum of all numbers along its path. # # Note: You can only move either down or right at any point in time. # # Example: # # # Input: # [ # [1,3,1], # โ  [1,5,1], # โ  [4,2,1] # ] # Output: 7 # Explanation: Because the path 1โ†’3โ†’1โ†’1โ†’1 minimizes the sum. # # # # @lc code=start """ [ [1,3,1], [1,5,1], [4,2,1] ] 0 0 0. 0 0 1 4 5 0 2 min(2,4)+5 min(7,5)+1 0 6 min(6,7)+2 min(8,6)+1 """ class Solution: def minPathSum(self, grid: List[List[int]]) -> int: # return self.O_MxN(grid) return self.O_N(grid) def O_N(self, grid): if not grid or not grid[0]: return 0 m, n = len(grid), len(grid[0]) dp = [0 for j in range(n)] # dp[0] = grid for i in range(m): for j in range(n): # dp[j] = if i == 0 and j == 0: dp[j] = grid[i][j] elif i == 0: dp[j] = dp[j-1] + grid[i][j] elif j == 0: dp[j] = dp[j] + grid[i][j] else: dp[j] = min(dp[j], dp[j-1]) + grid[i][j] return dp[-1] def O_MxN(self, grid): if not grid or not grid[0]: return 0 dp = [[0 for j in range(len(grid[0]))] for i in range(len(grid))] for i in range(len(dp)): for j in range(len(dp[0])): if i == 0 and j == 0: dp[i][j] = grid[i][j] elif i == 0: dp[i][j] = dp[i][j-1] + grid[i][j] elif j == 0: dp[i][j] = dp[i-1][j] + grid[i][j] else: dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j] return dp[-1][-1] def minPathSum_old(self, grid: List[List[int]]) -> int: if not grid or not grid[0]: return 0 dp = [[0 for j in range(len(grid[0])+1)] for i in range(len(grid)+1)] for i in range(1, len(dp)): for j in range(1, len(dp[0])): if i == 1: dp[i][j] = dp[i][j-1] + grid[i-1][j-1] elif j == 1: dp[i][j] = dp[i-1][j] + grid[i-1][j-1] else: # (0 <= i <=len(dp)-1) and (0 <=j <= len(dp[0])-1): dp[i][j] = min(dp[i][j-1], dp[i-1][j]) + grid[i-1][j-1] # print(dp) return dp[-1][-1] # @lc code=end
# # @lc app=leetcode id=296 lang=python3 # # [296] Best Meeting Point # # https://leetcode.com/problems/best-meeting-point/description/ # # algorithms # Hard (57.00%) # Likes: 442 # Dislikes: 36 # Total Accepted: 34.7K # Total Submissions: 60.6K # Testcase Example: '[[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]]' # # A group of two or more people wants to meet and minimize the total travel # distance. You are given a 2D grid of values 0 or 1, where each 1 marks the # home of someone in the group. The distance is calculated using Manhattan # Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|. # # Example: # # # Input: # # 1 - 0 - 0 - 0 - 1 # | | | | | # 0 - 0 - 0 - 0 - 0 # | | | | | # 0 - 0 - 1 - 0 - 0 # # Output: 6 # # Explanation: Given three people living at (0,0), (0,4), and # (2,2): # The point (0,2) is an ideal meeting point, as the total travel # distance # of 2+2+2=6 is minimal. So return 6. # # # @lc code=start class DataType: HOUSE = 1 EMPTY = 0 DIRECTIONS = [[0, 1], [0, -1], [1, 0], [-1, 0]] class Solution: """ @param grid: a 2D grid @return: An integer """ # def shortestDistance(self, grid): def minTotalDistance(self, grid: List[List[int]]) -> int: # return self.empty_oriented(grid) # return self.house_oriented(grid) return self.find_centroid(grid) def find_centroid(self, grid): """ [ [0,1,0,0], [1,0,1,1], [0,1,0,0] ] """ # One axis row_count = [sum(row) for row in grid] col_count = [0]* len(grid[0]) row_dist = [0]* len(grid) col_dist = [0]* len(grid[0]) output = sys.maxsize for i in range(len(grid)): for j in range(len(grid[0])): col_count[j] += grid[i][j] for index_p in range(len(row_count)): for index_h in range(len(row_count)): row_dist[index_p] += abs(index_h - index_p) * row_count[index_h] for index_p in range(len(col_count)): for index_h in range(len(col_count)): col_dist[index_p] += abs(index_h - index_p) * col_count[index_h] print(row_count) print(col_count) print(row_dist) print(col_dist) for i in range(len(grid)): for j in range(len(grid[0])): # if grid[i][j] == 1: # Should add this when building post-office # continue output = min(output, row_dist[i] + col_dist[j]) return output def house_oriented(self, grid): # write your code here """ [ [0,1,0,0], [1,0,1,1], [0,1,0,0] ] """ n, m = len(grid), len(grid[0]) dist = [[0 for _ in range(m)] for _ in range(n)] reachable_count = [[0 for _ in range(m)] for _ in range(n)] house_count = 0 for i in range(n): for j in range(m): if grid[i][j] == DataType.HOUSE: house_count += 1 self.bfs_house_oriented(grid, i, j, dist, reachable_count) print(f'dist: {dist}') print(f'reachable_count: {reachable_count}') min_dist = sys.maxsize for i in range(n): for j in range(m): if reachable_count[i][j] == house_count and dist[i][j] < min_dist : # and dist[i][j] != 0: # shouldn't be a HOUSE, should be handled in reachable_count min_dist = dist[i][j] if min_dist == sys.maxsize: return -1 return min_dist def bfs_house_oriented(self, grid, x, y, dist, reachable_count): Q = collections.deque() Q.append([x, y]) visited = set() visited.add((x, y)) cur_dist = 0 while Q: for _ in range(len(Q)): now_x, now_y = Q.popleft() dist[now_x][now_y] += cur_dist for delta_x, delta_y in DIRECTIONS: next_x = now_x + delta_x next_y = now_y + delta_y if self.is_valid(next_x, next_y, grid, visited): Q.append([next_x, next_y]) visited.add((next_x, next_y)) reachable_count[next_x][next_y] += 1 dist[next_x][next_y] # if grid[next_x][next_y] == DataType.HOUSE: cur_dist += 1 def is_valid(self, x, y, grid, visited): if x < 0 or y < 0 or x >= len(grid) or y >= len(grid[0]): return False if (x, y) in visited: return False # if grid[x][y] == DataType.HOUSE: # return False return True # O(N^4) def empty_oriented(self, grid): # write your code here """ [ [0,1,0,0], [1,0,1,1], [0,1,0,0] ] """ g_min = 0 # pos = [0, 0] for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == DataType.EMPTY: g_min = max(g_min, self.bfs_BF(grid, i, j)) return g_min def bfs_BF(self, grid, x, y): Q = collections.deque() Q.append([x, y]) visited = set((x, y)) distance = 0 while Q: for _ in range(len(Q)): now_x, now_y = Q.popleft() for delta_x, delta_y in DIRECTIONS: next_x = now_x + delta_x next_y = now_y + delta_y if self.is_valid(next_x, next_y, grid, visited): Q.append([next_x, next_y]) visited.add((next_x, next_y)) if grid[next_x][next_y] == DataType.HOUSE: pass return distance # def is_valid(self, x, y, grid, visited): # pass # @lc code=end
# # @lc app=leetcode id=737 lang=python3 # # [737] Sentence Similarity II # # https://leetcode.com/problems/sentence-similarity-ii/description/ # # algorithms # Medium (45.71%) # Likes: 492 # Dislikes: 31 # Total Accepted: 41.2K # Total Submissions: 90.1K # Testcase Example: '["great","acting","skills"]\n' + '["fine","drama","talent"]\n' + '[["great","good"],["fine","good"],["drama","acting"],["skills","talent"]]' # # Given two sentences words1, words2 (each represented as an array of strings), # and a list of similar word pairs pairs, determine if two sentences are # similar. # # For example, words1 = ["great", "acting", "skills"] and words2 = ["fine", # "drama", "talent"] are similar, if the similar word pairs are pairs = # [["great", "good"], ["fine", "good"], ["acting","drama"], # ["skills","talent"]]. # # Note that the similarity relation is transitive. For example, if "great" and # "good" are similar, and "fine" and "good" are similar, then "great" and # "fine" are similar. # # Similarity is also symmetric. For example, "great" and "fine" being similar # is the same as "fine" and "great" being similar. # # Also, a word is always similar with itself. For example, the sentences words1 # = ["great"], words2 = ["great"], pairs = [] are similar, even though there # are no specified similar word pairs. # # Finally, sentences can only be similar if they have the same number of words. # So a sentence like words1 = ["great"] can never be similar to words2 = # ["doubleplus","good"]. # # Note: # # # The length of words1 and words2 will not exceed 1000. # The length of pairs will not exceed 2000. # The length of each pairs[i] will be 2. # The length of each words[i] and pairs[i][j] will be in the range [1, 20]. # # # # # # @lc code=start class UF_w_rank(object): def __init__(self, n): self._parents = [idx for idx in range(n+1)] self._rank = [1 for idx in range(n+1)] def find(self, u): if u != self._parents[u]: self._parents[u] = self.find(self._parents[u]) return self._parents[u] def union(self, u, v): pu, pv = self.find(u), self.find(v) if pu == pv: return False # self._parents[pv] = pu # return True if self._rank[u] > self._rank[v]: self._parents[pv] = pu elif self._rank[u] < self._rank[v]: self._parents[pu] = pv else: self._parents[pv] = pu self._rank[pu] += 1 self._rank[pv] += 1 return True class UF(object): def __init__(self, n): self._parents = [idx for idx in range(n+1)] # self._rank def find(self, u): if u != self._parents[u]: self._parents[u] = self.find(self._parents[u]) return self._parents[u] def union(self, u, v): pu, pv = self.find(u), self.find(v) if pu == pv: return False self._parents[pv] = pu return True class Solution(object): def areSentencesSimilarTwo(self, words1, words2, pairs): """ :type words1: List[str] :type words2: List[str] :type pairs: List[List[str]] :rtype: bool """ m, n = len(words1), len(words2) if m != n or not pairs: return False uf = UF(len(pairs) * 2) # d = collections.defaultdict(int) d = {} for w1, w2 in pairs: # w1--> u # w2--> v # if w1 not in d: # d[w1] = len(d) u = d[w1] = d.get(w1, len(d)) v = d[w2] = d.get(w2, len(d)) # print(w1,u,w2,v) uf.union(u, v) for i in range(m): w1, w2 = words1[i], words2[i] if w1 == w2: # may both not in d, but are same continue # w1--> u # w2--> v if w1 not in d or w2 not in d: return False u, v = d[w1], d[w2] if uf.find(u) != uf.find(v): return False return True def BF(): # Not finished yet m, n = len(words1), len(words2) if m != n or not pairs: return False d = collections.defaultdict(set) for u, v in range(pairs): d[u].add(v) d[v].add(u) for i in range(m): if not self.is_similar(words1[i], words2[i], d): return False return True def is_similar(self, w1, w2, d): if w1 not in d and w2 not in d: return False if w1 in d: return self.is_similar( w2) # ==> many expansion! if w2 in d and w1 in d[w2]: return True # @lc code=end
# # @lc app=leetcode id=773 lang=python3 # # [773] Sliding Puzzle # # https://leetcode.com/problems/sliding-puzzle/description/ # # algorithms # Hard (57.38%) # Likes: 643 # Dislikes: 21 # Total Accepted: 36.8K # Total Submissions: 62.6K # Testcase Example: '[[1,2,3],[4,0,5]]' # # On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, # and an empty square represented by 0. # # A move consists of choosing 0ย and a 4-directionally adjacent number and # swapping it. # # The state of the board is solved if and only if the board is # [[1,2,3],[4,5,0]]. # # Given a puzzle board, return the least number of moves required so that the # state of the board is solved. If it is impossible for the state of the board # to be solved, return -1. # # Examples: # # # Input: board = [[1,2,3],[4,0,5]] # Output: 1 # Explanation: Swap the 0 and the 5 in one move. # # # # Input: board = [[1,2,3],[5,4,0]] # Output: -1 # Explanation: No number of moves will make the board solved. # # # # Input: board = [[4,1,2],[5,0,3]] # Output: 5 # Explanation: 5 is the smallest number of moves that solves the board. # An example path: # After move 0: [[4,1,2],[5,0,3]] # After move 1: [[4,1,2],[0,5,3]] # After move 2: [[0,1,2],[4,5,3]] # After move 3: [[1,0,2],[4,5,3]] # After move 4: [[1,2,0],[4,5,3]] # After move 5: [[1,2,3],[4,5,0]] # # # # Input: board = [[3,2,4],[1,5,0]] # Output: 14 # # # Note: # # # board will be a 2 x 3 array as described above. # board[i][j] will be a permutation of [0, 1, 2, 3, 4, 5]. # # # # @lc code=start DIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)] class Solution: def slidingPuzzle(self, board: List[List[int]]) -> int: final_board = [[1, 2, 3], [4, 5, 0]] # final_state = self.board_to_state(final_board) init_board = board Q = collections.deque() distance = {} for x in range(len(board)): for y in range(len(board[0])): if board[x][y] == 0: start_x, start_y = x, y try: start_x except: return -1 init_state = self.board_2_state(init_board) Q.append((start_x, start_y, init_state)) # init_state should be in tuple or string # steps = 0 distance[self.board_2_state(init_board)] = 0 while Q: x, y, now_state = Q.popleft() if self.state_2_board(now_state) == final_board: return distance[now_state] for next_x, next_y, next_state in self.find_next_states(x, y, now_state, distance): Q.append((next_x, next_y, next_state)) distance[(next_state)] = distance[(now_state)] + 1 # steps += 1 return -1 def find_next_states(self, x, y, state, distance): next_states_list = [] for delta_x, delta_y in DIRECTIONS: next_x = x + delta_x next_y = y + delta_y if self.is_valid(state, next_x, next_y): board = self.state_2_board(state) # tuple to list board[x][y], board[next_x][next_y] = board[next_x][next_y], board[x][y] # board[x][y], board[next_x][next_y] = board[next_x][next_y], board[x][y] next_state = self.board_2_state(board) if next_state in distance: continue next_states_list.append((next_x, next_y, next_state)) return next_states_list def state_2_board(self, state): # ( # (1,2,3), ==> list # (4,0,5) # ) # print(state) return [list(t) for t in state] def board_2_state(self, board): # print(board) return tuple([tuple(l) for l in board]) def is_valid(self, state, x, y): # SINCE we use tuple instead of str, we can get n & m from state if x < 0 or y < 0 or x >= len(state) or y >= len(state[0]): return False return True # @lc code=end
# # @lc app=leetcode id=34 lang=python3 # # [34] Find First and Last Position of Element in Sorted Array # # https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/ # # algorithms # Medium (35.27%) # Likes: 2850 # Dislikes: 127 # Total Accepted: 448.4K # Total Submissions: 1.3M # Testcase Example: '[5,7,7,8,8,10]\n8' # # Given an array of integers nums sorted in ascending order, find the starting # and ending position of a given target value. # # Your algorithm's runtime complexity must be in the order of O(log n). # # If the target is not found in the array, return [-1, -1]. # # Example 1: # # # Input: nums = [5,7,7,8,8,10], target = 8 # Output: [3,4] # # Example 2: # # # Input: nums = [5,7,7,8,8,10], target = 6 # Output: [-1,-1] # # # @lc code=start """ [5,7,7,8,8,10], 8 l r API1 3 API2 5 return (3, 5-1) if Not found e.g., to find 6 [5,7,7,8,8,10], 6 API1's return 5 == API2's return 5 return (-1, -1) """ class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: # return self.helper_O_N(nums, target) # return self.helper_O_lgN(nums, target) if not nums: return [-1, -1] start, end = 0, len(nums)-1 while start+1 < end: mid = start + (end-start)//2 if nums[mid] >= target: end = mid else: start = mid if nums[start] == target: first = start elif nums[end] == target: first = end else: return [-1, -1] start, end = 0, len(nums)-1 while start+1 < end: mid = start + (end-start)//2 if nums[mid] > target: end = mid else: start = mid if nums[end] == target: last = end elif nums[start] == target: last = start # print(start, end) return [first, last] def helper_O_N(self, nums, target): if not nums: return [-1, -1] # find left most l = self.b_left(nums, target) has_l = False if l < len(nums) and nums[l] == target: has_l = True if not has_l: return [-1, -1] r_bound = l while r_bound < len(nums) and nums[r_bound] == target: r_bound += 1 return [l, r_bound-1] def b_left(self, nums, target): l, r = 0, len(nums) while l < r: mid = (l+r)//2 if nums[mid] >= target: # or nums[mid] > target: r = mid else: l = mid+1 return l def helper_O_lgN(self, nums, target): if not nums: return [-1, -1] l = self.b_left(nums, target) has_l = False if l < len(nums) and nums[l] == target: has_l = True if not has_l: return [-1, -1] r = self.b_right(nums, target) # if l == r: # return [-1, -1] return [l, r-1] def b_right(self, nums, target): l, r = 0, len(nums) while l < r: mid = (l+r)//2 if nums[mid] > target: r = mid else: l = mid + 1 return l # i, j = 0, len(nums) # while i < j: # mid = (i+j)//2 # if nums[mid] > target: # i = mid # else: # j = mid + 1 # if l == i: # return [-1, -1] # return [l, i-1] # @lc code=end
# # @lc app=leetcode id=530 lang=python3 # # [530] Minimum Absolute Difference in BST # # https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/ # # algorithms # Easy (52.58%) # Likes: 758 # Dislikes: 62 # Total Accepted: 83.3K # Total Submissions: 157.5K # Testcase Example: '[1,null,3,2]' # # Given a binary search tree with non-negative values, find the minimum # absolute difference between values of any two nodes. # # Example: # # # Input: # # โ  1 # โ  \ # โ  3 # โ  / # โ  2 # # Output: # 1 # # Explanation: # The minimum absolute difference is 1, which is the difference between 2 and 1 # (or between 2 and 3). # # # # # Note: # # # There are at least two nodes in this BST. # This question is the same as 783: # https://leetcode.com/problems/minimum-distance-between-bst-nodes/ # # # # @lc code=start # Definition for a binary tree node. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def getMinimumDifference(self, root: TreeNode) -> int: # return self.dfs_main(root) return self.iterative(root) def iterative(self, root): S = [] prev = float('-inf') ans = float('inf') cur = root while True: while cur: S.append(cur) cur = cur.left if not S: break cur = S.pop() ans = min(ans, cur.val - prev) prev = cur.val cur = cur.right return ans def dfs_main(self, root): self.prev = float("-inf") self.ans = float("inf") self.dfs(root) return self.ans def dfs(self, root): if not root: return self.dfs(root.left) self.ans = min(root.val-self.prev, self.ans) self.prev = root.val self.dfs(root.right) # @lc code=end
# # @lc app=leetcode id=349 lang=python3 # # [349] Intersection of Two Arrays # # https://leetcode.com/problems/intersection-of-two-arrays/description/ # # algorithms # Easy (60.04%) # Likes: 701 # Dislikes: 1118 # Total Accepted: 329.6K # Total Submissions: 544.2K # Testcase Example: '[1,2,2,1]\n[2,2]' # # Given two arrays, write a function to compute their intersection. # # Example 1: # # # Input: nums1 = [1,2,2,1], nums2 = [2,2] # Output: [2] # # # # Example 2: # # # Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] # Output: [9,4] # # # Note: # # # Each element in the result must be unique. # The result can be in any order. # # # # # # @lc code=start from collections import Counter class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: s1 = Counter(nums1) s2 = Counter(nums2) ans = [] for k in s1.keys(): if k in s2: ans.append(k) return ans # @lc code=end
# # @lc app=leetcode id=212 lang=python3 # # [212] Word Search II # # https://leetcode.com/problems/word-search-ii/description/ # # algorithms # Hard (32.40%) # Likes: 2303 # Dislikes: 105 # Total Accepted: 196.4K # Total Submissions: 584.8K # Testcase Example: '[["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]]\n' + '["oath","pea","eat","rain"]' # # Given a 2D board and a list of words from the dictionary, find all words in # the board. # # Each word must 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 in a word. # # # # Example: # # # Input: # board = [ # โ  ['o','a','a','n'], # โ  ['e','t','a','e'], # โ  ['i','h','k','r'], # โ  ['i','f','l','v'] # ] # words = ["oath","pea","eat","rain"] # # Output:ย ["eat","oath"] # # # # # Note: # # # All inputs are consist of lowercase letters a-z. # The values ofย words are distinct. # # # # @lc code=start from copy import deepcopy # from collections import deque DIRECTIONS = [[0,1], [0,-1], [1,0], [-1,0]] class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: if not board or not board[0]: return [] # return self.bfs_old(board, word) # return self.word_by_word_TLE(board, words) return self.pre_fix_hash(board, words) # Inverse thought of word_by_word def pre_fix_hash(self, board, words): words_set = set(words) pre_fix_set = set() for word in words: for i in range(len(word)): pre_fix_set.add(word[:i+1]) n, m = len(board), len(board[0]) res = [] # visited = set() # visited = [[False for _ in range(m)] for _ in range(n)] for i in range(n): for j in range(m): # traverse board self.search(board, words_set, pre_fix_set, i, j, board[i][j], res, set([(i, j)])) return set(res) # ref: https://www.jiuzhang.com/solution/word-search-ii/#tag-other-lang-python def search(self, board, words_set, pre_fix_set, x, y, item, res, visited): if item not in pre_fix_set: return if item in words_set: res.append(item) # print(res) for delta_x, delta_y in DIRECTIONS: next_x = x + delta_x next_y = y + delta_y if self.is_valid2(next_x, next_y, board, pre_fix_set, item, visited): orig_state = item item += board[next_x][next_y] visited.add((next_x, next_y)) self.search(board, words_set, pre_fix_set, next_x, next_y, item, res, visited) item = orig_state visited.remove((next_x, next_y)) def is_valid2(self, x, y, board, pre_fix_set, item, visited): if x < 0 or y < 0 or x >= len(board) or y >= len(board[0]): return False if (x, y) in visited: return False if item + board[x][y] not in pre_fix_set: return False return True def word_by_word_TLE(self, board, words): res = [] for word in words: if self.dfs_main(board, word): res.append(word) return res # return self.dfs_main(board, word) # KEY: no go back & DFS def dfs_main(self, board, word): ans = False m, n = len(board), len(board[0]) visited = [[False for _ in range(n)] for _ in range(m)] for i in range(m): for j in range(n): if board[i][j] == word[0]: visited[i][j] = True if self.dfs(i, j, board, word, visited, 0): return True visited[i][j] = False return False def dfs(self, i, j, board, word, visited, idx): if word[idx] != board[i][j]: # print(word[:idx+1]) return False if idx == len(word)-1: return True for direction in DIRECTIONS: next_i, next_j = i+direction[0], j+direction[1] if self.is_valid(next_i, next_j, board, visited): # if next_i < 0 or next_i >= len(board) or next_j < 0 or next_j >= len(board[0]): # continue # if not visited[next_i][next_j]: visited[next_i][next_j] = True if self.dfs(next_i, next_j, board, word, visited, idx+1): return True visited[next_i][next_j] = False return False def is_valid(self, i, j, board, visited): if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]): return False if visited[i][j] == True: return False return True def findWords_old(self, board: List[List[str]], words: List[str]) -> List[str]: if not board or not words: return [] res = [] for word in words: if self.exist(board, word): res.append(word) return res ''' TLE when multiple words to search ''' def exist_old(self, board: List[List[str]], word: str) -> bool: if not board or not board[0]: return [] ans = False # visited = [[False for j in range(len(board[0]))]for i in range(len(board))] for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == word[0]: visited = [[False for j in range(len(board[0]))]for i in range(len(board))] ans = self.helper(board, i, j, word, False, visited) or ans if ans: return ans return ans ''' First version failed AT: [["C","A","A"], ["A","A","A"], ["B","C","D"]] "AAB" ''' def helper(self, board, row, col, item, ans, visited): # if not item: # return True if visited[row][col] == True: return False if board[row][col] == item[0]: visited[row][col] = True if len(item) == 1: return True else: item = item[1:] else: return False if row < len(board)-1: # print(row, col) if not visited[row+1][col]: tmp = visited[row+1][col] # ans = self.helper(board, row+1, col, item, ans, deepcopy(visited)) or ans ans = self.helper(board, row+1, col, item, ans, visited) or ans visited[row+1][col] = tmp if ans: return True if row > 0: if not visited[row-1][col]: tmp = visited[row-1][col] # ans = self.helper(board, row-1, col, item, ans, deepcopy(visited)) or ans ans = self.helper(board, row-1, col, item, ans, visited) or ans visited[row-1][col] = tmp if ans: return True if col < len(board[0])-1: if not visited[row][col+1]: tmp = visited[row][col+1] # ans = self.helper(board, row, col+1, item, ans, deepcopy(visited)) or ans ans = self.helper(board, row, col+1, item, ans, visited) or ans visited[row][col+1] = tmp if ans: return True if col > 0: if not visited[row][col-1]: tmp = visited[row][col-1] # ans = self.helper(board, row, col-1, item, ans, deepcopy(visited)) or ans ans = self.helper(board, row, col-1, item, ans, visited) or ans visited[row][col-1] = tmp if ans: return True return False # @lc code=end
# 291. Second Diameter # ไธญๆ–‡English # Given a tree consisting of n nodes, n-1 edges. Output the second diameter of a tree, namely, the second largest value of distance between pairs of nodes. # Given an array edge of size (n-1) \times 3(nโˆ’1)ร—3, and edge[i][0], edge[i][1] and edge[i][2] indicate that the i-th undirected edge is from edge[i][0] to edge[i][1] and the length is edge[i][2]. # Example # Input:[[0,1,4],[0,2,7]] # Output:7 # Explanation: The second largest value of distance is 7 between node 0 and node 2. # Clarification # If there are more than one max distance, you just need to return the max distance # Notice # 2 \leq n \leq 10^52โ‰คnโ‰ค10 # โ€‹5 # โ€‹โ€‹ # 1 \leq edge[i][2] \leq 10^51โ‰คedge[i][2]โ‰ค10 # โ€‹5 # โ€‹โ€‹ # Using DFS(Depth-First-Search) is easy to cause stack overflow, so please use BFS(Breadth First Search) to finish the task. class Solution: """ @param edge: edge[i][0] [1] [2] start point,end point,value @return: return the second diameter length of the tree """ def getSecondDiameter(self, edge): # write your code here neighbors = {} m = len(edge) # m = n-1 for i in range(m): if edge[i][0] not in neighbors: neighbors[edge[i][0]] = [] if edge[i][1] not in neighbors: neighbors[edge[i][1]] = [] for i in range(m): start, end, dist = edge[i] neighbors[start].append((end, dist)) neighbors[end].append((start, dist)) # start, _ = self.bfs(0, neighbors) start, _ = self.bfs(edge[0][0], neighbors, None) end, max_dist = self.bfs(start, neighbors, None) _, dist_no_start = self.bfs(end, neighbors, start) _, dist_no_end = self.bfs(start, neighbors, end) return max(dist_no_start,dist_no_end) def bfs(self, root, neighbors, ban_node): Q = collections.deque() Q.append(root) distance_to_root = {} distance_to_root[root] = 0 max_node, max_dist = None, 0 while Q: now = Q.popleft() if distance_to_root[now] > max_dist: max_node = now max_dist = distance_to_root[now] for nbr, edge_len in neighbors[now]: if nbr == ban_node: continue if nbr in distance_to_root: continue Q.append(nbr) distance_to_root[nbr] = distance_to_root[now] + edge_len return max_node, max_dist
# # @lc app=leetcode id=256 lang=python3 # # [256] Paint House # # https://leetcode.com/problems/paint-house/description/ # # algorithms # Easy (51.35%) # Likes: 744 # Dislikes: 78 # Total Accepted: 81.9K # Total Submissions: 158.9K # Testcase Example: '[[17,2,17],[16,16,5],[14,3,19]]' # # There are a row of n houses, each house can be painted with one of the three # colors: red, blue or green. The cost of painting each house with a certain # color is different. You have to paint all the houses such that no two # adjacent houses have the same color. # # The cost of painting each house with a certain color is represented by a n x # 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with # color red; costs[1][2] is the cost of painting house 1 with color green, and # so on... Find the minimum cost to paint all houses. # # Note: # All costs are positive integers. # # Example: # # # Input: [[17,2,17],[16,16,5],[14,3,19]] # Output: 10 # Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 # into blue. # Minimum cost: 2 + 5 + 3 = 10. # # # # @lc code=start class Solution: def minCost(self, costs: List[List[int]]) -> int: if not costs: return 0 f = costs[0] for i in range(1, len(costs)): red = min(f[1], f[2]) + costs[i][0] green = min(f[0], f[2]) + costs[i][1] blue = min(f[0], f[1]) + costs[i][2] f = [red, green, blue] return min(f) def minCost_old(self, costs: List[List[int]]) -> int: n = len(costs) if n == 0: return 0 elif n == 1: return min(costs[0][0], costs[0][1], costs[0][2]) elif n == 2: return min(costs[0][0] + min(costs[1][1], costs[1][2]), costs[0][1] + min(costs[1][2], costs[1][0]), costs[0][2] + min(costs[1][0], costs[1][1]), ) # elif n == 3: # return min(costs[0][0]) # up to ith house, the min costs to paint the house... T # dp = [0 for j in len(costs)] TODO: NO USE for n in reversed(range(len(costs) - 1)): # Total cost of painting nth house red. costs[n][0] += min(costs[n + 1][1], costs[n + 1][2]) # Total cost of painting nth house green. costs[n][1] += min(costs[n + 1][0], costs[n + 1][2]) # Total cost of painting nth house blue. costs[n][2] += min(costs[n + 1][0], costs[n + 1][1]) if len(costs) == 0: return 0 return min(costs[0]) # Return the minimum in the first row. # @lc code=end
# # @lc app=leetcode id=78 lang=python3 # # [78] Subsets # # https://leetcode.com/problems/subsets/description/ # # algorithms # Medium (58.50%) # Likes: 3130 # Dislikes: 73 # Total Accepted: 511.6K # Total Submissions: 869.2K # Testcase Example: '[1,2,3]' # # Given a set of distinct integers, nums, return all possible subsets (the # power set). # # Note: The solution set must not contain duplicate subsets. # # Example: # # # Input: nums = [1,2,3] # Output: # [ # โ  [3], # [1], # [2], # [1,2,3], # [1,3], # [2,3], # [1,2], # [] # ] # # # @lc code=start class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: if not nums: return [] self.res = [] self.helper_bt(nums, 0, []) # self.helper_BF_bt(nums, 0, []) return self.res return self.helper_BF(nums) # def helper_BF_bt_FAILED(self, nums, idx, item): # if idx == len(nums): # self.res.append(item.copy()) # return # for i in range(idx, len(nums)): # # self.helper_BF_bt(idx+1, item + [nums[i]]) # NOT to write in this way # item.append(nums[i]) # self.helper_BF_bt(nums, i+1, item) # item.pop() def helper_BF(self, nums): res = [[]] for num in nums: new_subset = [] for j in range(len(res)): cur = res[j].copy() # [] or [1] ... cur.append(num) # [2] or [1,2] new_subset.append(cur) # print(new_add) res.extend(new_subset) return res def helper_bt(self, nums, idx, item): if idx == len(nums): self.res.append(item.copy()) return self.helper_bt(nums, idx+1, item+[nums[idx]]) self.helper_bt(nums, idx+1, item) # class Solution: # def subsets(self, nums: List[int]) -> List[List[int]]: # if not nums: # return nums # self.result = [[]] # item = [] # self.helper(0, nums, item) # return self.result # def helper(self, level, nums, item): # if level == len(nums): # # self.result.append(item.copy()) # return # item.append(nums[level]) # [1,2,3] # prevent the OOR here # self.result.append(item.copy()) # self.helper(level+1, nums, item.copy()) # item.pop() # no 2 # self.helper(level+1, nums, item.copy()) # level 3 eturn # @lc code=end
# # @lc app=leetcode id=422 lang=python3 # # [422] Valid Word Square # # https://leetcode.com/problems/valid-word-square/description/ # # algorithms # Easy (37.17%) # Likes: 166 # Dislikes: 113 # Total Accepted: 28.8K # Total Submissions: 76.7K # Testcase Example: '["abcd","bnrt","crmy","dtye"]' # # Given a sequence of words, check whether it forms a valid word square. # # A sequence of words forms a valid word square if the k^th row and column read # the exact same string, where 0 โ‰ค k < max(numRows, numColumns). # # Note: # # The number of words given is at least 1 and does not exceed 500. # Word length will be at least 1 and does not exceed 500. # Each word contains only lowercase English alphabet a-z. # # # # Example 1: # # Input: # [ # โ  "abcd", # โ  "bnrt", # โ  "crmy", # โ  "dtye" # ] # # Output: # true # # Explanation: # The first row and first column both read "abcd". # The second row and second column both read "bnrt". # The third row and third column both read "crmy". # The fourth row and fourth column both read "dtye". # # Therefore, it is a valid word square. # # # # Example 2: # # Input: # [ # โ  "abcd", # โ  "bnrt", # โ  "crm", # โ  "dt" # ] # # Output: # true # # Explanation: # The first row and first column both read "abcd". # The second row and second column both read "bnrt". # The third row and third column both read "crm". # The fourth row and fourth column both read "dt". # # Therefore, it is a valid word square. # # # # Example 3: # # Input: # [ # โ  "ball", # โ  "area", # โ  "read", # โ  "lady" # ] # # Output: # false # # Explanation: # The third row reads "read" while the third column reads "lead". # # Therefore, it is NOT a valid word square. # # # # @lc code=start """ [ "ball", "asee", "let.", "lep." ] """ class Solution: def validWordSquare(self, words: List[str]) -> bool: if not words or not words[0]: return False n = len(words) # n = len(words) m = max(len(word) for word in words) if n != m: return False grid = [] for i in range(n): item = words[i] if len(words[i]) < m: item += (m-len(words[i])) * '.' grid.append(item) for i in range(n): for j in range(i+1, m): # for j in range(m): if grid[i][j] != grid[j][i]: return False return True # @lc code=end
from copy import deepcopy START_STATE = ([4]*6 + [0])*2 class PocketName: num_pockets = 14 p0_mancala = 6 p1_mancala = 13 p0_pockets = list(range(6)) p1_pockets = list(range(12,6,-1)) class GameState: def __init__(self, init_state=START_STATE, player_turn=0, stealing=True): self.state = init_state self.player_turn = player_turn self.stealing = stealing self.winner = None def show(self): print() print("Player {}'s turn:".format(self.player_turn)) print(" 5 4 3 2 1 0") print("[{:2}]({:2})({:2})({:2})({:2})({:2})({:2})[ ]".format(*self.state[-1:6:-1])) print("[ ]({:2})({:2})({:2})({:2})({:2})({:2})[{:2}]".format(*self.state[:7])) print(" 0 1 2 3 4 5") def show_winning_message(self): print(f"Player {self.winner} Won!") def is_terminal(self): if self.winner is not None: return True return False def children(self): for move in self.possible_moves(): new_state = self.make_move(move) yield move, new_state def possible_moves(self): if self.player_turn == 0: for i in PocketName.p0_pockets: if self.state[i] != 0: yield i else: for i in PocketName.p1_pockets: if self.state[i] != 0: yield i def make_move(self, move): # assumes that the move is valid player0_turn = self.player_turn == 0 new_state = deepcopy(self.state) hand = new_state[move] new_state[move] = 0 while hand > 0: move = (move + 1) % PocketName.num_pockets if (player0_turn and move == PocketName.p1_mancala) or (not player0_turn and move == PocketName.p0_mancala): # skip opponent's mancala continue hand -= 1 new_state[move] += 1 if self.stealing: if (player0_turn and move in PocketName.p0_pockets) or (not player0_turn and move in PocketName.p1_pockets): if new_state[move] == 1: # steal marbles from opposite pocket if your pocket was empty opposite_move = 12 - move hand = new_state[move] + new_state[opposite_move] new_state[move], new_state[opposite_move] = 0, 0 if player0_turn: new_state[PocketName.p0_mancala] += hand else: new_state[PocketName.p1_mancala] += hand if (player0_turn and move == PocketName.p0_mancala) or (not player0_turn and move == PocketName.p1_mancala): # play again if last peice is put in your own mancala next_player = self.player_turn else: next_player = 1 - self.player_turn # check for winner game_done = sum(new_state[:6]) == 0 or sum(new_state[7:13]) == 0 winner = None if game_done: if sum(new_state[:6]) == 0: new_state[PocketName.p1_mancala] += sum(new_state[7:13]) for i in PocketName.p1_pockets: new_state[i] = 0 elif sum(new_state[7:13]) == 0: new_state[PocketName.p0_mancala] += sum(new_state[:6]) for i in PocketName.p0_pockets: new_state[i] = 0 winner = 0 if new_state[PocketName.p0_mancala] > new_state[PocketName.p1_mancala] else 1 new_game_state = GameState(new_state, next_player, self.stealing) new_game_state.winner = winner return new_game_state if __name__ == "__main__": game_state = GameState() print(game_state.state) game_state.show()