text
stringlengths
37
1.41M
from PIL import Image fg = Image.open('logo-1.png') # IMAGE NAME TO BE ANALIZED, PLEASE STORE IT IN THE SAME FOLDER THAN THE SCRIPT dimensions = fg.size # TUPLE WITH (width, height) OF THE IMAGE newIm = Image.new("RGB", dimensions,"white") # NEW IMAGE ALL WHITE WITH RGB PROPERTIES AND DIMENSIONS OF THE ANALYZED IMAGE fg_rgb = fg.convert('RGB') # CREATES AN IMAGE IN RGB FROM THE ORIGINAL IMAGE i = 0 # CREATES COUNTER # CREATES A LOOP TO GO THROUGH ALL THE PIXELS OF THE IMAGE for row in range(dimensions[1]): for col in range(dimensions[0]): fgpix = fg.getpixel((col,row)) # CREATES A TUPLE (1,3) WITH A BYTE PER POSITION CORRESPONDING TO THE PIXEL fg1 = fgpix[0] # BYTE CORRESPONDING TO R fg2 = fgpix[1] # BYTE CORRESPONDING TO G fg3 = fgpix[2] # BYTE CORRESPONDING TO B fgr = fg1 + fg2 + fg3 # SUMS THE INFORMATION OF THE THREE POSITIONS FOR ANALYSIS if fg2 <= 1 and fg1 <= 1 and fg3 <=1: # if there is some sign of least bit newIm.putpixel((col,row),(255,255,255)) # puts a white pixel else: newIm.putpixel((col,row),(0,0,0)) # INCREASES THE COUNTER FOR INDICATIONS OF LSB USED FOR STORING INFORMATION if (fgr == 764 or fgr == 1): i += 1 else: continue if i != 0: print("Possible least significant bit." + str(i)+ " instances found.") newIm.show() win = image.ImageWin(dimensions[1],dimensions[0]) newIm.draw(win) win.exitonclick()
# CSCI 1913, Spring 2020, Lab 3 # Student Names: # Omar Masri! # Brandon Weinstein! # [email protected] # [email protected] #gets rid of punctuation def clean_word(text): contin = True while contin: for i in range(len(text)): if text[i] in ["!", ",", "?", "."]: text = text[:i] + text[i+1:] contin = True break else: contin = False return text #splits text into word list, also calls clean_word function to get rid of punctuation def my_split(text): cleaned_text = clean_word(text) text_list = [] last_index = 0 for i in range(len(cleaned_text)): if cleaned_text[i] == " ": text_list.append(cleaned_text[last_index:i]) last_index = (i+1) elif i == len(cleaned_text) - 1: text_list.append(cleaned_text[last_index:(i+1)]) return text_list # counts number of words and creates dictionary containing word and count. (not using .count()) def count(words): word_dict = {} for i in words: if i in word_dict: word_dict[i] += 1 else: word_dict[i] = 1 return(word_dict) # run similarity forumla on words, return similarity value from 0-1 def word_count_similarity(count1, count2): s1 = 0 s2 = 0 s3 = 0 for i in count1.values(): s1 += i*i for i in count2.values(): s2 += i*i for i in count1.keys(): if i in count2: s3 += count1[i]*count2[i] return (s3/(s1*s2)) # compares known "authors" to an unkown word sample, returns author with closest similarity value using word_count_similarity def best_guess(known_author_counts, unknown_count): similarity = 0 for i in known_author_counts: if word_count_similarity(known_author_counts[i], unknown_count) >= similarity: author = i similarity = word_count_similarity(known_author_counts[i], unknown_count) return author
# list of items items_list = [ { 'item_code': '84500', 'item_description': 'CHOCOLATE SHORTCAKE', 'customer_name': 'FROSTY TREATS', 'gross_weight': 15.95, 'units':10 }, { 'item_code':'84400', 'item_description':'STRAWBERRY SHORTCAKE', 'customer_name':'FROSTY TREATS', 'gross_weight': 16.3, 'units':15 }, { 'item_code':8520, 'item_description':'COOKIES & CREAM BAR', 'customer_name':'FROSTY TREATS', 'gross_weight': 14.1, 'units':25 } ] # declare variable to store total weight total_weight = 0 # loop through all items in items_list for item in items_list: # multiply an units x gross weight to get the item weight # note: each item is a dictionary --> access values by indexing with a key item_weight = item['gross_weight'] * item['units'] # print the current item description and weight to the console # note: use "%s" as a placeholder for the item description (a string) and "%d" as a placeholder for the item weight (a float) print("Item: %s, Item weight on hand: %d" % (item["item_description"], item_weight)) # increment total weight with current item's weight total_weight = total_weight + item_weight # finally, print the total weight of all items print("Total weight of all items: %d" % total_weight)
# define list of valid facility IDs facility_ids = ["78401", "MO-SKSTN"] # get user input of facility ID facility_input = input("Enter a facility ID: ") # set up criteria for while loop num_entries = 0 max_entries = 4 if facility_input in facility_ids: # if facility is valid --> print welcome to facility message print("Welcome to facility: %s" % facility_input) else: # if facility is invalid --> prompt user for a facility until either: # 1) user enters a valid facility # 2) user exceeds max number of entries while (facility_input not in facility_ids) and (num_entries < max_entries): facility_input = input("Facility ID invalid. Please try again: ") num_entries = num_entries + 1 if num_entries == max_entries: print("Too many entries - try again some other time")
user_input_name = input("Enter a name: ") user_input_place = input("Enter a place: ") if user_input_name == "": message = "No name entered - cannot print welcome :(" else: # welcome message with multiple values passed to string interpolation message = "Hello, %s! Welcome to %s!" % (user_input_name, user_input_place) print(message)
import pandas as pd import numpy as np # read in sample data files from csv df_items = pd.read_csv("items_sample.csv") df_inventory_activity = pd.read_csv("inventory_activity_sample.csv") # create a user defined function which rounds the pallet picks of each activity record def get_num_pallets(activity): # set the pallet size and units equal to the pallet_size and units from the activity pallet_size = activity["pallet_size"] units = activity["units"] # get the number of pallets by dividing units by pallet size num_pallets = units / pallet_size # if num_pallets is less than zero --> round up; if num_pallets is greater than zero --> round down if num_pallets < 0: rounded_num_pallets = np.ceil(num_pallets) else: rounded_num_pallets = np.floor(num_pallets) return int(rounded_num_pallets) # filter items which only have a tie and high greater than 0 df_items = df_items[(df_items["tie"] > 0) & (df_items["high"] > 0)] # merge sample data into a single dataframe # - use an inner join on matching rows # - join on matching item_code, facility_id, customer_id df_item_activity = pd.merge( left = df_items, right = df_inventory_activity, how = "inner", left_on = ["item_code","facility_id","customer_id"], right_on = ["item_code","facility_id","customer_id"] ) # create a new column called pallet_size which is the product of tie x high df_item_activity["pallet_size"] = df_item_activity["tie"] * df_item_activity["high"] # use the apply function to evaluate how many full pallets were selected for each activity # specifying axis = 1 the entire dataframe, one activity at a time df_item_activity["full_pallet_picks"] = df_item_activity.apply(get_num_pallets, axis = 1) print(df_item_activity[["item_code","item_description","facility_id","customer_id","filter_date", "tie", "high", "activity_type","units","pallet_size","full_pallet_picks"]])
import pandas as pd # read in the sample items csv as dataframe items_df = pd.read_csv("items_sample.csv") # user defined function to determine an item's category def get_volume_category(item): # multiply width x height x depth to calculate volume volume = item["unit_width"]*item["unit_depth"]*item["unit_height"] if volume == 0: return "Missing data!" if volume < 2000: return "Small" if volume < 30000: return "Medium" else: return "Large" # apply custom function to dataframe # - the parameter "axis=1" indicates that an entire row will be the input to the function "apply_volume_category" # - we apply "apply_volume_category" one row at a time, with the output of each function call creating the new column "volume_category" items_df["volume_category"] = items_df.apply(get_volume_category, axis=1) # define a list of columns to subset # print dataframe including only these columns subset_cols = ["item_code","item_description","unit_width","unit_depth", "unit_height","volume_category"] print(items_df[subset_cols])
# create item dictionaries item_1 = { "item_code": "84500", "item_description": "CHOCOLATE SHORTCAKE", "customer_name": "FROSTY TREATS", "gross_weight": 15.95 } item_2 = { "item_code": "84400", "item_description": "STRAWBERRY SHORTCAKE", "customer_name": "FROSTY TREATS", "gross_weight": 16.3 } # create list of items and print to console item_list = [item_1, item_2] print("item_list:", item_list) # get the weight of both items, add together, then print total_item_weight = item_list[0]["gross_weight"] + item_list[1]["gross_weight"] print("total_item_weight:", total_item_weight)
def printboard(dict1): print("|",dict1[7],"|",dict1[8],"|",dict1[9],"|") print("------------") print("|",dict1[4],"|",dict1[5],"|",dict1[6],"|") print("------------") print("|",dict1[1],"|",dict1[2],"|",dict1[3],"|") print("THE TIC TAC TOE") print("Hi, Welcome to the game , the game rules are simple and most of you know it") print("Each player gets a chance one by one to play ") print("lets see who wins?😀") def check(d): if d[1]==d[2]==d[3]: return True elif d[4]==d[5]==d[6]: return True elif d[1]==d[2]==d[3]: return True elif d[7]==d[4]==d[1]: return True elif d[8]==d[5]==d[2]: return True elif d[9]==d[6]==d[3]: return True elif d[7]==d[5]==d[3]: return True elif d[9]==d[5]==d[1]: return True else: return False def startgame(): dict1={1:" ",2:" ",3:" ",4:" ",5:" ",6:" ",7:" ",8:" ",9:" "} printboard(dict1) f,f1,k=0,0,0 while(k!=10): if(k%2==0): print("X it's you're turn") print("In which place do you want to place X") l=int(input()) if l in dict1 and dict1[l]==" ": dict1[l]='X' k+=1 else: print("Select the correct index") printboard(dict1) if k>=5: flag=check(dict1) if flag==True: f1=1 break else: print("O it's you're turn") print("In which place do you want to place O") l=int(input()) if l in dict1 and dict1[l]==" ": dict1[l]="O" k+=1 else: print("Select the correct index") printboard(dict1) if k>=5: flag=check(dict1) if flag==True: f=1 break if f==1: print("O won the match") elif f1==1: print("X won the match") else: print("its a tie ") print("This is the intial board the numbers of the indexs are like this ...") print("7 8 9") print("4 5 6") print("1 2 3") print("Ready?") st=input() while(st=="yes"): startgame() print("do you want to continue??") st=input() print("Thank You For playing")
""" msg = input("What's The Secret Password? ") while msg != "bananas": print("WRONG!") msg = input("What's The Secret Password? ") print("Correct!") """ smiley = "\U0001f600" times = 10 for num in range(1,11): print(smiley * num) while times > 0: print(smiley * times) times-=1
# Add # Adds an element to a set # If element already in set, set doesn't change s = set([1,2,3]) print(f"\nOriginal Set: {s}") s.add(4) print(f"'4' Added To Set: {s}") # Remove # Removes value from set # KeyError if value not found # Use 'discard()' to remove without KeyError s.remove(4) print(f"'4' Removed From Set: {s}") # Copy s2 = s.copy() print(f"Copy Of Set: {s2}") # Clear s2.clear() print(f"Cleared Set: {s2}") # Set Math # Including 'intersection', 'symmetric_difference', 'union', etc # Union: Combination of sets without duplicates # Intersection which set elements are shared between sets math_students = {"Matthew", "Helen", "Prashant", "James", "Aparna"} biology_students = {"Jane", "Matthew", "Charlotte", "Mesut", "Oliver", "James"} print("\n...Students...") print(f"Math: {math_students}") print(f"Biology: {biology_students}") # Union of Sets print("\nAll Students (Union)") print(math_students|biology_students) # Intersections print("\nStudents In Both Classes (Intersection)") print(math_students&biology_students)
# def square(num): return num * num # print(square(9)) square2 = lambda num: num * num print(square2(7)) # # add = lambda a,b: a + b # print(add(3,10)) # # Lambda's haven't any name: # print(square.__name__) # print(square2.__name__) # Most commonly used # when you need to pass a function into a function as a parameter # and that function will never be used again # Syntax # lambda paramaters: body of function
# Argument Unpacking Using ** As An Argument # We can use ** as an argument to a function to "unpack" values # # See 038_UnpackingTuples.py for further reference def display_names(first, second): print(f"{first} says hello to {second}") names = {"first": "Colt", "second":"Rusty"} display_names(**names) # Without **, we get a TypeError: # "display_names() missing 1 required positional argument: 'second' # As the entire names dictionary is passed in as the argument 'first'
import random rand_num = random.randint(1,10) while True: guess = int(input("\nPick A Number From 1 To 10: ")) if guess < rand_num: print("Too Low!") elif guess > rand_num: print("Too High!") else: print("YOU GOT IT!") play_again = input("\nDo You Want To Play Again? (y/n) ") if play_again == "y": rand_num = random.randint(1,10) guess = None else: print("\nThank You For Playing!") break
import os import cv2 from PIL import Image ''' This class is used to seperate single symbol with equation according to its file name length ''' # This class is used to seperate single and equation from the annotated data class TestEqual: def getEqual(self): dataroot = os.getcwd() + "/data/annotated_train/" saveroot = os.getcwd() + "/data/train/" for f in os.listdir(dataroot): if f.endswith(".png"): ins = f.split('.')[0].split('_') if len(ins) > 3: # exclude the equation png only individual symbol im = Image.open(dataroot + f) im.save(saveroot + f) def main(): x = TestEqual() x.getEqual() if __name__ == "__main__": main()
from string import punctuation, whitespace class DateSniffer: SNIPPET_BEFORE = 40 SNIPPET_AFTER = 40 MONTH = [ 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december' ] MONTH_ABBR = [ 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sept', 'oct', 'nov', 'dec' ] MONTH_DAYS = [ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] BORDERS = punctuation + whitespace def __init__(self, year, month=None, keyword=None, distance=10): if not isinstance(year, int) or year > 3000 or year < 1000: raise ValueError("Invalid year format") if month is not None: if not isinstance(month, int) or month > 12 or month < 1: raise ValueError("Invalid month") self.distance = distance self.year = str(year) self.month = month self.keyword = keyword month_options = [] if month: month_options.append('{:04}-{:02}-'.format(year, month)) month_options.append('{:04}/{:02}/'.format(year, month)) for i in range(1, 32): month_options.append('{:02}/{:02}/{:04}'.format(month, i, year)) self.month_options = month_options def find_isolated(self, keyword, text): start = 0 locations = [] while True: found = text.find(keyword, start) if found == -1: break start = found + 1 if found > 0 and text[found - 1] not in self.BORDERS: continue if found + len(keyword) < len(text) and text[found + len(keyword)] not in self.BORDERS: continue locations.append(found) return locations def find_month(self, snippet): start = len(snippet) // 2 - (self.distance + 10) # compensate month length stop = len(snippet) // 2 + self.distance if start < 0: start = 0 if stop >= len(snippet): stop = len(snippet) - 1 text = snippet[start:stop + 1].lower() if self.find_isolated(keyword=self.MONTH[self.month - 1], text=text): return True if self.find_isolated(keyword=self.MONTH_ABBR[self.month - 1], text=text): return True for m in self.month_options: if m in text: return True return False def find_days(self, snippet): """ Try to find isolated 1-{max days in the month} numbers. If there month == number: check patterns mon/day/year, year-month-day, year/month/day """ snippet = snippet.replace(self.year, ' ') days = [] for i in range(1, self.MONTH_DAYS[self.month] + 1): keys = [str(i)] if i < 10: keys.append('{:02}'.format(i)) for key in keys: if key in snippet and self.find_isolated(keyword=key, text=snippet): days.append(i) if not days: return [] result = set() for d in days: if d == self.month: if '{:02}/{:02}/{}'.format(self.month, d, self.year) in snippet: result.add(d) elif '{}-{:02}-{:02}'.format(self.year, self.month, d) in snippet: result.add(d) elif '{}/{:02}/{:02}'.format(self.year, self.month, d) in snippet: result.add(d) elif '{}/{}/{}'.format(self.month, d, self.year) in snippet: result.add(d) elif '{}/{}/{}'.format(self.year, self.month, d) in snippet: result.add(d) else: result.add(d) return list(result) def find_keyword(self, snippet): start = len(snippet) // 2 - self.distance stop = len(snippet) // 2 + self.distance if start < 0: start = 0 if stop >= len(snippet): stop = len(snippet) - 1 return self.keyword.lower() in snippet.lower()[start:stop + 1] def sniff(self, text): year_positions = self.find_isolated(keyword=self.year, text=text) results = {} for pos in year_positions: snippet_start = pos - self.SNIPPET_BEFORE if snippet_start < 0: snippet_start = 0 snippet_stop = pos + len(str(self.year)) + self.SNIPPET_AFTER if snippet_stop >= len(text): snippet_stop = len(text) - 1 while snippet_start > 0: if text[snippet_start] not in self.BORDERS: snippet_start -= 1 else: snippet_start += 1 break while snippet_stop < len(text): if text[snippet_stop] not in self.BORDERS: snippet_stop += 1 else: snippet_stop -= 1 break snippet = text[snippet_start: snippet_stop + 1] if self.month and not self.find_month(snippet=snippet): continue if self.keyword and not self.find_keyword(snippet=snippet): continue if self.month: days = self.find_days(snippet=snippet) else: days = [] if snippet_start > 0: snippet = '... ' + snippet if snippet_stop < len(text) - 1: snippet = snippet + ' ...' snippet = snippet.replace('\n', ' ').replace('\t', ' ') if snippet not in results: results[snippet] = list(sorted(days)) else: results[snippet] = list(sorted(set(results[snippet] + days))) return dict(results)
# befor # class NewsPerson: # """This is a high-level module""" # @staticmethod # def publish(news: str) -> None: # """ # :param news: # :return: # """ # print(NewsPaper().publish(news=news)) # class NewsPaper: # """This is a low-level module""" # @staticmethod # def publish(news: str) -> None: # """ # :param news: # :return: # """ # print(f"{news} Hello newspaper") # person = NewsPerson() # print(person.publish("News Paper")) # after class NewsPerson: """This is a high-level module""" @staticmethod def publish(news: str, publisher=None) -> None: print(publisher.publish(news=news)) class NewsPaper: """This is a low-level module""" @staticmethod def publish(news: str) -> None: print("{} news paper".format(news)) class Facebook: """This is a low-level module""" @staticmethod def publish(news: str) -> None: print(f"{news} - share this post on {news}") person = NewsPerson() person.publish("hello", NewsPaper()) person.publish("facebook", Facebook())
import re import the_minion_game_data as data TC3 = """BANANANAAAS""" # See discussion below HUNDRED = data.TC5[:100] TWOK = data.TC5[:2000] THREEK = data.TC5[:3000] FOURK = data.TC5[:4000] DODGY = data.TC5[:4250] # ABBREV5 = data.TC5[:5000] between 4k and 5k causes problems. # Setting ulimit -v 2000000 is too small for 4k, ok for 1000. def winning_name(vowel_score, consonant_score): VOWEL_PLAYER = "Kevin" CONSONANT_PLAYER = "Stuart" DRAW = "Draw" if vowel_score > consonant_score: return VOWEL_PLAYER if consonant_score > vowel_score: return CONSONANT_PLAYER assert vowel_score == consonant_score, "Incoherent outcome! v {} c {}".format(vowel_score, consonant_score) return DRAW def scores_starting_at_position(pos, length): # The trick to the problem. We don't need THE SUBSTRINGS themselves, just a count of them. # If we know the position of a given character, we can credit # all valid substrs without knowing the rest of their contents. return length - pos def anomalous_draw_handling(score): # This function is my way of highlighting that it's illogical that a draw wouldn't print the score but that's how # the problem is specified. print (score) def minion_game(s): all_vowels = 'AEIOU' # total count is just math -- 'triangular' number summing n, n-1, n-2,... 1. n = len(s) total_substrings = int(n * (n+1) / 2) # print("Tot {}".format(total_substrings)) list_of_vowel_scores = [ scores_starting_at_position(x, n) for x in range(0, n) if s[x].upper() in all_vowels] vowel_score = sum(list_of_vowel_scores) consonant_score = total_substrings - vowel_score the_tuple = (name, winning_score) = (winning_name(vowel_score=vowel_score, consonant_score=consonant_score), max(vowel_score, consonant_score)) if vowel_score == consonant_score: anomalous_draw_handling(the_tuple[0]) else: # print("{} {}".format(vowel_score, consonant_score)) print("{} {}".format(the_tuple[0], the_tuple[1])) return the_tuple if __name__ == '__main__': print ("Input?") # for s in ['banana', 'oiseau', '1234']: assert scores_starting_at_position(0, 1) == 1 assert scores_starting_at_position(0, 2) == 2 assert scores_starting_at_position(1, 2) == 1 assert scores_starting_at_position(10, 50) == 40 for (s, name, score) in [ ('aba', 'Kevin', 4), (TC3, 'Draw', 33), (HUNDRED, 'Kevin', 2550), (TWOK, 'Kevin', 1001000),# should be 2000 * 2002 / 4 = 1001000 # (THREEK, 999), # (FOURK, 999), # (DODGY, 999), ]: tup = minion_game(s) #print("{} {}".format(tup[0], tup[1])) print ("Len of string: {}".format(len(s))) assert tup[0] == name, "NAME WRONG {}".format(tup[0]) assert tup[1] == score, "SCORE WRONG {}".format(tup[1]) # I misread the problem and started with the set version, but I like that too. # # def set_of_substr(s): # return {s[i:j] for i in range(0, len(s)) for j in range (i+1, len(s)+1)} # # def minion_game(s): # substrs = set_of_substr(s) # vowel_score = len({x for x in substrs if re.match('^[aeiou]', x, re.IGNORECASE)}) # return vowel_score # return set_of_substr(s) ##### So what's going wrong? # Kevin 25005000 # There are 5000 occurrences of A, and vowel win must start with one. # The first (position 0) has 10k different possible substring lengths. # The second (2) has 9998 # The last (pos 9998) has 2. # E.g. at 4 chars, # ABAB ABA AB A : 4 choices # ..AB ...A: 2 choices. # Summing pairwise: 2 + 10000, 4 + 9998, etc. # 5000 numbers means 2500 pairs. Each pair sums to 10002 # 25005000 # Where did my formula go wrong? Because I misstated the number of possibles. # (n+2), not (n+1)
import requests import time status_url = 'http://www.proofofexistence.com/api/v1/status' register_url = 'http://www.proofofexistence.com/api/v1/register' class TimestampFile: def __init__(self, file_hash): self.file_hash = file_hash @property def request_timestamp(self): """ using ProofOfExistence to register and make timestamp for a file @return: dictionary contains information about Bitcoin payment price and payment address. Returns -1 if failed. """ returnval = {'pay_address': "", 'price': "", 'id': self.file_hash} params = {'d': self.file_hash} r = requests.post(status_url, data=params, timeout=10) if r.status_code != 200: return -1 text = r.json() if text['success'] is False: if text['reason'] == 'nonexistent': r = requests.post(register_url, data=params) text = r.json() if text['success'] is False: print("Opps, failed to register digest! \n") return -1 if text['success'] is True: r = requests.post(status_url, data=params) text = r.json() if text['status'] == 'registered': returnval['pay_address'] = text['pay_address'] returnval['price'] = text['price'] return returnval def check_timestamp(self): """ check whether the file has timestamp @return: dictionary contains information about timestamp status, timestamp time and transaction id. Returns -1 if failed. """ params = {'d': self.file_hash} r = requests.post(status_url, data=params, timeout=10) returnval = {'timestamp': False, 'time': "", 'Transaction': "" } if r.status_code != 200: print("Error: HTTP Status Code " + r.status_code + ". " + "The request was not succeeded, expected staus code '200'. \n") return -1 text = r.json() if text['success'] is False: return -1 if text['success'] is True: r = requests.post(status_url, data=params) text = r.json() if text['status'] == 'pending': print("Your payment has been received. Please wait at least 1 minute for your payment to be certified. \n") time_out_count = 0 while text['status'] == 'pending': if time_out_count > 10: print("Maximum 10 minute time limit exceeded. Transaction not confirmed. \n") return -1 time_out_count += 1 time.sleep(60) r = requests.post(status_url, data=params) text = r.json() if text['status'] == 'confirmed': returnval['timestamp']=True else: return -1 if text['status'] == 'confirmed': returnval['timestamp'] = True if returnval['timestamp'] is True: returnval['time'] = text['txstamp'] returnval["Transaction"] = text['transaction'] return returnval
import numpy as np import cv2 #image read img = cv2.imread('Screenshot_2.png', cv2.IMREAD_COLOR) #to draw circle on the imgae cv2.circle(img,(200,200),70,(0,0,255),3) # (img,centre ,radius ,color,thickness=None,lineType=None) if thickness=-1 then circle get filled otherwise empty cv2.imshow('draw',img) #show imagev and drawn things on it #wait for undefinite time for key stroke cv2.waitKey(0) cv2.destroyAllWindows()
#Introduction to Python for i in range(5): print('I am a ghost') print('Will this give me an error?')
def repeat_times(n): s = 0 n_str = str(n) while (n > 0): n -= sum([int(i) for i in list(n_str)]) n_str = list(str(n)) s += 1 return s print(repeat_times(9)) print(repeat_times(21))
import calendar y = int (input ("Introduzca el año: ")) m = int (input ("introduzca el mes: ")) print(calendar.month(y,m))
def agregaString(str): if len(str) >= 2 and str [:2] == "Is": return str return "Is" + str print(agregaString("Blue")) print(agregaString("Isgreen"))
num = int(input("Please input the number: ")) #Taking input from user if (num % 2 == 0): print(num, "is Even") else: print(num, "is Odd")
from wordcloud import WordCloud, STOPWORDS txt = "Many times you might have seen a cloud filled with lots of words in different sizes, which represent the frequency or the importance of each word. This is called Tag Cloud or WordCloud. For this tutorial, you will learn how to create a WordCloud of your own in Python and customize it as you see fit. This tool will be quite handy for exploring text data and making your report more lively." print(txt) stopwords = set(STOPWORDS) wordcloud = WordCloud(stopwords=stopwords).generate(txt) wordcloud.to_file("2.png")
import math n = int(input()) def palindrome(a): if a < n: return False else: list_num = str(a) for i in range(0, len(list_num)//2): if list_num[i] == list_num[len(list_num) - 1 - i]: continue else: return False return True def prime_num(a): if a == 1: return False b = int(math.sqrt(a)) for i in range(2, b+1): if a % i == 0: return False return True c = False while (c == False): if palindrome(n) == True: c = prime_num(n) n = n + 1 print(n-1)
''' Basic Python Data Types Examples and Playground ''' print("----------------") # int x = 3 print(x) print(type(x)) print("----------------") # float x = 3.0 print(x) print(type(x)) print("----------------") # float x = 3e10 print(x) print(type(x)) print("----------------") # string x = "3" print(x) print(type(x)) print("----------------") # bool x = True print(x) print(type(x)) print("----------------") # string x = "True" print(x) print(type(x)) print("----------------") # complex x = 1 + 2j print(x) print(type(x)) print("----------------") # complex x = complex(1,2) print(x) print(type(x)) print("----------------") # ----------------------------------------------- # Quick Tasks # # What is the data type of complex(1,0)? # What is the data type of float("inf")? # -----------------------------------------------
''' Arguments to Functions Examples and Playground ''' print("----------------") # Default Arguments def log(message = None): "logs a message, if passed" if message: print("LOG: {0}".format(message)) print(log) log("Hello there!") print("----------------") # Default Arguments def greet(name = None): "greets a user, if name known" if name: print("Hello {0}! It's wonderful to meet you.".format(name)) print(greet) greet("Sourav") print("----------------") # Arbitrary Number of Arguments def add_n(first_num, *args): "returns the sum of one or more numbers" num_list = [first_num] + [num for num in args] return sum(num_list) print(add_n) add_n(1, 2, 3, 4) print("----------------") # Arbitrary Number of Arguments def mult_n(*args): "returns the product of one or more numbers" result = 1 for num in args: result *= num return(result) print(mult_n) mult_n(4, 5, 7, 2) print("----------------") # ----------------------------------------------- # Quick Tasks # # Create a function for Temperature conversion. Take user input 32 C to F or 98.6 F to C, and use the function to convert the temperature. Default conversion should be C to F if the user does not specify. # -----------------------------------------------
#!/usr/bin/env python3 import re def integers_in_brackets(s): # result = re.findall(r"\[\s*([+-]?\d+)\s*\]", s) items = re.findall(r"[\[\{\(][^a-zA-Z\]]+[\}\]\)]", s) print(items) L = [] for item in items: if '+-' not in item and '+]' not in item: num = re.findall(r"-?\d+", item) L.append(int(num[0])) return L def main(): str = 'afd [128+] [47 ] [a34] [ +-43 ]tt [+12]xxx' print(str) integers_in_brackets(str) if __name__ == "__main__": main()
#!/usr/bin/env python3 def merge(L1, L2): L3 = L1 + L2 L = [] while len(L3) > 0: min = L3[0] for num in L3: if num < min: min = num L.append(min) L3.remove(min) return L def main(): a = [5, 6, 8] b = [2, 4, 6] print(merge(a , b)) if __name__ == "__main__": main()
#!/usr/bin/env python3 import pandas as pd def powers_of_series(s, k): a = [] for i in range(1, k+1): #df.append(s.values**i) df = pd.DataFrame(s**i, index=s.index, columns=[i]) a.append(df) return pd.concat(a, axis=1) def main(): s = pd.Series([1, 2, 3, 4], index=list("abcd")) print(powers_of_series(s, 3)) if __name__ == "__main__": main()
print(2 - 1) # print('2' - '1') first_name = 'Smit' last_name = 'Patel' name = first_name + '' + last_name print(name) print('Naah, na na nanana naah, nanana naah, hey Jude. \n' *10) print(f'Hello, {name}!') actor = 'Joaquin Phoenix' year = 2020 movie = 'Joker' print(f'{actor} wins Best Actor for {movie}') pi = 3.14159265358 print(f'Pi equals{pi:.3}')
def main(): print("Mad libs generator!\n") line1 = "While {} the other day, you noticed a {} {} whizzing by your lawn at a speed of {} km per hour." wordlist1 = ["(a noun)", "(an adjective)", "(a verb)", "(a number)"] print(line1.format(wordlist1[2], wordlist1[0], wordlist1[1], wordlist1[3])) wordList2 = [] print("Let's fill in the blanks!") print("What's a verb you could do in front of the house?") input1 = input("") print("What is a silly noun that could be on the sidewalk or road?") input2 = input("") print("Write a verb that silly noun could be doing.") input3 = input("") print("What is a crazy speed they could be doing that action at?") input4 = input("") wordList2.append(input1) wordList2.append(input2) wordList2.append(input3) wordList2.append(input4) print(wordList2) print("Let's see what that leaves us with!") print(line1.format(wordList2[2], wordList2[0], wordList2[1], wordList2[3])) main()
def calculate_experince(experinces): years, months = 0, 0 for exp in experinces: years += exp['years'] months += exp['months'] years += months / 12 months = months % 12 print 'You have %s years and %s months experience' with open('test_file.txt') as test_file: exp = {} years, months = 0, 0 for line in test_file: line_years, line_month = [int(item) for item in line.strip().split(",")] years += line_years months += line_month years += months / 12 months = months % 12 print 'You have %s years and %s months experience' % (years, months)
def detect_age(age): if age >= 0 and age <=2: return "Still in Mama's arms" elif age >= 3 and age <=4: return "Preschool Maniac" elif age >= 5 and age <=11: return "Elementary school" elif age >= 12 and age <=14: return "Middle school" elif age >= 15 and age <=18: return "High school" elif age >= 19 and age <=22: return "College" elif age >= 23 and age <=65: return "Working for the man" elif age >= 66 and age <=100: return "The Golden Years" else: return "This program is for humans" with open('test_file.txt','r') as test_file: for line in test_file: age = int(line.strip()) print detect_age(age)
#!/usr/bin/env python # -*- coding:utf-8 -*- # author:艾强云 # Email:[email protected] # datetime:2019/7/5 16:08 # software: PyCharm import math #log a(di) B(zhen) = c(zhi) a ** c = b while True: a = input("请输入底数") b = input("请输入真数") c = input("请输入指数") if a == '': #利用pow(a, b)函数即可。需要开a的r次方则pow(a, 1.0/r) a = math.pow(float(b), 1/float(c)) elif b == '': b = float(a) ** float(c) else: c = math.log(float(b), float(a)) print("底数,真数,指数分别为:") print(a, b, c)
#num = int(input("Enter number > 5 to print Heart :")) num = 6 for row in range(num): for col in range(num+1): if (row==0 and col%3 !=0) or (row == 1 and col % 3 ==0) or ((row-col)==2) or (row+col==8): print("* ", end="") else: print(" ", end="") else: print() # Output : # * * * * #* * * #* * # * * # * * # *
class Deque(object): def __init__(self): self.items = [] def isempty(self): return self.items == [] def add_front(self, item): self.items.append(item) def add_rear(self, item): self.items.insert(0, item) def remove_front(self): return self.items.pop() def remove_rear(self): return self.items.pop(0) def size(self): return len(self.items) def print_stack(self): for item in self.items: print(item) deque = Deque() print('Size :: ', deque.size()) print('Is Empty :: ', deque.isempty()) print('Add Front (1) :: ', deque.add_front(1)) print('Add Rear (2) :: ', deque.add_rear(2)) print('Remove Front (1) :: ', deque.remove_front()) print('Remove Rear (2) :: ', deque.remove_rear()) print('Add Front (Aryan) :: ', deque.add_front('Aryan')) print('Add Rear (True) :: ', deque.add_rear(True)) print('Size :: ', deque.size()) print('Is Empty :: ', deque.isempty()) print('******************************** ') print(deque.print_stack()) # ------------------- # Output # ------------------- # Size :: 0 # Is Empty :: True # Add Front (1) :: None # Add Rear (2) :: None # Remove Front (1) :: 1 # Remove Rear (2) :: 2 # Add Front (Aryan) :: None # Add Rear (True) :: None # Size :: 2 # Is Empty :: False # ******************************** # True # Aryan # None
class BalancedParenthesisCheck(object): def is_balanced(self, str): stack = [] opening_parenthesis = ['(', '{', '['] matches = set(( ('(', ')'), ('{', '}'), ('[',']') )) for s in str: if s in opening_parenthesis: stack.append(s) else: if len(stack) == 0: return False last_open = stack.pop() if (last_open, s) not in matches: return False return len(stack) == 0 balanced = BalancedParenthesisCheck() print('{{(([[{}]]))}} :: ', balanced.is_balanced("{{(([[{}]]))}}")) print('{([{}])} :: ', balanced.is_balanced("{([{}])}")) print('{(} :: ', balanced.is_balanced("{(}")) # ------------------- # Output # ------------------- # {{(([[{}]]))}} :: True # {([{}])} :: True # {(} :: False
class ReverseWordOrder(object): @staticmethod def reverse1(str): return " ".join(reversed(str.split())) @staticmethod def reverse2(str): return " ".join(str.split()[::-1]) print(ReverseWordOrder.reverse1("best answer")) print(ReverseWordOrder.reverse2("best answer")) # ------------------- # Output # ------------------- # answer best # answer best
#!/usr/bin/env python # -*- coding: utf-8 -*- # 標準ライブラリ import math # 3次元座標の変換用クラス # 高速化のためfor文を使わずベタ書き # 平行移動 # | 1 0 0 Tx | | x | # | 0 1 0 Ty | \/ | y | # | 0 0 1 Tz | /\ | z | # | 0 0 0 1 | | 1 | # # X軸回転 # | 1 0 0 0 | | x | # | 0 cosθ -sinθ 0 | \/ | y | # | 0 sinθ cosθ 0 | /\ | z | # | 0 0 0 1 | | 1 | # # Y軸回転 # | cosθ 0 sinθ 0 | | x | # | 0 1 0 0 | \/ | y | # | -sinθ 0 cosθ 0 | /\ | z | # | 0 0 0 1 | | 1 | # # Z軸回転 # | cosθ -sinθ 0 0 | | x | # | sinθ cosθ 0 0 | \/ | y | # | 0 0 1 0 | /\ | z | # | 0 0 0 1 | | 1 | class Transform3D(object): def __init__(self): # 4x4の単位行列を作成 self.mat = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] # 行列の値をセットする valuesは4x4の2次元配列 def set(self,values): self.mat[0][0] = values[0][0] self.mat[0][1] = values[0][1] self.mat[0][2] = values[0][2] self.mat[0][3] = values[0][3] self.mat[1][0] = values[1][0] self.mat[1][1] = values[1][1] self.mat[1][2] = values[1][2] self.mat[1][3] = values[1][3] self.mat[2][0] = values[2][0] self.mat[2][1] = values[2][1] self.mat[2][2] = values[2][2] self.mat[2][3] = values[2][3] self.mat[3][0] = values[3][0] self.mat[3][1] = values[3][1] self.mat[3][2] = values[3][2] self.mat[3][3] = values[3][3] # 積算 自分x相手 def mulR(self, other): # 結果格納用 res = [[0 for m in range(4)] for n in range(4)] # 1行目 res[0][0] = self.mat[0][0]*other[0][0] + self.mat[0][1]*other[1][0] + self.mat[0][2]*other[2][0] + self.mat[0][3]*other[3][0] res[0][1] = self.mat[0][0]*other[0][1] + self.mat[0][1]*other[1][1] + self.mat[0][2]*other[2][1] + self.mat[0][3]*other[3][1] res[0][2] = self.mat[0][0]*other[0][2] + self.mat[0][1]*other[1][2] + self.mat[0][2]*other[2][2] + self.mat[0][3]*other[3][2] res[0][3] = self.mat[0][0]*other[0][3] + self.mat[0][1]*other[1][3] + self.mat[0][2]*other[2][3] + self.mat[0][3]*other[3][3] # 2行目 res[1][0] = self.mat[1][0]*other[0][0] + self.mat[1][1]*other[1][0] + self.mat[1][2]*other[2][0] + self.mat[1][3]*other[3][0] res[1][1] = self.mat[1][0]*other[0][1] + self.mat[1][1]*other[1][1] + self.mat[1][2]*other[2][1] + self.mat[1][3]*other[3][1] res[1][2] = self.mat[1][0]*other[0][2] + self.mat[1][1]*other[1][2] + self.mat[1][2]*other[2][2] + self.mat[1][3]*other[3][2] res[1][3] = self.mat[1][0]*other[0][3] + self.mat[1][1]*other[1][3] + self.mat[1][2]*other[2][3] + self.mat[1][3]*other[3][3] # 3行目 res[2][0] = self.mat[2][0]*other[0][0] + self.mat[2][1]*other[1][0] + self.mat[2][2]*other[2][0] + self.mat[2][3]*other[3][0] res[2][1] = self.mat[2][0]*other[0][1] + self.mat[2][1]*other[1][1] + self.mat[2][2]*other[2][1] + self.mat[2][3]*other[3][1] res[2][2] = self.mat[2][0]*other[0][2] + self.mat[2][1]*other[1][2] + self.mat[2][2]*other[2][2] + self.mat[2][3]*other[3][2] res[2][3] = self.mat[2][0]*other[0][3] + self.mat[2][1]*other[1][3] + self.mat[2][2]*other[2][3] + self.mat[2][3]*other[3][3] # 4行目 res[3][0] = self.mat[3][0]*other[0][0] + self.mat[3][1]*other[1][0] + self.mat[3][2]*other[2][0] + self.mat[3][3]*other[3][0] res[3][1] = self.mat[3][0]*other[0][1] + self.mat[3][1]*other[1][1] + self.mat[3][2]*other[2][1] + self.mat[3][3]*other[3][1] res[3][2] = self.mat[3][0]*other[0][2] + self.mat[3][1]*other[1][2] + self.mat[3][2]*other[2][2] + self.mat[3][3]*other[3][2] res[3][3] = self.mat[3][0]*other[0][3] + self.mat[3][1]*other[1][3] + self.mat[3][2]*other[2][3] + self.mat[3][3]*other[3][3] # 計算結果反映 self.set(res) # 積算 相手x自分 def mulL(self, other): # 結果格納用 res = [[0 for m in range(4)] for n in range(4)] # 1行目 res[0][0] = other[0][0]*self.mat[0][0] + other[0][1]*self.mat[1][0] + other[0][2]*self.mat[2][0] + other[0][3]*self.mat[3][0] res[0][1] = other[0][0]*self.mat[0][1] + other[0][1]*self.mat[1][1] + other[0][2]*self.mat[2][1] + other[0][3]*self.mat[3][1] res[0][2] = other[0][0]*self.mat[0][2] + other[0][1]*self.mat[1][2] + other[0][2]*self.mat[2][2] + other[0][3]*self.mat[3][2] res[0][3] = other[0][0]*self.mat[0][3] + other[0][1]*self.mat[1][3] + other[0][2]*self.mat[2][3] + other[0][3]*self.mat[3][3] # 2行目 res[1][0] = other[1][0]*self.mat[0][0] + other[1][1]*self.mat[1][0] + other[1][2]*self.mat[2][0] + other[1][3]*self.mat[3][0] res[1][1] = other[1][0]*self.mat[0][1] + other[1][1]*self.mat[1][1] + other[1][2]*self.mat[2][1] + other[1][3]*self.mat[3][1] res[1][2] = other[1][0]*self.mat[0][2] + other[1][1]*self.mat[1][2] + other[1][2]*self.mat[2][2] + other[1][3]*self.mat[3][2] res[1][3] = other[1][0]*self.mat[0][3] + other[1][1]*self.mat[1][3] + other[1][2]*self.mat[2][3] + other[1][3]*self.mat[3][3] # 3行目 res[2][0] = other[2][0]*self.mat[0][0] + other[2][1]*self.mat[1][0] + other[2][2]*self.mat[2][0] + other[2][3]*self.mat[3][0] res[2][1] = other[2][0]*self.mat[0][1] + other[2][1]*self.mat[1][1] + other[2][2]*self.mat[2][1] + other[2][3]*self.mat[3][1] res[2][2] = other[2][0]*self.mat[0][2] + other[2][1]*self.mat[1][2] + other[2][2]*self.mat[2][2] + other[2][3]*self.mat[3][2] res[2][3] = other[2][0]*self.mat[0][3] + other[2][1]*self.mat[1][3] + other[2][2]*self.mat[2][3] + other[2][3]*self.mat[3][3] # 4行目 res[3][0] = other[3][0]*self.mat[0][0] + other[3][1]*self.mat[1][0] + other[3][2]*self.mat[2][0] + other[3][3]*self.mat[3][0] res[3][1] = other[3][0]*self.mat[0][1] + other[3][1]*self.mat[1][1] + other[3][2]*self.mat[2][1] + other[3][3]*self.mat[3][1] res[3][2] = other[3][0]*self.mat[0][2] + other[3][1]*self.mat[1][2] + other[3][2]*self.mat[2][2] + other[3][3]*self.mat[3][2] res[3][3] = other[3][0]*self.mat[0][3] + other[3][1]*self.mat[1][3] + other[3][2]*self.mat[2][3] + other[3][3]*self.mat[3][3] # 計算結果反映 self.set(res) # 並行移動 def Translate(self, tx, ty, tz): trans = [[1, 0, 0, tx], \ [0, 1, 0, ty], \ [0, 0, 1, tz], \ [0, 0, 0, 1]] self.mulL(trans) # X-Y-Z回転[deg] この回転だとズレるので本当はクォータニオンにしたい def RotateXYZ(self, rx, ry, rz): sx = math.sin(math.radians(rx)) cx = math.cos(math.radians(rx)) sy = math.sin(math.radians(ry)) cy = math.cos(math.radians(ry)) sz = math.sin(math.radians(rz)) cz = math.cos(math.radians(rz)) # 回転行列計算(X軸回転->Y軸回転->Z軸回転をひとまとめ) rot = [[cy*cz, sx*sy*cz-cx*sz, cx*sy*cz+sx*sz, 0], \ [cy*sz, sx*sy*sz+cx*cz, cx*sy*sz-sx*cz, 0], \ [ -sy, sx*cy, cx*cy, 0], \ [ 0, 0, 0, 1]] self.mulL(rot) # 座標変換 自分×変換対象(変換対象の形式は[x y z 1]) def Transform(self, coordinate): # 結果格納用 res = [0 for m in range(4)] # 変換実行 res[0] = self.mat[0][0]*coordinate[0] + self.mat[0][1]*coordinate[1] + self.mat[0][2]*coordinate[2] + self.mat[0][3]*coordinate[3] res[1] = self.mat[1][0]*coordinate[0] + self.mat[1][1]*coordinate[1] + self.mat[1][2]*coordinate[2] + self.mat[1][3]*coordinate[3] res[2] = self.mat[2][0]*coordinate[0] + self.mat[2][1]*coordinate[1] + self.mat[2][2]*coordinate[2] + self.mat[2][3]*coordinate[3] res[3] = self.mat[3][0]*coordinate[0] + self.mat[3][1]*coordinate[1] + self.mat[3][2]*coordinate[2] + self.mat[3][3]*coordinate[3] return res
import random ROCK = "rock" PAPER = "paper" SCISSORS = "scissors" computer_input_list = [ROCK, PAPER, SCISSORS] computer_input = random.choice(computer_input_list) #print(computer_input) comp = "" if(computer_input == ROCK): comp = 1; elif(computer_input == SCISSORS): comp = 2 else: comp = 3 user_input = input("Enter your choice - rock, paper, scissors : ") user_choice = "" if(user_input == ROCK): user_choice = 1 elif(user_input == SCISSORS): user_choice = 2 else: user_choice = 3 #print(user_input) print("Your opponent opted : ", computer_input) if(comp == user_choice): print("its a tie") elif(comp == 1 and user_choice == 2): print("Sorry , you loose") elif(comp == 2 and user_choice == 3): print("Sorry , you loose") elif(comp == 3 and user_choice == 1): print("Sorry , you loose") else: print("You won")
''' print "Hello" Mylist = [] for i in range(1,301): Mylist.append(i) print(Mylist) Mylist = [] for x in Mylist: if (x % 26 == 0): print(x) for i in range(1,301): if(i % 26 == 0): print(i) ''' Mylist = [] A=0 for i in range(1,201): Mylist.append(i) if(i % 17 == 0): A=A+i print("Sum of numbers divisible by 17 is",A) print(Mylist)
import requests def main(): currency = get_target_currency() bitcoin = get_number_of_bitcoins() converted = convert_bitcoin_to_target(bitcoin, currency) display_result(bitcoin, currency, converted) def get_target_currency(): # Get target currency currencySymbol = "" currencyInitials = input("Enter target currency code e.g. USD, CNY: ").upper() while True: if (currencyInitials == "USD" or currencyInitials == "CNY"): break else: currencyInitials = input("Enter target currency code e.g. USD, CNY: ").upper() return currencyInitials def get_number_of_bitcoins(): # Get number of bitcoin bitcoin = float(input("Enter the number of bitcoins: ")) return bitcoin def convert_bitcoin_to_target(bitcoin, target_currency): # Convert amount of bitcoin to target currency exchange_rate = get_exchange_rate(target_currency) converted = convert(bitcoin, exchange_rate) return converted def get_exchange_rate(currency): # Call API with currency as parameter response = request_rates(currency) rate = extract_rate(response, currency) return rate def request_rates(currency): # Perform API request and return response params = currency url = "https://api.coindesk.com/v1/bpi/currentprice/" + params return requests.get(url).json() def extract_rate(rate, currency): # Process JSON response and extract rate information return rate["bpi"][currency]["rate_float"] def convert(amount, exchange_rate): # Convert bitcoin to target currency using given exchange rate return amount * exchange_rate def display_result(bitcoin, currency, converted): # Format and print information to screen print(f"{bitcoin} bitcoin is equal to {converted} {currency}.") if __name__ == '__main__' : main()
# -*- coding: cp1252 -*- import csv InputFile_name = "Day2Part1Data.csv" InputFile_h = open(InputFile_name,'r') CSVInput = csv.reader(InputFile_h) next(CSVInput) #HEADER valid_pw = 0 for record in CSVInput: min_occ = int(record[0].strip()) max_occ = int(record[1].strip()) letter = record[2].strip() password = record[3].strip() ## print(min_occ) ## print(max_occ) ## print(letter) ## print(password) ## print(password[min_occ-1]) ## print(password[max_occ-1]) if (password[min_occ-1] == letter and password[max_occ-1] != letter) or (password[min_occ-1] != letter and password[max_occ-1] == letter) : valid_pw += 1 print (valid_pw) InputFile_h.close()
def cargar_archivo(lab): return open(lab) ## Mat es la copia de la matriz que se carga en el archivo,fil (fila inicial), col (Columna inicial) , aux ( Ayuda a controlar el tamao de la matriz ## para no salirse del limite), tam (es el tamao del lado de la matriz cargada nxn) def Derecha(mat,fil,col,aux,tam): if(tam>0): # Si el tamao de aux no supera el tamao de la matriz, imprime las coordenadas iniciales que se le dieron y luego se suma 1 a la columna para # avanzar por columna hacia la derecha. if(aux<tam): print(mat[fil][col]) # Recursividad Derecha(mat,fil,col+1,aux+1,tam) # cuando el tamao auxiliar es igual al tamao de lado n de la matiz quiere decir que se paso 1 columna fuera de la matriz # por lo tanto se resta 1 columna y se agrega 1 fila para continuar con el siguiente dato y se resta 1 en el tamao de la matriz # para imprimir los otros datos sin pasar del limite. (La nueva fila y columna pasa a la funcion de mvoer abajo) if(aux==tam): Abajo(mat,fil+1,col-1,0,tam-1) else: print("") def Abajo(mat,fil,col,aux,tam): if(tam>0): if(aux<tam): print(mat[fil][col]) Abajo(mat,fil+1,col,aux+1,tam) if(aux==tam): Izquierda(mat,fil-1,col-1,0,tam) else: print("") def Izquierda(mat,fil,col,aux,tam): if(tam>0): if(aux<tam): print(mat[fil][col]) Izquierda(mat,fil,col-1,aux+1,tam) if(aux==tam): Arriba(mat,fil-1,col+1,0,tam-1) else: print("") def Arriba(mat,fil,col,aux,tam): if(tam>0): if(aux<tam): print(mat[fil][col]) Arriba(mat,fil-1,col,aux+1,tam) if(aux==tam): Derecha(mat,fil+1,col+1,0,tam) else: print("") # Funcion a la que se envia una matriz vacia y la matriz que viene del archivo para ser cargada def crear_mat(mat,lab): for x in cargar_archivo(lab): mat.append(x.strip().split()) # Retorna la matriz ya llena con los datos cargados return mat # funcion a la que se envian los datos de entrada suponiendo que se comienzan desde las coordenadas 0,0 y hacia la derecha def RecorrerMatriz(lab): Derecha(crear_mat([],lab),0,0,0,len(crear_mat([],lab))) RecorrerMatriz("Matriz.txt")
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # 1 ''' load the dataset''' museum_data = pd.read_csv('museum.csv',index_col=0,parse_dates=True) # 2 '''print last five rows of dataset''' print(museum_data.tail()) ''' Fill in the line below: How many visitors did the Chinese American Museum receive in July 2018?''' ca_museum_jul18 = museum_data['Chinese American Museum']['2018-07-01'] ''' Fill in the line below: In October 2018, how many more visitors did Avila Adobe receive than the Firehouse Museum?''' avila_oct18 = museum_data['Avila Adobe']['2018-10-01']-museum_data['Firehouse Museum']['2018-10-01'] # 3 '''Line chart showing the number of visitors to each museum over time''' sns.lineplot(data=museum_data) # 4 '''Line plot showing the number of visitors to Avila Adobe over time''' sns.lineplot(data=museum_data['Avila Adobe'])
# 1 def select_second(L): """Return the second element of the given list. If the list has no second element, return None. """ if len(L)<2: return None else: return L[1] # 2 def losing_team_captain(teams): """Given a list of teams, where each team is a list of names, return the 2nd player (captain) from the last listed team """ return teams[-1][1] # 3 def purple_shell(racers): """Given a list of racers, set the first place racer (at the front of the list) to last place and vice versa. >>> r = ["Mario", "Bowser", "Luigi"] >>> purple_shell(r) >>> r ["Luigi", "Bowser", "Mario"] """ racers[0], racers[-1] = racers[-1], racers[0] # 4 a = [1, 2, 3] b = [1, [2, 3]] c = [] d = [1, 2, 3][1:] # Put your predictions in the list below. Lengths should contain 4 numbers, the # first being the length of a, the second being the length of b and so on. lengths = [3,2,0,2] # 5 '''party_attendees = ['Adela', 'Fleda', 'Owen', 'May', 'Mona', 'Gilbert', 'Ford'] A guest is considered 'fashionably late' if they arrived after at least half of the party's guests. However, they must not be the very last guest (that's taking it too far). In the above example, Mona and Gilbert are the only guests who were fashionably late.''' def fashionably_late(arrivals, name): """Given an ordered list of arrivals to the party and a name, return whether the guest with that name was fashionably late. """ l = len(arrivals) if l%2==0: if name in arrivals[l//2:-1]: return True return False else: if name in arrivals[(l//2)+1:-1]: return True return False
#영단어 맞추기 게임 import random words_dict = { "사자" : "lion", "호랑이" : "tiger", "사과" : "apple", "비행기" : "airplane", } words = [] for word in words_dict: words.append(word) random.shuffle(words) chance = 3 for i in range(0, len(words)): #문제 개수 (4개) q = words[i] for j in range(0, chance): #총 기회 (3번) user_input = str(input("{}의 영어 단어를 입력하세요 >> " .format(q))) english = words_dict[q] if user_input.strip().lower() == english.lower(): print("정답입니다.") break else: print("틀렸습니다.") if user_input != english: print("정답은 {}입니다.".format(english)) print("문제가 더이상 없습니다.")
# Simulation of Proof Of Work Protocol from block import Block import hashlib # Function to solve math puzzle; find a SHA256 hash key depending on the difficulty set def pow(key, difficulty): dif_list = [0] * difficulty dif_str = "".join(str(x) for x in dif_list) nonceValue = 0 hash_value = hashlib.sha256(str.encode(key + str(nonceValue))).hexdigest() check = list() for i in hash_value[:difficulty]: check.append(i) check_str = "".join(str(x) for x in check) while dif_str != check_str: nonceValue += 1 hash_value = hashlib.sha256(str.encode(key + str(nonceValue))).hexdigest() check = list() for i in hash_value[:difficulty]: check.append(i) check_str = "".join(str(x) for x in check) print("Nonce value is:" ,nonceValue) print("Hash value is:", hash_value) return nonceValue # Check whether the new block key matches the pow protocol def check(hash_value, difficulty): dif_list = [0] * difficulty dif_str = "".join(str(x) for x in dif_list) check = list() for i in hash_value[:difficulty]: check.append(i) check_str = "".join(str(x) for x in check) if dif_str == check_str: return True else: return False
# https://leetcode.com/problems/validate-binary-search-tree/ # Given the root of a binary tree, determine if it is a valid binary search tree (BST). # A valid BST is defined as follows: # The left subtree of a node contains only nodes with keys less than the node's key. # The right subtree of a node contains only nodes with keys greater than the node's key. # Both the left and right subtrees must also be binary search trees. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # Solution 1 - recursive DFS # O(n) time complexity, O(n) space complexity class Solution(object): # Using Depth First Search to go through the tree and validate def isValidBST(self, root): """ :type root: list :rtype: bool """ # Older versions of Python don't have math.inf module, we have to use float("inf") instead return self.traverse_preorder(root, -float("inf"), float("inf")) # Pre-order DFS traverse def traverse_preorder(self, current_node, min_val, max_val): # if the current node value is smaller than or equal to minimum, it is not valid BST # if the current node value is larger or equal to maximum, it is not a valid BST if current_node.val <= min_val or current_node.val >= max_val: return False # go to the left node, left node's value must be smaller than current node's value if current_node.left is not None: if not self.traverse_preorder(current_node.left, min_val, current_node.val): return False # got to the right node, right node's value must be larger than current node's value if current_node.right is not None: if not self.traverse_preorder(current_node.right, current_node.val, max_val): return False # If we've got here, it must be a valid BST return True # Solution 2 - iterative DFS # O(n) time complexity, O(n) space complexity class Solution(object): # Using Depth First Search to go through the tree and validate def isValidBST(self, root): """ :type root: list :rtype: bool """ if root is None: return True # we have to make our own stack # Older versions of Python don't have math.inf module, we have to use float("inf") instead stack = [[root, -float("inf"), float("inf")]] while len(stack) > 0: current = stack.pop() current_node = current[0] min_val = current[1] max_val = current[2] if current_node.val <= min_val or current_node.val >= max_val: return False if current_node.left is not None: stack.append([current_node.left, min_val, current_node.val]) if current_node.right is not None: stack.append([current_node.right, current_node.val, max_val]) # If we have got this far, the tree is a valid BST return True
# https://leetcode.com/problems/number-of-1-bits/ # Write a function that takes an unsigned integer # and returns the number of '1' bits it has (also known as the Hamming weight). # O(number of 1 bits in n) time complexity, O(1) space complexity def hamming_weight(n): """ :type n: int :rtype: int """ # We continue removing 1 bits until n == 0 # -1- 0 0 - > 2^2 = 4 # -0- 1 1 (n - 1 = 4 - 1 = 3) -> current bit becomes 0 (binary 0 1 1) # -0- 0 0 - n & (n - 1) - result is 1 only if both n and (n - 1) are 1, which they are not # So n & (n - 1) is 1 0 0 & 0 1 1 = 0 0 0 # # Or with number n = 1101, n - 1 = 1100, 1101 & 1100 = 1100 - we remove one 1bit every cycle # Next cycle n = 1100, n - 1 = 1011, 1100 & 1011 = 1000 # The last cycle n = 1000, n - 1 = 0111, 1000 & 0111 = 0000 - we have finished count = 0 while n != 0: n = n & (n - 1) count += 1 return count print(hamming_weight(0o0000000000000000000000000001011)) print(hamming_weight(0o0000000000000000000000010000000)) print(hamming_weight(0o11111111111111111111111111111101))
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ # You are given an array prices where prices[i] is the price of a given stock on the ith day. # You want to maximize your profit by choosing a single day to buy one stock # and choosing a different day in the future to sell that stock. # Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0 # # O(n^2) solution # def max_profit_func(prices): # """ # :type prices: List[int] # :rtype: int # """ # max_profit = 0 # for i in range(0, len(prices)): # # Go backwards towards current i to find the best profit # for j in range(len(prices) - 1, i, -1): # best_price = prices[j] - prices[i] # if best_price > max_profit: # max_profit = best_price # return max_profit # O(n) solution def max_profit_func(prices): """ :type prices: List[int] :rtype: int """ min_price = prices[0] max_profit = 0 for i in range(0, len(prices)): if prices[i] - min_price > max_profit: max_profit = prices[i] - min_price if prices[i] < min_price: min_price = prices[i] return max_profit print(f"Max profit: {max_profit_func([7, 1, 5, 3, 6, 4])}") print(f"Max profit: {max_profit_func([7, 6, 4, 3, 1])}") print(f"Max profit: {max_profit_func([2, 1, 4])}") print(f"Max profit: {max_profit_func([1, 2])}")
# https://leetcode.com/problems/merge-sorted-array/ # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # The number of elements initialized in nums1 and nums2 are m and n respectively. # You may assume that nums1 has a size equal to m + n # such that it has enough space to hold additional elements from nums2. # Solution 1 # O(n^2) time complexity, O(1) space complexity # as we have to modify nums1 in-place, we can't use extra list for the sorting # the time complexity is thus higher, as we have to move items in nums1 during merging def merge(nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead. """ i = 0 j = 0 while j < n: # if we iterated through nums1 if i >= m: nums1[i] = nums2[j] i += 1 j += 1 # if we iterated through nums2 elif j >= n: return # otherwise keep iterating over both else: # if nums1[i] is smaller or equal to nums2[j], it stays in place if nums1[i] <= nums2[j]: i += 1 # if nums2[j] is smaller, it is copied over to nums1[i] else: # all other items behind nums1[i] have to be moved starting from the end of the list (m) # we iterate backwards - the last item is length of both list (m + n) minus 1 # the first item is i for k in range(m, i, -1): nums1[k] = nums1[k - 1] nums1[i] = nums2[j] j += 1 # i has to be increased by 1 - original item has moved by 1 to make space for item from nums2 i += 1 # number of items in nums1 was increased m += 1 list1 = [4, 5, 6, 0, 0, 0] list2 = [1, 2, 3] list3 = [1] list4 = [] print(f"nums1 = {list1}") print(f"nums2 = {list2}") merge(nums1=list1, m=3, nums2=list2, n=3) print(f"nums2 merged in nums1 = {list1}") # # Solution 2 (by Eric Welch) # # Not what would interviewers look for, but practically the easiest and simplest # def merge2(nums1, m, nums2, n): # nums1[m:] = nums2[:n] # nums1.sort() # # # print(f"nums1 = {list1}") # print(f"nums2 = {list2}") # # merge2(nums1=list1, m=3, nums2=list2, n=3) # # print(f"nums2 merged in nums1 = {list1}")
# Bubble sort O(n^2) - super inefficient, space complexity O(1) def bubble_sort(num_list): """Bubble sort. Sorts the list of integers passed to it as an argument.""" for _ in num_list: for i in range(len(num_list) - 1): if num_list[i] > num_list[i + 1]: # Swap the two numbers temp = num_list[i] num_list[i] = num_list[i + 1] num_list[i + 1] = temp numbers = [13, 33, 6, 187, 1, 5, 89, 56, 2, 11] print(f"Unsorted input: {numbers}") bubble_sort(numbers) print(f"Sorted output: {numbers}")
# https://leetcode.com/problems/excel-sheet-column-number/ # Given a string columnTitle that represents the column title as appear in an Excel sheet, # return its corresponding column number. def title_to_number(column_title): """ :type column_title: str :rtype: int """ title = column_title.lower() column_dict = { "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, "l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r": 18, "s": 19, "t": 20, "u": 21, "v": 22, "w": 23, "x": 24, "y": 25, "z": 26 } if len(title) == 0: return 0 elif len(title) == 1: return column_dict[title] # If title has more than one character else: final_number = 0 # Go through title character by character # First character is always character value # Each following character value is final_number * 26 + current character value for i in range(len(title)): if i == 0: final_number = column_dict[title[i]] else: final_number = final_number * 26 + column_dict[title[i]] return final_number print(title_to_number("AA")) print(title_to_number("FXSHRXW"))
# Merge sorted arrays O(a+b) def merge_sorted_arrays(array1, array2): merged_array = [] i = 0 j = 0 while i < len(array1) or j < len(array2): if i < len(array1) and j < len(array2): # Append the smaller item to the merge_array if array1[i] < array2[j]: merged_array.append(array1[i]) i += 1 else: merged_array.append(array2[j]) j += 1 else: # One of the arrays is at its end and i or j is out of range if j < len(array2): merged_array.append(array2[j]) j += 1 if i < len(array1): merged_array.append(array1[i]) i += 1 return merged_array print(merge_sorted_arrays([0, 3, 4, 31, 33, 41], [4, 6, 32, 64])) # ---------------------------------------------------------------------------------------------------------------------- # # Easy fast way # def merge_sorted_arrays_easy(array1, array2): # return sorted(array1 + array2) # # # print(merge_sorted_arrays_easy([0, 3, 4, 31, 33, 41], [4, 6, 32, 64]))
# https://leetcode.com/problems/longest-substring-without-repeating-characters/ # Given a string s, find the length of the longest substring without repeating characters. # Solution 1 - moving window # O(n) time complexity, O(n) space complexity def length_of_longest_substring(s): """ :type s: str :rtype: int """ current_count = 0 highest_count = 0 seen_chars = {} i = 0 while i < len(s): # check the current char if s[i] in seen_chars: # if char is repeating, record the highest_count if current_count > highest_count: highest_count = current_count # reset values # move i to the last non-repeating position i = seen_chars[s[i]] + 1 current_count = 0 seen_chars = {} # store the position of the current char seen_chars[s[i]] = i current_count += 1 # increment i i += 1 # check in case of all unique characters in a string if current_count > highest_count: return current_count return highest_count # print(length_of_longest_substring("abcabcbb")) # print(length_of_longest_substring("bbbbb")) # print(length_of_longest_substring("pwwkew")) # print(length_of_longest_substring("")) # print(length_of_longest_substring(" ")) # print(length_of_longest_substring("dvdf")) # Solution 2 - optimized moving window - without moving back # O(n) time complexity, O(n) space complexity def length_of_longest_substring_2(s): """ :type s: str :rtype: int """ start = 0 highest_count = 0 seen_chars = {} i = 0 while i < len(s): # check the current char # seen_chars[s[i]] must be >= start so we don't move backwards - "abba" if s[i] in seen_chars and seen_chars[s[i]] >= start: # if char is repeating, record the highest_count if i - start > highest_count: highest_count = i - start # start i to the last non-repeating position start = seen_chars[s[i]] + 1 # store the position of the current char seen_chars[s[i]] = i # increment i i += 1 # check in case of all unique characters in a string if i - start > highest_count: return i - start return highest_count print(length_of_longest_substring_2("abcabcbb")) print(length_of_longest_substring_2("bbbbb")) print(length_of_longest_substring_2("pwwkew")) print(length_of_longest_substring_2("")) print(length_of_longest_substring_2(" ")) print(length_of_longest_substring_2("dvdf")) print(length_of_longest_substring_2("abba"))
# Hackerrank problem # Determine the maximum positive spread for a stock given its price history # If the stock remains flat or declines for the full period, return -1 # Complete the 'maxDifference' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY px as parameter. # def max_difference(px): min_price = px[0] max_profit = 0 for i in range(1, len(px)): if px[i] < min_price: min_price = px[i] if px[i] - min_price > max_profit: max_profit = px[i] - min_price if max_profit < 1: return -1 return max_profit print(max_difference([7, 1, 2, 5])) print(max_difference([7, 5, 3, 1])) # 1222 output expected print(max_difference([100, -129, 877, -166, 433, 547, 413, 311, 311, 307, 15, 334, -58, 821, 335, 646, 697, 845, -156, 781, -84, 675, 833, 182, 937, -246, 865, 603, 534, 912, 618, 494, -73, 131, 28, 282, 412, 489, 902, 842, 259, 844, 720, 324, -154, 757, 662, 628, -5, 163, 178, -7, -18, 365, 303, 530, 744, 838, 626, -175, 216, 22, 976, 704, 782, 579, 151, 764, 494, -28, 699, 718, 351, 959, 407, 256, 215, 952, 328, 631, 228, 711, 438, 753, 830, 28, 81, 410, 621, 543, 745, 714, 829, 457, 481, 136, 134, 50, 678, -235, 256]))
# https://leetcode.com/problems/count-and-say/ # The count-and-say sequence is a sequence of digit strings defined by the recursive formula: # countAndSay(1) = "1" # countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), # which is then converted into a different digit string. # To determine how you "say" a digit string, # split it into the minimal number of groups so that each group is a contiguous section all of the same character. # Then for each group, say the number of characters, then say the character. # To convert the saying into a digit string, replace the counts with a number and concatenate every saying. # Given a positive integer n, return the nth term of the count-and-say sequence. # Hint: The following are the terms from n=1 to n=10 of the count-and-say sequence: # 1. 1 # 2. 11 # 3. 21 # 4. 1211 # 5. 111221 # 6. 312211 # 7. 13112221 # 8. 1113213211 # 9. 31131211131221 # 10. 13211311123113112211 # O(2^n) time complexity, O(2^n) space complexity def count_and_say(n): """ :type n: int :rtype: str """ if n == 1: return "1" last_in_sequence = "1" for i in range(n - 1): new_in_sequence = "" digit_counter = 0 last_digit = last_in_sequence[0] # Go through each digit and count it for digit in range(len(last_in_sequence)): # if the current digit is not the same as the last digit # add the last_digit in the new_in_sequence if last_digit != last_in_sequence[digit]: new_in_sequence += str(digit_counter) + last_digit # Reset the counter digit_counter = 1 else: digit_counter += 1 # if digit is the last digit in the current sequence if digit == len(last_in_sequence) - 1: new_in_sequence += str(digit_counter) + last_in_sequence[digit] # The current digit is now the last digit for the next iteration last_digit = last_in_sequence[digit] # replace previous n-1 sequence item with the new item last_in_sequence = new_in_sequence return last_in_sequence print(count_and_say(1)) print(count_and_say(4)) print(count_and_say(6)) print(count_and_say(10))
# https://leetcode.com/problems/maximum-number-of-balloons/ # Given a string text, # you want to use the characters of text to form as many instances of the word "balloon" as possible. # You can use each character in text at most once. Return the maximum number of instances that can be formed. # Solution 1 - two dictionaries - universal, should works for any string # O(n) time complexity, O(n) space complexity def max_number_of_balloons(text): """ :type text: str :rtype: int """ balloon = "balloon" char_dict = {} # create dictionary with char count of balloon (can be used for any other string) for i in range(len(balloon)): if balloon[i] in char_dict: char_dict[balloon[i]] += 1 else: char_dict[balloon[i]] = 1 # check text for amount of letters from char_dict in text char_dict_2 = {} for i in range(len(text)): if text[i] in char_dict: if text[i] in char_dict_2: char_dict_2[text[i]] += 1 else: char_dict_2[text[i]] = 1 # calculate how many instaces of balloon can we form from text # has to be min_instances = float("inf") - LeetCode runs older version of Python # in Python 3 we import math and use min_instances = math.inf min_instances = float("inf") for char in char_dict: if char in char_dict_2: current_instances = char_dict_2[char] // char_dict[char] min_instances = min(min_instances, current_instances) else: return 0 return min_instances print(max_number_of_balloons("nlaebolko")) print(max_number_of_balloons("loonbalxballpoon")) print(max_number_of_balloons("leetcode"))
from collections import deque class Graph: def __init__(self, adjacency_list): self.adjacency_list = adjacency_list # O(v + e) time complexity (every node and every edge is visited) # O(n) space complexity def bfs_traversal(self, start): if len(self.adjacency_list) > 0: queue = deque([start]) values = [] seen = set() while len(queue) > 0: current = queue.popleft() # append actual vertex value to return at the end values.append(current) # remember visited vertices seen.add(current) # check adjacency list for connections if len(self.adjacency_list[current]) > 0: for vertex in self.adjacency_list[current]: # add all connected vertices, # but only if they were not visited yet if vertex not in seen: queue.append(vertex) return values # O(v + e) time complexity (every node and every edge is visited) # O(n) space complexity def dfs_traversal(self, start): if len(self.adjacency_list) > 0: stack = [start] values = [] seen = [False for vertex in range(len(self.adjacency_list))] while len(stack) > 0: current = stack.pop() if not seen[current]: # append actual vertex value to return at the end values.append(current) # remember visited vertices seen[current] = True # check adjacency list for connections if len(self.adjacency_list[current]) > 0: # we have to traverse the adjacency list from the end or reverse it # so the first connected vertex is the last added to the stack # in the next iteration, the first vertex from the adjacency list will be popped # this is necessary, otherwise the returned values list is in different order # compared to the one returned by the recursive method for vertex in reversed(self.adjacency_list[current]): # add all connected vertices, # but only if they were not visited yet if not seen[vertex]: # add to a stack stack.append(vertex) return values # O(v + e) time complexity (every node and every edge is visited) # O(n) space complexity # main driving method def dfs_traversal_recursive(self, start): if len(self.adjacency_list) > 0: values = [] seen = [False for vertex in range(len(self.adjacency_list))] return self.dfs_recursive(start, values, seen) # recursive traversal method def dfs_recursive(self, vertex, values, seen): # append actual vertex value to return at the end values.append(vertex) # remember visited vertices seen[vertex] = True for connected_vertex in self.adjacency_list[vertex]: # call itself on every not visited connected vertex if not seen[connected_vertex]: self.dfs_recursive(connected_vertex, values, seen) return values list_of_connections = [[1, 3], [0], [3, 8], [0, 2, 4, 5], [3, 6], [3], [4, 7], [6], [2]] graph = Graph(list_of_connections) print(f"Graph BFS: {graph.bfs_traversal(0)}") print(f"Graph DFS: {graph.dfs_traversal(0)}") print(f"Recursive DFS: {graph.dfs_traversal_recursive(0)}")
# https://leetcode.com/problems/binary-tree-right-side-view/ # Given the root of a binary tree, imagine yourself standing on the right side of it, # return the values of the nodes you can see ordered from top to bottom. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from collections import deque # Solution 1 - BFS # O(n) time complexity, O(n) space complexity class Solution(object): def rightSideView(self, root): """ :type root: TreeNode :rtype: List[int] """ if root is None: return [] queue = deque([]) queue.append(root) right_values = [] # We can use BFS # we store current level node values in a list # at the end of the level we can identify the rightmost item of the level (the last item in the list) while len(queue) > 0: current_level = [] level_length = len(queue) counter = 0 # current level consists of nodes, that are already in the queue at this point # we have to count how many times we pop the queue # to make sure we don't start to iterate over child nodes from the next level (the ones added in this loop) while counter < level_length: current_node = queue.popleft() # append value to the current_level current_level.append(current_node.val) # add child nodes to the queue # we will iterate over the child nodes only in the next iteration of the main loop if current_node.left is not None: queue.append(current_node.left) if current_node.right is not None: queue.append(current_node.right) # increment counter counter += 1 # append the last item from current_level to levels right_values list right_values.append(current_level[-1]) return right_values # Solution 2 - DFS # O(n) time complexity, O(n) space complexity class Solution2(object): def rightSideView(self, root): """ :type root: TreeNode :rtype: List[int] """ if root is None: return [] # keep the rightmost values in the list right_values = [] # call recursive DFS self.dfs_preorder(root, 0, right_values) return right_values # DFS - Depth First Search - Preorder def dfs_preorder(self, current_node, level, right_values): # basecase if current_node is None: return # append values only if the current level is higher than any previous one (length of right_values) if level >= len(right_values): right_values.append(current_node.val) # traverse right if current_node.right is not None: self.dfs_preorder(current_node.right, level + 1, right_values) # traverse left if current_node.left is not None: self.dfs_preorder(current_node.left, level + 1, right_values)
__author__ = 'Ciaran' import random def generateWord(): list_of_words = ["python", "jumble", "easy", "difficult", "answer", "xylophone"] randomWord = random.choice(list_of_words) #print(word) return randomWord def showBlank(randomWord): blankWord = len(randomWord) * "*" print(blankWord) # def printCurrentLives(currentLives): # while currentLives > 0: # print(currentLives) def guessLetter(): letter = input("Guess a letter: ") return letter def replaceLetter(letter, randomWord, blankWord): index = randomWord.find(letter) blankWord = blankWord[:index] + letter + blankWord[index+1:] print(blankWord) return blankWord def checkLetter(letter, randomWord): #returns true if letter is in word otherwise return false for i in range(len(randomWord)): if randomWord[i] == letter: correct = True else: correct = False return correct def main(): randomWord = generateWord() currentLives = 10 blankWord = showBlank(randomWord) while currentLives > 0: letter = guessLetter() guess = checkLetter(letter, randomWord) if guess: replaceLetter(letter, randomWord, blankWord) else: currentLives = currentLives - 1 print(blankWord) print(currentLives) main()
a = float(input('Podaj liczbę:')) wynik = a == 7 or ( a % 2 == 0 and a % 3 == 0 and a > 10 ) print(f"Liczba jest podzielna przez 2 i 3, większa od 10 lub równa 7: {wynik}")
napis = input("Podaj napis z jednym nawiasem <>: ") for litera in napis: if litera == "<": # print(napis.index(litera)) x = napis.index(litera) elif litera == ">": y = napis.index(litera) print(f" Ilość znaków w nawiasie wynosi: {y - x - 1}") # inne rozwiazanie licznik = 0 czy_zliczac = False for i in napis: if i == "<": czy_zliczac = True elif i == ">": czy_zliczac = False elif czy_zliczac: licznik += 1 print(f" Ilość znaków w nawiasie wynosi: {licznik}")
class Vector: def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return f"Wektor: {self.x}, {self.y}" def __add__(self, other): nowy_x = self.x + other.x nowy_y = self.y + other.y return Vector(nowy_x, nowy_y) v1 = Vector(1,3) v2 = Vector(4,4) print(v1) print(v2) v3 = v1 + v2 print(v3) v2 += v1 print(v2)
#program do liczenia objętości pudła i sprawdzić czy jest większa od 1 litra a = float(input('Podaj wymiar podstawy a w cm')) b = float(input('Podaj wymiar podstawy b w cm')) h = float(input('Podaj wymiar wysokości h w cm')) V = a * b * h print(f"Objęstość pudła jest: {V} cm3 i jest większa od 1 litra: {V>1000}") if V > 2000: print(f"Objętość większa niż 2l") elif V > 1000: print(f"Objętość większa niż 1l") else: print(f"Objętość mniejsza lub równa 1l") a = 0 if a: print(f"Sprawdzenie a")
# while inicializado en True y se sale con break while True: n=int(input("Ingrese numero entre 100 y 200: ")) if 100<=n<=200: # if n>=100 and n<=200 break else: print("Fuera de Rango!!!") if n%2==0: print(f"{n} es par") else: print(f"{n} es impar")
''' Calcular la potencia de un numero usando ciclos (no podra usar el operador aritmetico **), para ellos, el sistema solicitará por pantalla el valor de la base y el valor del exponente (ejemplo, base=4, exponente=2, entonces el resultado será 16), una vez realizado el calculo se mostrara el resultado por una salida por pantalla mostrando la informacion de la siguiente manera: "El resultado de la potencia de base 4 y exponente 2 es 16" ''' # Las potencia es el numero base multiplicado por el exponente esa cantidad de veces por si mismo. # Por ejemplo base 3 exponente 4, es 3*3*3*3 lo que da 81 # Solicitamos los dos numeros y validamos while True: try: base=int(input("Ingresar número base (Mayor a Cero): ")) exponente=int(input("Ingresar número exponente (Mayor a Cero): ")) if base>0 and exponente>0: break except: print("Ingrese solo números.") # Realizamos el calculo de la potencia potencia=1 for i in range(exponente): potencia*=base # potencia = potencia * base print(f"El resultado de la potencia de base {base} y exponente {exponente} es {potencia}")
# Enunciado 5 # Diego Sobarzo Licandeo # PGY1121_004V def funcion(): primerNumero = float(input("Introduce un primer número: ")) segundoNumero = float(input("Introduce un segundo número: ")) if primerNumero > segundoNumero: return 1 elif primerNumero < segundoNumero: return -1 else: return 0 programa = funcion() print(f"Valor devuelto: {programa}")
import pygame from Hero import HERO pygame.init() # ----- these varaibles will be used to create the menu as well as the light version of the game ------ # WHITE = (255,255,255) GREY = (70,70,70) LRED = (189,147,216) RED = (180,122,234) LGREEN = (49,203,0) GREEN = (17,152,34) LBLUE = (123,205,186) BLUE = (113,169,247) BLACK = (0,0,0) SCREENWIDTH = 800 #screen width SCREENHEIGHT = 600 #screen height clock = pygame.time.Clock() size = (SCREENWIDTH,SCREENHEIGHT) screen = pygame.display.set_mode(size) #creates the canvase/screen pygame.display.set_caption("GUI") #caption # ------------ this function is where the buttons will do their stuff --------- # def Button(msg,x,y,w,h,col1,col2,action = None): mouse = pygame.mouse.get_pos() #tracks mouses position click = pygame.mouse.get_pressed() #checks if mouse has been clicked if x < mouse[0] < x+w and y < mouse[1] < y+h and click[0] == 1: #this checks if the mouse is in the perameters of the green button and has been pressed pygame.draw.rect(screen,BLACK,(x,y,w,h)) #then turns the button black if click[0] == 1 and action != None: #this checks if the button has a specified action with its pressing action() #then executes said command elif x < mouse[0] < x+w and y < mouse[1] < y+h: #this checks to see if the mouse is in the perameters of the button pygame.draw.rect(screen,col2,(x,y,w,h)) #then changes the colour to a darker shade else: #if none of the above are true pygame.draw.rect(screen,col1,(x,y,w,h)) #the button will be there but in a lighter state font = pygame.font.SysFont("comicsansms",20) #this defines the font of the button text text = font.render(msg,1,(0,0,0)) #this creats the message and it's colour textrect = text.get_rect() textrect.center = (x + (w/2),y + (h/2)) screen.blit(text,textrect) # ----------- this concludes the section of code for the buttons ------------ # # ----------- This section of code will be for the setting menu ------------- # def Setting(): setting = True while setting: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type==pygame.KEYDOWN: if event.key==pygame.K_ESCAPE: #if the escape button is pressed setting = False #leave the settings menu # ------ visible things go here ------- # screen.fill(WHITE) fontS = pygame.font.Font(None,35) #defines the font textS = fontS.render("SETTINGS",1,BLACK) #renders the text TextSRect = textS.get_rect() #creates the text into an object TextSRect.center = (SCREENWIDTH/2,SCREENHEIGHT/5) #centers the text screen.blit(textS,TextSRect) #print the setting title pygame.display.flip() clock.tick(60) # ---------- this concludes the section for the settings menu ----------- # # ---------- this section of code will create and maintain the load screen ---------- # def Load(): load = True while load: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.KEYDOWN: if event.key==pygame.K_ESCAPE: #if the escape button is pressed load = False #leave the load file screen # ------ visible things will go here ------ # screen.fill(WHITE) fontL = pygame.font.Font(None,35) #defines the font textL = fontL.render("Load Saved File",1,BLACK) #renders the text TextLRect = textL.get_rect() #creates the text into an object TextLRect.center = (SCREENWIDTH/2,SCREENHEIGHT/5) #centers the text screen.blit(textL,TextLRect) #print the Load title pygame.display.update() clock.tick(60) # ---------- this concludes the code that is for the Load file screen ------------# # ---------- this long ass code thing will be the test demo for a game that will incorperate the things i want into my summative ------------- # def Game(): Sart = True while Sart: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.Quit() elif event.type==pygame.KEYDOWN: if event.key==pygame.K_x: pygame.quit() # -------- visible items --------- # screen.fill(GREY) pygame.display.update() clock.tick(60) # ----------- and this is the end of it ----------------------- # # ---------- this code will be for the starting menu ---------------- # menu = True while menu: #this is the menu loop for event in pygame.event.get(): #for every event that happens if event.type == pygame.QUIT: #if red box in the corner is pressed pygame.quit() #code closses elif event.type==pygame.KEYDOWN: if event.key==pygame.K_ESCAPE: menu = False # ------- draw code goes after here ------- # screen.fill(WHITE) #title font fontm = pygame.font.Font(None,35) #defines the font textm = fontm.render("TITLE",1,BLACK) #renders the text TextRect = textm.get_rect() #creates the text into an object TextRect.center = (SCREENWIDTH/2,SCREENHEIGHT/5) #centers the text screen.blit(textm,TextRect) #print the title Button("Start",SCREENWIDTH/2-50,SCREENHEIGHT/3,100,50,RED,LRED,Game) #green button that will start the quick demo Button("Load",SCREENWIDTH/2-50,SCREENHEIGHT/3+150,100,50,GREEN,LGREEN,Load) #red button taht brings to load file menu Button("Settings",SCREENWIDTH/2-50,SCREENHEIGHT/3+300,100,50,BLUE,LBLUE,Setting) #blue button that brings to settings menu Button("ESC",10,10,100,50,WHITE,GREY,pygame.quit) #white button that quits the game pygame.display.flip() clock.tick(60) # ----------- This concludes the section of the main menu code ----------- # pygame.quit()
import json import math input_x = int(input("Enter origin X coordinate: ")) input_y = int(input("Enter origin Y coordinate: ")) def sortfunction(c): x = int(c["value"].split(",")[0]) y = int(c["value"].split(",")[1]) return math.sqrt(math.pow(x-input_x, 2) + math.pow(y-input_y, 2)) def getClosestCoordinatesFromFile(): with open('coordinates.json', 'r') as f: array = json.load(f) array.sort(key=sortfunction) return array print(getClosestCoordinatesFromFile())
def is_prime(x): hits=0 for i in range(1,x+1): if x % i == 0: hits += 1 if hits == 2: return True else: return False
from random import randrange random_number = randrange(1, 10) count = 0 # Start your game! while (count<3): guess = int(raw_input("Enter Guess:")) count += 1 if (guess == random_number): print "You win!" break else: print "You lose"
# -*- coding: utf-8 -*- """ Problem 6 - Sum square difference Created on Thu Jan 15 00:16:07 2015 @author: Richard Decal, [email protected] """ x = sum(range(1,101)) ** 2 - sum([x**2 for x in range(1,101)]) print x
for i in range(1, 5): for j in range(1, 5): for n in range(1, 5): if i != j != n: print(i, j, n)
a = 'hello,world' b = 1.414 c = (1 != 2) d = (True and False) e = (True or False) print("a:%s;b:%.2f;c:%s;d:%s;e:%s" %(a, b, c, d, e)) print("\\\"hello,world\"")
coins = [1, 2, 5] combos = [1] + [0] * 11 for coin in coins: print('coin ', coin) for i in range(coin, 12): print('coin:' , coin, ' i:', i, ' i-coin:', i-coin) combos[i] += combos[i-coin] print('combos ', combos) def all_coin_change_combinations(amount_to_divide, coin_array): combos = [1] + [0] * amount_to_divide for coin in coin_array for i in range(coin, amount_to_divide+1): combos[i] += combos[i-coin] return combos[amount_to_divide] arr = [1,4,0,5,-3,20,-1,6,12,-10,4,1,1,1,8,10,12,9,5,1] #max non-adjacent subset of an array def max_subset_sum(arr): n = len(arr) back_2 = arr[0] back_1 = max(arr[0],arr[1]) for i in range(2,n): val = arr[i] new_max = max(val, back_1, val + back_2) back_2 = back_1 back_1 = new_max return back_1
def percent_method(string): print("This prints your string - %s - using the percentage method." % string) def format_method(string): print("This prints your string - {} - using the .format method.".format(string)) def f_method(string): print(f"This prints your string - {string} - using the f-string method.") def f_method_with_dictionary(dictionary): #for kwarg in kwargs: #print(kwarg, kwargs[kwarg]) print(f"The user {dictionary['user']}'s status is {dictionary['status']}") john = {'user': 'John', 'status': 'Active'} #split string over multiple lines s1 = "This is a string separated " \ "by a forward slash" s2 = """This is a multiline string contained within triple quotes which allows for many consecutive lines""" if __name__ == "__main__": string = input('Enter a string: ') percent_method(string) format_method(string) f_method(string) f_method_with_dictionary(john)
def enumerate_inputs(data): enumerated = enumerate(data) print('Printing enumerated items...') for item in enumerated: print(item) def zip_two_inputs(iterable1, iterable2): zipped = zip(iterable1, iterable2) print('Printing zipped items...') for item in zipped: print(item) def find_locations_of_value(arr, value): locations = [] for i, j in enumerate(arr): if j == value: locations.append(i) if __name__ == "__main__": print('Zip and enumerate functions are ready') arr1 = ['a','b','c','d','e'] arr2 = ['alpha','beta', 'gamma', 'delta', 'epsilon'] print('list 1 (variable name arr1): ', arr1) print('list 2 (variable name arr2): ', arr2) enumerate_inputs(arr1) zip_two_inputs(arr1,arr2)
from collections import deque from queue import PriorityQueue # hash map representation of a graph problem test_graph = { "A": {"B": 2, "C": 5}, "B": {"D": 7, "C": 5}, "C": {"D": 2, "E": 4}, "D": {"F": 1}, "E": {"D": 6, "F": 3}, "F": {} } costs = { "A": 0, "B": float("inf"), "C": float("inf"), "D": float("inf"), "E": float("inf"), "F": float("inf") } parents = { "A": None, "B": None, "C": None, "D": None, "E": None, "F": None } processed = [] def dijkstra(g: dict, c: dict, pa: dict, pr: list, start, end): current_key = start # set current key as start key while current_key is not end: # loop while current node key is not last node for child_key in g[current_key].keys(): # loop on current parent neighbours path_cost = c[current_key] + g[current_key][child_key] # parent weight + edge if c[child_key] > path_cost and child_key not in pr: # if path cost > current cost of node update c[child_key] = path_cost # update cost of selected neighbour pa[child_key] = current_key # update parent pr.append(current_key) # mark node as processed # Find cheapest next not processed node key by using min element algorithm cheapest_weight = float("inf") cheapest_key = None for node_key in c.keys(): if c[node_key] < cheapest_weight and node_key not in pr: cheapest_weight = c[node_key] cheapest_key = node_key current_key = cheapest_key return pa, c[end] def dijkstra_pq(g: dict, source, target): # initialize dist: dict = {source: 0} prev = {} pq = PriorityQueue() pq.put((0, source)) # populate distance list for node_key in test_graph.keys(): if node_key != source: dist[node_key] = float('inf') # while queue is not empty while pq.queue: node_dist, node_key = pq.get() # priority pop least distance node neighbours = test_graph[node_key] # get neighbour nodes if node_dist > dist[node_key]: # if distance of node popped greater that that saved reset loop continue for neighbour_key in neighbours: # loop on neighbour nods and update their costs alt = dist[node_key] + g[node_key][neighbour_key] if alt < dist[neighbour_key]: dist[neighbour_key] = alt prev[neighbour_key] = node_key pq.put((alt, neighbour_key)) return prev, dist[target] def print_path(pa: dict, start, end): path = deque() current = end while current != start: path.appendleft(current) current = pa[current] print(start) for n in path: print(n) return print_path(dijkstra_pq(test_graph, "A", "F")[0], "A", "F") # print_path(dijkstra(test_graph, costs, parents, processed, "A", "F")[0], "A", "F")
dic={ "I":1 , "V":5 , "X":10 , "L":50 , " C":100 , "D":500 , "M":1000 } def roman2int(roman ): inty=[dic [liczba] for liczba in list(roman )] last = inty[0] i=1; while i< (len(inty)): if last < inty[i]: inty[i-1]=- inty[i-1] if(i<len(inty)): last=inty[i-1] i = i + 1 return sum(inty) x = raw_input("liczba rzymska do zamiany na int:?(duze litery) " ) print roman2int(x)
class Queue: def __init__(self): self.items = [] def __str__(self): # podgladanie kolejki return str(self.items) def is_empty(self): return not self.items def is_full(self): # nigdy nie jest pusta return False def put(self, data): if self.is_full(): raise ValueError("kolejka pelna") else: self.items.append(data) def get(self): if self.is_empty(): raise ValueError("kolejka pusta") else: return self.items.pop(0) # malo wydajne! #===================test==================================== print 'start' q = Queue() print 'empty(): ' + repr(q.is_empty()) print 'full(): ' + repr(q.is_full()) q.put(1) q.put(2) q.put(3) q.put(4) print q.get() print q.get() print q.get() print q.get() print 'empty(): ' + repr(q.is_empty()) print 'full(): ' + repr(q.is_full()) print 'koniec'
#mamy a * x + b * y + c = 0 #przedstawia ono linie prosta o parametrach a,b,c #upraszczam problem: #algorytm szukania miejsca zerowego prostej y = a*x + b #gdzie mamy zadane a i b: def solve1(a, b): """Rozwiazywanie rownania liniowego y = a*x + b .""" if a==0: if b==0: print 'rownanie ma nieskonczenie wiele rozwiazan' return else: print 'rownanie sprzeczne' return else: x = float(-b)/float(a) print 'rozwiazanie rownania: x = ' , x return solve1(2,3) solve1(15,5) solve1(0,2) solve1(0,0) # uzylem schematu blokowego algorytmu z ponizszej strony # http://alg24.com/images/Algorytmy/alg_rownlin.png
#================================================================= class Stack: def __init__(self, size=10): self.items = size * [None] # utworzenie tablicy self.n = 0 # liczba elementow na stosie self.size = size def is_empty(self): return self.n == 0 def is_full(self): return self.size == self.n def push(self, data): if self.is_full(): raise ValueError("stos pelny") else: self.items[self.n] = data self.n = self.n + 1 def pop(self): if self.is_empty(): raise ValueError("stos pusty") else: self.n = self.n - 1 data = self.items[self.n] self.items[self.n] = None # usuwam referencje return data #================================================================= #kod testujacy: print 'start' stack = Stack(3) stack.push(1) stack.push(2) stack.push(3) print 'czy pusty? ' + repr(stack.is_empty()) print 'czy pelny? ' + repr(stack.is_full()) #stack.push(4) - wyrzuci ValueError print stack.pop() print stack.pop() print stack.pop() #print stack.pop() - wyrzuci ValueError print 'czy pusty? ' + repr(stack.is_empty()) print 'czy pelny? ' + repr(stack.is_full())
# # @lc app=leetcode.cn id=1207 lang=python3 # # [1207] 独一无二的出现次数 # # https://leetcode-cn.com/problems/unique-number-of-occurrences/description/ # # algorithms # Easy (66.73%) # Likes: 25 # Dislikes: 0 # Total Accepted: 9.2K # Total Submissions: 13.4K # Testcase Example: '[1,2,2,1,1,3]' # # 给你一个整数数组 arr,请你帮忙统计数组中每个数的出现次数。 # # 如果每个数的出现次数都是独一无二的,就返回 true;否则返回 false。 # # # # 示例 1: # # 输入:arr = [1,2,2,1,1,3] # 输出:true # 解释:在该数组中,1 出现了 3 次,2 出现了 2 次,3 只出现了 1 次。没有两个数的出现次数相同。 # # 示例 2: # # 输入:arr = [1,2] # 输出:false # # # 示例 3: # # 输入:arr = [-3,0,1,-3,1,1,1,-3,10,0] # 输出:true # # # # # 提示: # # # 1 <= arr.length <= 1000 # -1000 <= arr[i] <= 1000 # # # from typing import List # @lc code=start class Solution: def uniqueOccurrences(self, arr: List[int]) -> bool: from collections import Counter count = Counter(arr) occurs = count.values() return len(occurs) == len(set(occurs)) # @lc code=end
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ # 比较蠢的方法: import copy def is_palindromic(num): tmp=list(repr(num)) tmp_reverse=copy.copy(tmp) tmp_reverse.reverse() if tmp==tmp_reverse: return(True) return(False) states=True def largest_palindrom(): results=[] for i in range(999,99,-1): for j in range(i,99,-1): num=i*j if is_palindromic(num): results.append(num) return(max(results)) # 简洁: max([x*y for x in range(900,1000) for y in range(900,1000) if str(x*y)==str(x*y)[::-1]])
# # @lc app=leetcode.cn id=69 lang=python3 # # [69] x 的平方根 # # https://leetcode-cn.com/problems/sqrtx/description/ # # algorithms # Easy (37.24%) # Likes: 274 # Dislikes: 0 # Total Accepted: 80K # Total Submissions: 214.7K # Testcase Example: '4' # # 实现 int sqrt(int x) 函数。 # # 计算并返回 x 的平方根,其中 x 是非负整数。 # # 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 # # 示例 1: # # 输入: 4 # 输出: 2 # # # 示例 2: # # 输入: 8 # 输出: 2 # 说明: 8 的平方根是 2.82842..., # 由于返回类型是整数,小数部分将被舍去。 # # # # @lc code=start class Solution: def mySqrt(self, x: int) -> int: # TODO: 1. 牛顿迭代法 if x < 2: return x x0 = x x1 = (x0 + x / x0) / 2 while abs(x1 - x0) >= 1: x0 = x1 x1 = (x1 + x / x0) / 2 return int(x1) def mySqrt2(self, x: int) -> int: # 2. 二分查找 if x == 0: return 0 l, r = 1, x // 2 while l < r: mid = (l + r + 1) / 2 square = mid * mid if square > x: r = mid - 1 else: l = mid return l # @lc code=end
# # @lc app=leetcode.cn id=844 lang=python3 # # [844] 比较含退格的字符串 # # https://leetcode-cn.com/problems/backspace-string-compare/description/ # # algorithms # Easy (49.30%) # Likes: 96 # Dislikes: 0 # Total Accepted: 16.8K # Total Submissions: 33.5K # Testcase Example: '"ab#c"\n"ad#c"' # # 给定 S 和 T 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 # 代表退格字符。 # # # # 示例 1: # # 输入:S = "ab#c", T = "ad#c" # 输出:true # 解释:S 和 T 都会变成 “ac”。 # # # 示例 2: # # 输入:S = "ab##", T = "c#d#" # 输出:true # 解释:S 和 T 都会变成 “”。 # # # 示例 3: # # 输入:S = "a##c", T = "#a#c" # 输出:true # 解释:S 和 T 都会变成 “c”。 # # # 示例 4: # # 输入:S = "a#c", T = "b" # 输出:false # 解释:S 会变成 “c”,但 T 仍然是 “b”。 # # # # 提示: # # # 1 <= S.length <= 200 # 1 <= T.length <= 200 # S 和 T 只含有小写字母以及字符 '#'。 # # # # # # @lc code=start class Solution: def backspaceCompare(self, S: str, T: str) -> bool: stack_S = [] stack_T = [] for char in S: if char != '#': stack_S.append(char) elif stack_S: stack_S.pop() for char in T: if char != '#': stack_T.append(char) elif stack_T: stack_T.pop() return stack_S == stack_T # @lc code=end
# # @lc app=leetcode.cn id=24 lang=python3 # # [24] 两两交换链表中的节点 # # https://leetcode-cn.com/problems/swap-nodes-in-pairs/description/ # # algorithms # Medium (63.21%) # Likes: 353 # Dislikes: 0 # Total Accepted: 56.6K # Total Submissions: 89.6K # Testcase Example: '[1,2,3,4]' # # 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 # # 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 # # # # 示例: # # 给定 1->2->3->4, 你应该返回 2->1->4->3. # # # class ListNode: def __init__(self, x): self.val = x self.next = None def __str__(self): s = f'{self.val}' tmp = self.next while tmp is not None: s += f'-->{tmp.val}' tmp = tmp.next return s + '-->NULL' # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def swapPairs_1(self, head: ListNode) -> ListNode: """ 1. 递归解法 """ if not (head and head.next): return head next = head.next head.next = self.swapPairs(next.next) next.next = head return next def swapPairs(self, head: ListNode) -> ListNode: """ 2. 递推解法:多个节点 prev、a1、a2、next 的交替操作; 难点:要返回处理后链表的 首节点 --> 设置一个 dummy 节点!! """ prev = dummy = ListNode(None) prev.next = head while prev.next and prev.next.next: a1 = prev.next a2 = a1.next a1.next = a2.next a2.next = a1 prev.next = a2 prev = a1 return dummy.next # @lc code=end nodes = [ListNode(i) for i in range(1, 6)] for i in range(len(nodes) - 1): nodes[i].next = nodes[i + 1] head = nodes[0] Solution().swapPairs(head)
# # @lc app=leetcode.cn id=25 lang=python3 # # [25] K 个一组翻转链表 # # https://leetcode-cn.com/problems/reverse-nodes-in-k-group/description/ # # algorithms # Hard (55.24%) # Likes: 320 # Dislikes: 0 # Total Accepted: 29.9K # Total Submissions: 54.2K # Testcase Example: '[1,2,3,4,5]\n2' # # 给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。 # # k 是一个正整数,它的值小于或等于链表的长度。 # # 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。 # # 示例 : # # 给定这个链表:1->2->3->4->5 # # 当 k = 2 时,应当返回: 2->1->4->3->5 # # 当 k = 3 时,应当返回: 3->2->1->4->5 # # 说明 : # # # 你的算法只能使用常数的额外空间。 # 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 # # # class ListNode: def __init__(self, x): self.val = x self.next = None def __str__(self): s = f'{self.val}' tmp = self.next while tmp is not None: s += f'-->{tmp.val}' tmp = tmp.next return s + '-->NULL' # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseKGroup_1(self, head: ListNode, k: int) -> ListNode: """ KEY: 1. 尾插法 """ dummy = ListNode(0) dummy.next = head pre = dummy tail = dummy while True: count = k while count and tail: count -= 1 tail = tail.next if not tail: break head = pre.next while pre.next != tail: cur = pre.next pre.next = cur.next cur.next = tail.next tail.next = cur pre = head tail = head return dummy.next def reverseKGroup(self, head: ListNode, k: int) -> ListNode: """ 2. 转换成节点列表,会消耗 O(N) 的空间 """ if not head: return head nodes = [] while head: nodes.append(head) head = head.next for i in range(0, len(nodes), k): if i + k <= len(nodes): nodes[i:i + k] = nodes[i:i + k][::-1] for i in range(len(nodes)): if i == len(nodes) - 1: nodes[i].next = None else: nodes[i].next = nodes[i + 1] return nodes[0] def reverseKGroup_2(self, head: ListNode, k: int) -> ListNode: """ 3. 利用栈保存连续的 k 个节点,而不是保存所有节点 """ dummy = ListNode(None) dummy.next = head prev = dummy while True: stack = [] count = k start = prev.next while count and start: count -= 1 stack.append(start) start = start.next if count: break while stack: prev.next = stack.pop() prev = prev.next prev.next = start return dummy.next # @lc code=end
# # @lc app=leetcode.cn id=214 lang=python3 # # [214] 最短回文串 # # https://leetcode-cn.com/problems/shortest-palindrome/description/ # # algorithms # Hard (30.91%) # Likes: 109 # Dislikes: 0 # Total Accepted: 5.5K # Total Submissions: 17.6K # Testcase Example: '"aacecaaa"' # # 给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。 # # 示例 1: # # 输入: "aacecaaa" # 输出: "aaacecaaa" # # # 示例 2: # # 输入: "abcd" # 输出: "dcbabcd" # # # @lc code=start class Solution: def shortestPalindrome_1(self, s: str) -> str: # 1. 暴力法 :先求出从头开始的最长子串 # 判断是否回文:sub[::-1] == sub for i in range(len(s), -1, -1): sub = s[:i] if sub[::-1] == sub: break return s[i:][::-1] + s def shortestPalindrome(self, s: str) -> str: # TODO: 2. KMP(Knuth–Morris–Pratt) def compute_table(p): table = [0] * len(p) i = 1 j = 0 while i < len(p): if p[i] == p[j]: j += 1 table[i] = j i += 1 else: if j > 0: j = table[j - 1] else: i += 1 j = 0 return table table = compute_table(s + "#" + s[::-1]) return s[table[-1]:][::-1] + s # @lc code=end
# # @lc app=leetcode.cn id=409 lang=python3 # # [409] 最长回文串 # # https://leetcode-cn.com/problems/longest-palindrome/description/ # # algorithms # Easy (50.96%) # Likes: 101 # Dislikes: 0 # Total Accepted: 16.2K # Total Submissions: 31.2K # Testcase Example: '"abccccdd"' # # 给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。 # # 在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。 # # 注意: # 假设字符串的长度不会超过 1010。 # # 示例 1: # # # 输入: # "abccccdd" # # 输出: # 7 # # 解释: # 我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。 # # # # @lc code=start class Solution: def longestPalindrome(self, s: str) -> int: from collections import Counter counts = Counter(s) res = 0 i = 0 for num in counts.values(): if num % 2: i = 1 res += num - 1 else: res += num return res + i # @lc code=end
# # @lc app=leetcode.cn id=92 lang=python3 # # [92] 反转链表 II # # https://leetcode-cn.com/problems/reverse-linked-list-ii/description/ # # algorithms # Medium (48.10%) # Likes: 308 # Dislikes: 0 # Total Accepted: 35.5K # Total Submissions: 72.2K # Testcase Example: '[1,2,3,4,5]\n2\n4' # # 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 # # 说明: # 1 ≤ m ≤ n ≤ 链表长度。 # # 示例: # # 输入: 1->2->3->4->5->NULL, m = 2, n = 4 # 输出: 1->4->3->2->5->NULL # # # @lc code=start # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseBetween_1(self, head: ListNode, m: int, n: int) -> ListNode: """ 1. 找到并记录第 m-1 和 第 n 个节点,然后开始逆转 """ dummy = ListNode(0) dummy.next = head cur = dummy i = 0 while True: if i == m - 1: prev = cur if i == n: last = cur p = prev.next prev.next = last end = last.next next = end while p != end: tmp = p.next p.next = next next = p p = tmp break cur = cur.next i += 1 return dummy.next def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: """ 2. 到 m 个节点,依次将后面节点插到前面 """ dummy = ListNode(0) dummy.next = head prev = dummy i = 0 while i < m - 1: prev = prev.next i += 1 end = prev.next while i < n-1: start = prev.next curr = end.next nxt = curr.next prev.next = curr end.next = nxt curr.next = start i += 1 return dummy.next # @lc code=end
# # @lc app=leetcode.cn id=1048 lang=python3 # # [1048] 最长字符串链 # # https://leetcode-cn.com/problems/longest-string-chain/description/ # # algorithms # Medium (37.62%) # Likes: 30 # Dislikes: 0 # Total Accepted: 3.2K # Total Submissions: 7.9K # Testcase Example: '["a","b","ba","bca","bda","bdca"]' # # 给出一个单词列表,其中每个单词都由小写英文字母组成。 # # 如果我们可以在 word1 的任何地方添加一个字母使其变成 word2,那么我们认为 word1 是 word2 的前身。例如,"abc" 是 # "abac" 的前身。 # # 词链是单词 [word_1, word_2, ..., word_k] 组成的序列,k >= 1,其中 word_1 是 word_2 # 的前身,word_2 是 word_3 的前身,依此类推。 # # 从给定单词列表 words 中选择单词组成词链,返回词链的最长可能长度。 # # # 示例: # # 输入:["a","b","ba","bca","bda","bdca"] # 输出:4 # 解释:最长单词链之一为 "a","ba","bda","bdca"。 # # # # # 提示: # # # 1 <= words.length <= 1000 # 1 <= words[i].length <= 16 # words[i] 仅由小写英文字母组成。 # # # # # from typing import List # @lc code=start class Solution: def longestStrChain(self, words: List[str]) -> int: words = sorted(words, key=len) def isNext(word1, word2): return len(word2) == len(word1) + 1 and all([char in set(word2) for char in word1]) dp = [1] * len(words) for i in range(1, len(words)): for j in range(i): if isNext(words[j], words[i]): dp[i] = max(dp[i], dp[j] + 1) print(dp) return max(dp) # @lc code=end words = [ "ksqvsyq", "ks", "kss", "czvh", "zczpzvdhx", "zczpzvh", "zczpzvhx", "zcpzvh", "zczvh", "gr", "grukmj", "ksqvsq", "gruj", "kssq", "ksqsq", "grukkmj", "grukj", "zczpzfvdhx", "gru" ] print(Solution().longestStrChain(words))
# # @lc app=leetcode.cn id=559 lang=python3 # # [559] N叉树的最大深度 # # https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/description/ # # algorithms # Easy (67.37%) # Likes: 73 # Dislikes: 0 # Total Accepted: 16.5K # Total Submissions: 24.3K # Testcase Example: '[1,null,3,2,4,null,5,6]\r' # # 给定一个 N 叉树,找到其最大深度。 # # 最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。 # # 例如,给定一个 3叉树 : # # # # # # # # 我们应返回其最大深度,3。 # # 说明: # # # 树的深度不会超过 1000。 # 树的节点总不会超过 5000。 # # # @lc code=start """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def maxDepth(self, root: 'Node') -> int: """ 1. 递归 """ if not root: return 0 elif not root.children: return 1 else: return 1 + max([self.maxDepth(child) for child in root.children]) # TODO:栈的解法 # @lc code=end
__author__ = 'yangbin1729' class Tree: # ------------------------------- nested Position class ------------------------------- class Position: def element(self): raise NotImplementedError('must be implemented by subclass') def __eq__(self, other): raise NotImplementedError('must be implemented by subclass') def __ne__(self, other): return not (self == other) # ---------- abstract methods that concrete subclass must support ---------- def root(self): raise NotImplementedError('must be implemented by subclass') def parent(self, p): raise NotImplementedError('must be implemented by subclass') def num_children(self, p): raise NotImplementedError('must be implemented by subclass') def children(self, p): raise NotImplementedError('must be implemented by subclass') def __len__(self): raise NotImplementedError('must be implemented by subclass') # ---------- concrete methods implemented in this class ---------- def is_root(self, p): return self.root() == p def is_leaf(self, p): return self.num_children(p) == 0 def is_empty(self): return len(self) == 0 def depth(self, p): if self.is_root(p): return 0 else: return 1 + self.depth(self.parent(p)) def _height1(self): # works, but O(n^2) worst-case time return max(self.depth(p) for p in self.positions() if self.is_leaf(p)) def _height2(self, p): # time is linear in size of subtree if self.is_leaf(p): return 0 else: return 1 + max(self._height2(c) for c in self.children(p)) def height(self, p=None): if p is None: p = self.root() return self._height2(p) # start _height2 recursion def __iter__(self): for p in self.positions(): # use same order as positions() yield p.element() # but yield each element def positions(self): return self.preorder() # return entire preorder iteration def preorder(self): if not self.is_empty(): for p in self._subtree_preorder(self.root()): # start recursion yield p def _subtree_preorder(self, p): yield p # visit p before its subtrees for c in self.children(p): # for each child c for other in self._subtree_preorder(c): # do preorder of c's subtree yield other # yielding each to our caller def postorder(self): if not self.is_empty(): for p in self._subtree_postorder(self.root()): # start recursion yield p def _subtree_postorder(self, p): for c in self.children(p): # for each child c for other in self._subtree_postorder(c): # do postorder of c's subtree yield other # yielding each to our caller yield p # visit p after its subtrees def breadthfirst(self): if not self.is_empty(): fringe = LinkedQueue() # known positions not yet yielded fringe.enqueue(self.root()) # starting with the root while not fringe.is_empty(): p = fringe.dequeue() # remove from front of the queue yield p # report this position for c in self.children(p): fringe.enqueue(c) # add children to back of queue
a=5 b=2 if(a<b): print (a) else: print (b)