text
stringlengths
37
1.41M
import re; import random; def removeExtraApostropheS(movie_title,tokenized_list): '''Function removes extra 's' appearing as word in the tokenized list''' original_words = len(movie_title.split()); # original words in the movie title - space separated tokenized_words = len(tokenized_list); # get the total words in the tokenized list if (original_words < tokenized_words): # the tokenized list contains extra words - lets check for 's words apos_s_pattern = re.compile("'s"); # regular expression for finding the 's in the movie title apos_s_words = len(apos_s_pattern.findall(movie_title)); # find all the occurrences of 's in the movie title if (apos_s_words > 0): for i in range(0,apos_s_words): tokenized_list.remove("s"); return tokenized_list; def debugger(msg): '''debugger prints the given debug msg on screen/in debug file log''' debugger_output = "con" if debugger_output == "con":#console print ("--> %s <--") % (msg) else: df = open(debugger_output,"a"); df.write(str(msg)); df.close(); #just a placeholder func def findinDatabase(word): '''finds a word in the database and returns True/False, action_seq_id and length of action_seq''' return (random.choice([True,False]),random.choice(range(0,10)),random.choice(range(9,15))) #simulate existence of a word in database #function ends here def error_logger(req,error): req.write("Error occured :"+ error); return True;
""" Scales are first-order functions that take an index as argument, and return the distance in semitones from the root. Modular arithmetic is used, so there is no limit to the index you may request. """ def chromatic(i): return i def major(i): j=i%7 k=i//7 scale = [0,2,4,5,7,9,11] return k*12 + scale[j] def minor(i): # natural minor j=i%7 k=i//7 scale = [0,2,3,5,7,8,10] return k*12 + scale[j] def harmonicMinor(i): j=i%7 k=i//7 scale = [0,2,3,5,7,8,11] return k*12 + scale[j] def hungarianMinor(i): j=i%7 k=i//7 scale = [0,2,3,6,7,8,11] return k*12 + scale[j] def majorPentatonic(i): j=i%5 k=i//5 scale = [0,2,4,7,9] return k*12 + scale[j] def minorPentatonic(i): j=i%5 k=i//5 scale = [0,3,5,7,10] return k*12 + scale[j] def diminished(i): j=i%8 k=i//8 scale = [0,2,3,5,6,8,9,11] return k*12 + scale[j]
#! /usr/bin/env python3 import numpy as np list1 = [] print("Enter the values") while 1: data=input() # for only integer data possible try: list1.append(int(data)) except: break size=len(list1) print(size) n1=size**.5 n2=np.ceil(n1) print(n2) for i in range(2,int(n2)+1): if (size%i)==0: flag=1 break else: flag=0 break if flag==0: data=input("Enter one more dimension") list1.append(int(data)) print("Values are:- ") for k in list1: print(k,end=" ") new_size=len(list1) z=int(new_size/2)+1 print() print("Possible Dimensions:- ") for x in range(2, z): if ((new_size%x)==0): q=(new_size/x) print(x,"*",int(q))
#not done. This needs a bit more work #only thing that needs to be done is to figure out matching and fix Clue's print function #this is a class to define a full puzzle. It's got a list of clues (which themselves # store their connections to other clues), a solve function, and a print function # so that basically all the main program has to do to execute is create a puzzle, # puzzle.readIn("puzzle.txt") puzzle.solve(), and puzzle.print() # can even skip a step and just put the reading in in the constructor # but if it's a command line arg anyway, no point in making it more difficult # See readme for puzzle.txt formatting #matching: The first way I'm thinking to do it is to work off of the one-PS clues. #ex. the only one that matched purple was chirp, and the only one that matched chirp was inch #the problem is, there has to be at least one clue that you can get without the connections #also, I should look into making that recursive in some way. #basically the move would be to just call solve on all the connections of the first clue that only had #one potential solution, mark the solved clues solved, and keep going until all the clues were solved. #this is where it turns into a graph traversal. #I think breadth-first works best here. Say purple has more than one connection: I'd want to whittle down the #list of potential solutions to things that match with purple before continuing on to that clue's other solutions. #what if there's more than one thing that works with purple? Then what? You'd go through that connections #potential solutions and its connections, so let's say chirp and xhirp work with purple. Xhirp wouldn't have any solutions with #the other connection, so it could be eliminated. I don't have to worry about there being multiple solutions if it's a valid puzzle #the thing is, I feel like that method's gotta work even if you don't start with a 1ps clue. If it recurses through, it should #go something like: 1's matches: inch -> chirp , inst -> spire. spiry ; unsolved. 2's matches to connection at 4: chirp -> purple. #chirp is the solution. is there any connected clue that's unsolved? Yes, 1. What matches with chirp? Inch, now it's solved. #come to think of it, this sounds like depth first search now that I talk it out. #let's say you whittle a clue down and it's still not solved because it needs it's other connections to solve it. #then what do you do? ex. say chirp and xhirp both worked with purple. Then you'd need to reverse whittle clue 2. #by reverse whittle I mean do the exact same thing, but instead of deleting the non-matching words from the connected clue and solving that, #you'd delete the words from the original clue's list, and then it would be solved. Then you could call whittle on the original and continue #execution as usual #something just dawned on me, if you start with a reverse whittle, you can get rid of the requirement that the puzzle #has to have one clue that can be solved without whittling. For example. You reverse whittle clue 1, it doesn't help you. Neither clue 1 nor clue 2 are solved #so you reverse whittle clue 2. That solves clue 2. (What if that doesn't solve clue 2?) So then you can call whittle on clue 2 and that solves clue 1 and clue 3. You now whittle clue 1, all its connections # are solved so it doesn't do anything and it finishes, and it 'solves' clue 3, calls whittle on it and the same thing happens, so it exits the recursion # and now the puzzle is solved, so you can print it. #what if that doesn't solve clue 2? Then you can potentially have an infinite loop on your hands if it then reverse whittles clue 1 again. #you have to 1. either call reverse whittle on another one of 2's connections 2. quit the branch execution and hope the program comes back to it when one of the clues is solved # #(which it should. if it doesn't, then you can always come back to it during the check at the end of solve) #but if it happens at the beginning of execution when there aren't any other branches, that wouldn't solve the puzzle. So I need to come up with the comprehensive solution for this #either way, should modify the function and call reverseWhittle with a calledFromReverseWhittle boolean #no so you still need a clue that can be solved by itself, because reverse whittling depends on the connections being solved, and only then can you #eliminate a potential solution based on a mismatch #speaking of, I need to find a good way to print it now that I don't have a solutionFirstHalf and solutionSecondHalf #I can just generate a solFirstHalf and secondHalf in the print function from the solution and print it from there #so the infinite loop problem only arises if a reverseWhittle called from a reverseWhittle doesn't solve the clue. When reverseWhittle calls reverseWhittle, it calles it on the #last connection. So the problem only arises if it's the last connection in both, they're both unsolved (obviously), and the answer can only be obtained by a single one of the two clues' connections #Solution: if a reverseWhittle is called from another reverseWhittle, and it doesn't solve the second clue, call reverse whittle on one of the other connections. #Can this problem be fixed by just calling it with the first connection? If the clue only has one connection then it can't not be solved by a reverse whittle -- unless the other clue isn't solved #new idea: if you try to reverse whittle something and it doesn't get solved, then you reverse whittle the connection and that does get solved, the original clue should get solved by reverse whittling. #So if something was already visited by reverse whittle, you shouldn't try reverse whittling it again. I think that's fine. I need to test it and see if I can improve this for the case where #the infinite loop happens too early in the execution. What's too early in the execution? #what if I keep track of the reverse whittling chain? So every time reverse whittle gets called from whittle(or the start), it gets called with a new chain. #if it's already been reverse whittled on the chain, quit execution because that's the indicator of an infinite loop #Plan 2.0: There's two ways to solve an infinite loop problem, and now that I think about it, there's two ways to solve any problem: #Deal with it, or avoid it. While it may not be the most sound life advice, I'm gonna go with the latter here, if only because it feels #a lot easier than the former, again, not unlike real life. I'm gonna do this really simply with two tactics: #1. When a reverse whittle that's called by a reverse whittle doesn't solve the problem (since this is an imperfect way to deal with the problem in general), #just terminate the execution thread. This is only a real problem if this happens in the beginning of the execution and the program doesn't have any 'loose ends', #or waiting-to-be-executed recursive calls in the stack. (It'll happen in the beginning of my test puzzle, and any other puzzle that doesn't start with a onePS) #2. This flaw is solved by starting execution somewhat similarly to originally thought out: Going through all the clues, marking the onePS's solved, and starting the whittling process from each. #This makes sure that in the case of a thread terminating, there will be plenty of other threads to approach the unsolved clue from every connection, as in a ~50 clue puzzle it can be expected that there are #well over 10 onePS's #it looks like it works, I just found a bug in my code, basically it can get into another loop when it can't solve something by reverse whittling, so it reverse whittles its last connection. #if the clue is already solved, it doesn't trigger the loop avoidance because its calling reverse whittle from whittle. An easy fix is just to check if you're reverse whittling something solved, then stop. #Now that this has basically just become the file where I write down whatever comes to mind about this program, #it's time to come up with some tests. If it's going to be something you showcase on your profile, it needs to be good code. #and all good code is tested properly. Remember, it's more important to do a good job than to work hard. #So. using unittest, you're going to test every case for every function in this program. # 1. block.print() - not really sure what to test for 2. block init -- what happens if it's called with weird inputs? Probably not good stuff #stuff to do before pushing this code: #1. test what happens if block is initialized wrong #2. test what happens if clue is initialized wrong #3. should probably add in command line argument for puzzle file. Don't want to have to mess with the source for each puzzle #4. also, try and figure out if there's a better way to input the puzzle, because right now it's brutal. The thing is, dealing #with images is hard, and not necessarily in the scope of this project. For now, just tell the user what they did wrong #Non-test stuff to write: #1. Add in command line arg for puzzle file #2. SD Readme detailing how to format puzzle file, what assumptions were made, etc #3. File IO isn't the only thing you have to do responsibly # --for a bunch of things, make sure the program exits gracefully, and tells the user what's wrong #Tests to write: #1. if run without command line arg for puzzle file, what do I want to happen? What happens? # --this is testing the main program execution #2. if a clue is formatted incorrectly, what happens? # --this is testing readIn #2a. There's probably going to be a bunch of variations on this, but the place to deal with it is going to be where I cast the data types # #3. now that I've given the user control over ID's, what if two clues have the same ID? # --this seems like a more sophisticated test #4. What if the connection I'm looking for doesn't exist? # --this is testing findSecondaryConnectionIndex #5. What happens if there's a 13+ letter clue? # --I just need to account for this in readIn #6. Is there a case where the solver fails to solve a solvable puzzle? # --I don't think so, I think my solve function is pretty comprehensive, it will eventually whittle or solve every clue #7. what if solve is called before readIn? # --I just need to check for this, maybe the simplest way is to add a bool in puzzle #8. what if whittle is called on an unsolved clue? # --Same thing, just need to check in the beginning #9. what if the connected clue I'm looking for doesn't exist? # --this is testing __findConnectedClue #10. Just while we're being thorough, I should test all the print functions
import pandas as pd import numpy as np import matplotlib.pyplot as plt from datetime import datetime birddata = pd.read_csv("bird_tracking.csv", index_col=0) #Exercise 1 # First, use `groupby()` to group the data by "bird_name". grouped_birds = birddata.groupby('bird_name') # Now calculate the mean of `speed_2d` using the `mean()` function. mean_speeds = grouped_birds['speed_2d'].mean() # Find the mean `altitude` for each bird. mean_altitudes = grouped_birds['altitude'].mean() #Exercise 2 # Convert birddata.date_time to the `pd.datetime` format. birddata.date_time = pd.to_datetime(birddata.date_time) # Create a new column of day of observation birddata["date"] = birddata['date_time'].dt.date # Use `groupby()` to group the data by date. grouped_bydates = birddata.groupby("date",group_keys=True) # Find the mean `altitude` for each date. mean_altitudes_perday = grouped_bydates["altitude"].mean() date = datetime.strptime("2013-09-12", "%Y-%m-%d").date() print(mean_altitudes_perday[date]) #Exercise 3 # Use `groupby()` to group the data by bird and date. grouped_birdday = birddata.groupby(['bird_name','date']) # Find the mean `altitude` for each bird and date. mean_altitudes_perday = grouped_birdday["altitude"].mean() name = "Eric" date = datetime.strptime("2013-08-18", "%Y-%m-%d").date() print(mean_altitudes_perday[name,date]) #Exercise 4 import matplotlib.pyplot as plt speed_2d = grouped_birdday["speed_2d"].mean() eric_daily_speed = speed_2d["Eric"] sanne_daily_speed = speed_2d["Sanne"] nico_daily_speed = speed_2d["Nico"] eric_daily_speed.plot(label="Eric") sanne_daily_speed.plot(label="Sanne") nico_daily_speed.plot(label="Nico") plt.legend(loc="upper left") plt.show()
def fibo(n): if n==0: print("Digit should be greater than 0.") elif n==1: return 0 elif n==2: return 1 else: return fibo(n-1)+fibo(n-2) n = int(input("Enter the digit upto which you want to find fibnacci series: ")) l = list() l=[str(fibo(i)) for i in range(1,n+1)] s = ",".join(l) print(s)
import player as P class Game: def __init__(self, numShips): """ Initializes the game :param numShips: The number of ships players start with """ self.win = False self.numShips = numShips; self.player1 = P.Player() self.player2 = P.Player() self.currentPlayer = self.player1 self.nextPlayer = self.player2 def advancePlayer(self): """ Changes who the current player is """ self.nextPlayer = self.currentPlayer if self.currentPlayer == self.player1: self.currentPlayer = self.player2 else: self.currentPlayer = self.player1 def turn(self, guess): """ Changes who's turn it is, calls advancePlayer to switch turns :param guess: The position a player has guessed """ self.currentPlayer.guess(guess, self.nextPlayer) self.advancePlayer() self.currentPlayer.removeSunkShips() if self.currentPlayer.numShips == 0: self.win = True def printWinner(self): """ Print's out the winner of the game """ if self.nextPlayer == self.player1: print("Player 1 Wins!") else: print("Player 2 Wins!")
message = "One of Python's" print(message) print(3 ** 2) # 创建列表 name = ['ricardo', 'bob', 'lucc'] print(name) # 向列表末尾添加数据 name.append('walter') print(name) # 向列表0位置增加数据 name.insert(0, 'nazz') print(name) # 删除一条数据 del name[0] print(name) # 删除末尾数据 name.pop() print(name) # 按值删除 name.remove('bob') # 临时排序 sorted print(sorted(name)) # 临时排序反序 print(sorted(name, reverse = True)) # 确定列表长度 print(len(name)) # 列表反转 name.reverse() print(name) # 永久性排序 sort name.sort() # print(name) # 永久性排序 倒叙 不能直接写在print里面 name.sort(reverse = True) print(name) for n in name: print(n) # 使用range函数 for value in range(1, 5): print(value) for value in range(1, 10, 2): print(value) num_list = list(range(1, 5, 2)) print(num_list) print(max(num_list)) min(num_list) sum(num_list) # 定义元祖 name_tuple = ('bob', 'walter') print(name_tuple) # name_tuple[0] = 'nazz' 错误 name_tuple = ('lucc') print(name_tuple)
# -*- coding: utf-8 -*- """ Created on Tue Nov 5 21:54:31 2019 Assignment 1 Prob 3 Fibonacci sequence @author: CHINTAN """ s=[1,1] for i in range(2,10): s.append(s[i-1]+s[i-2]) print(s)
import random moves = ["rock", "paper", "scissor"] keep_playing = True while keep_playing: cmove = random.choice(moves) pmove = input("You are about to start Rock, Paper and Scissor game. Please enter your input: ") if cmove == pmove: print('Tie') elif pmove == 'rock' and cmove == 'scissor': print("Player wins!!") elif pmove == 'scissor' and cmove == 'paper': print("Player wins!!") elif pmove == 'paper' and cmove == 'rock': print("Player wins!!") elif cmove == 'rock' and pmove == 'scissor': print("Computer wins!!") elif cmove == 'scissor' and pmove == 'paper': print("Computer wins!!") elif cmove == 'paper' and pmove == 'rock': print("Computer wins!!") else: print("Please enter a valid input next time!!") print(cmove, 'and ', pmove) option = print(input("Do you want to continue the game. If no, please enter N: ")) if option == 'N': keep_playing = False print('GoodBye!!') break else: print("Enter a valid input")
file='input.txt' fhand=open(file,"r") full_txt=fhand.read() words=full_txt.split() print(words) words.sort() print('Sorted list', words) print([ (i,words.count(i)) for i in set(words) ])
a=[5, 10, 15, 20, 25] l = len(a) print("The first element of the list is",a[0],"and the last element of the list is",a[l-1]) b=[a[0],a[l-1]] print("The new list is: ",b)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ answ, L = [], [root] while L and root: answ.insert(0, [n["val"] for n in L]) a = [] for node in L: print("N", node) for c in (node['left'], node["right"]): print('c', c) print('=' * 30) if c: a.append(c) L = a # L = [C for N in L for C in (N["left"], N["right"]) if C] return answ data = { "val": 3, "left": {"val": 9, "left": {"val": 4, "left": None, "right": None}, "right": None}, "right": { "val": 20, "left": {"val": 15, "left": None, "right": None}, "right": {"val": 7, "left": None, "right": None}, } } # print([i for a in [1, 2, 3] for i in [2, 3, 4]]) print(Solution().levelOrderBottom(data))
#Deleting different dictionary elements dict1={"student1":"madhuri","student2":"diya","student3":"karthik"} dict2={"id":int("234"),"roll":int("2"),"phoneno":int("1234567898")} dict3={"branch1":"ECE","branch2":"CSE","branch3":"IT"} #Deleting Specific element del dict1["student3"] dict2.pop("roll") print(dict1) print(dict2) #Deleting all elements del dict2 dict3.clear() print(dict2) print(dict3)
import sqlite3 with sqlite3.connect("blog_posts.db") as connection: c = connection.cursor() c.execute('DROP TABLE posts') c.execute('CREATE TABLE posts(title TEXT, description TEXT)') c.execute('INSERT INTO posts VALUES("Lorem Ispum", "Lorem Ipsum dolor sit amet."(') c.execute('INSERT INTO posts VALUES("Ice Cream", "I delicious.")') c.execute('INSERT INTO posts VALUES("pizza", "Mmmmm pizza.")') c.execute('INSERT INTO posts VALUES("Hello World", "My very first blog post!.")') print("Created Database!")
#!/usr/bin/env python import sys import os.path import os import csv import glob from pandas import DataFrame, Series import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model from sklearn.discriminant_analysis import LinearDiscriminantAnalysis import scipy.stats as stats import numpy.ma as ma # Here's a starter for the homework. You can call this file from them command # line with a file path as a command-line argument # As you complete the assignment, you can un-comment these lines to pull it all together # frame = read_all_files(sys.argv[1]) # num_iv_columns = len(frame.columns)-1 # training_class = categorical_transformation(frame) # classify(frame, num_iv_columns, training_class) # Building a Classification Tool # then choose and run a classification algorithm. It won't be that # statistically rigorous, but that's not our concern here. Instead, we'll # be building a clean piece of code that separates a number of different # pieces of functionality. # Copy this starter to a python executable named: classification.py. # Place all functions for in classification.py # The data files for this assignment are data_banknote_authorization.txt # and iris.csv and they are on Canvas. They are both publicly available as # documented here: # https://archive.ics.uci.edu/ml/datasets.html # 0. Reading in the Data. # Copy in the function read_all_files from Lecture 7 and modify it # so that it can either read a single data file OR read all of the files in # a directory. The function should still take in a single argument path # which can now be either the path to a file or the path to a directory. # The function's signature shoul be exactly: def read_all_files(path): files = dir_or_file(path) frames = [] for f in files: extension = os.path.splitext(f)[-1] file_reader = reader(extension) new_frame = file_reader(f) frames.append(new_frame) return pd.concat(frames, ignore_index = True) def dir_or_file(path): if os.path.isdir(path): if os.listdir(path): path = path + '/*' else: raise Exception ('Folder %s is empty' % path) elif os.path.isfile(path): path = path else: raise Exception (' %s is not a folder or file. Try another.' % path) files = glob.glob(path) return files def reader(extension): if extension == '.csv' or extension == '.txt': return csv_reader elif extension == '.json': return json_reader else: raise Exception('Reader for file type %s not found.' % extension) def json_reader(path): return pd.read_json(path, orient='records') def csv_reader(path): return pd.read_csv(path) # When reading files from a directory you can assume they are all the same # format and that there is no header. # Your function should return a single data frame containing all of the data. # Your function only needs to be able to read in CSV data. You can re-use # code from the Lecture and pair programming for this. Your function should # also be able to read files with the extension .txt as CSV files. You can # assume there is no header in the CSV data. # Your function should: # * Raise an exception if the given file type is not supported (i.e. is not CSV). # * Raise an exception if path is not a file or a directory. # * Raise an exception if path is an empty directory. # For all three of these exceptions, the value of path should appear in the # error message. # To test your function, you can read both of the test data sets individually. # You can also put a few copies of one of the datasets in a new directory. # --------------------------------------------------------------------------- # # To make things easier we're going to make some assumptions about our data # from here on: # 1. The class we have observed is always on the right hand side of the dataset. # It is the last column. # 2. All of the other columns are independent variables. All of those are # numeric and can be used in our classification. # e.g. for the row of data: # 3.6216,8.6661,-2.8073,-0.44699,0 # The last 0 is the class we have observed. All the other columns are # independent variables. # 1. Prepare your data frame. # In order to be able to use any data set on our classification algorithms, # we might need to do a lot of dataset preparation. We might want to make # sure that our independent variables are numeric or, if they are categorical, # handle them differently in some way. # On this assignment we're not going to go through all of these steps. # Instead, we'll just do one data cleaning step to show the idea. # In our Iris dataset, the classes are described by string values # (such as 'Iris-virginica'). It can often be easier for the classes to have # integer values, so let's create a new column in the data frame that is the # observed class, represented as an integer. #Write a function called (exactly): def categorical_tranformation(frame): frame['Class Integer']= pd.Categorical.from_array(frame.ix[:,-1]).codes return frame.ix[:,-1] # that takes a dataframe, frame and returns a new column that has been added # to that dataframe. # Assume that the observed class for each row is in the last column. Your # function should add a new column to the dataframe and the values of that # column should be an integer representation of the classes. In our Iris data, # there are three classes so for that dataset your dataframe should have a new # column with values 0, 1 or 2. In the banknote data, the values should be # binary. # Make sure that the mapping of string class names to integers is not # hard-coded, i.e. your function should work even if there were a new type of # Iris in the data. Your function should work if the classes are represented # by strings or integers. Your function should work whether the data is sorted # or not. # Your function should return the new column. # 2. Set up two different Estimators # Write two functions called (exactly): def classify_logistic (frame): log_estimator = linear_model.LinearRegression() return log_estimator def classify_lda(frame): LDA_estimator = LinearDiscriminantAnalysis() return LDA_estimator # Both functions should take a DataFrame, frame # The first function returns a sklearn Estmimator object for Logistic Regression. # The second function should return a sklearn Estimator object for LDA. # Note that this step does not require you to fit the data. # 3. Writing a function to choose an algorithm. # Choice of a classification algorithm should depend on many factors and a # practitioner would evaluate various attributes of the data to make that choice. # For this assignment we'll make a simple selection based on one property of LDA. # LDA assumes normality of the independent variables. # Write a function called (exactly): def algorithm_chooser(frame, num_ivs): for column in frame.ix[:,0:num_ivs]: #TODO fix header problem threshold = float(0.05) z, pval = stats.stats.normaltest(frame[column]) pval = np.float(pval) if (pval > threshold): return classify_logistic(frame) break else: return classify_lda(frame) # that takes a dataframe, frame and outputs the name of one of your two #classification functions from Section (2). # Your function should select logistic regression if any of the independent # variable columns are not normally distributed. If all columns are normally # distributed, it should select LDA. We'll assume that a variable is normally # distributed if its p-value is > 0.05. # Hint: The SciPy library has a stats package that may be useful in testing normality. # Note: It's not a requirement of this assignment but it's preferable to stop # checking the normality of columns as soon as you've found one that has # violated that assumption. You can use a break statement for this. # 4. Putting it all together. # Finally, let's fit the estimator. Write a function called (exactly): def classify(frame, num_ivs, training_class_series): my_estimator = algorithm_chooser(frame, num_ivs) my_estimator.fit(frame.ix[:,0:num_ivs], training_class_series) return my_estimator num_ivs = 4 frame = read_all_files(sys.argv[1]) # categorical_tranformation(frame) # classify_logistic (frame) # classify_lda(frame) # algorithm_chooser(frame, num_ivs) classify(read_all_files(sys.argv[1]),num_ivs, categorical_tranformation(frame)) # that takes a dataframe, frame, an integer num_ivs and a pandas Series # training_class_series. num_ivs is the number of independent variables and # training_class_series is the column of the dataframe that contains the # observed integer class values. # Your function should: # * Call the algorithm_chooser to choose a function # * Call the function returned by algorithm_chooser to create an Estimator # * Call the .fit function on the estimator based on the number of independent # variables and the observed class values # * Return the estimator # 5. Questions # In a comment block, write answers to the following questions: # (Put answers at the end of your .py file in comments) # a) Is your code maintainable? Why/give an example? # Yes, the categorical_tranformation function can categorize any independent variable string # for any column in the data just by changing the frame indexing. # b) Is your code extensible? Why/give an example? #Yes, we could easily create functions for different types of estimators. # c) Is your code reusable? Why/give an example? #Yes, the first five functions can take any .csv, .txt, or .json and return a pandas dataframe.
#多进程 """ Unix/Linux操作系统提供了一个fork()系统调用,它非常特殊。 普通的函数调用,调用一次,返回一次,但是fork()调用一次,返回两次, 因为操作系统自动把当前进程(称为父进程)复制了一份(称为子进程), 然后,分别在父进程和子进程内返回。 子进程永远返回0,而父进程返回子进程的ID。 这样做的理由是,一个父进程可以fork出很多子进程,所以,父进程要记下每个子进程的ID, 而子进程只需要调用getppid()就可以拿到父进程的ID。 Python的os模块封装了常见的系统调用,其中就包括fork,可以在Python程序中轻松创建子进程 """ """ import os print('Process (%s) start...' % os.getpid()) pid = os.fork() if pid == 0: print('i am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid())) else: print('i (%s) just created a child process (%s).' % (os.getpid(), pid)) """ #由于Windows没有fork调用,上面的代码在Windows上无法运行。 #由于Mac系统是基于BSD(Unix的一种)内核, #所以,在Mac下运行是没有问题的,推荐大家用Mac学Python! """ from multiprocessing import Process import os #子进程要执行的代码 def run_proc(name): print('Run child process %s (%s)...' % (name, os.getpid())) if __name__ == '__main__': print('Parent process %s.' % os.getpid()) p = Process(target=run_proc, args = ('test',)) print('Child process will start.') p.start() p.join() print('Child process end.') """ #在IDE中直接运行,看不到子进程的运行结果, #这是因为multiprocessing模块在交互模式是不支持的, #在 cmd 里头输入 python xxx.py 来运行起来,就可以看到子进程的执行了。 """ 输出结果: Parent process 10480. Child process will start. Run child process test (10268)... Child process end. """ #如果要启动大量的子进程,可以用进程池的方式批量创建子进程: """ from multiprocessing import Pool import os, time, random def long_time_task(name): print('Run task %s (%s)...' % (name, os.getpid())) start = time.time() time.sleep(1) #睡1秒 end = time.time() print('Task %s runs %0.2f seconds.' % (name, (end - start))) if __name__ == '__main__': print('Parent process %s.' % os.getpid()) p = Pool(4) for i in range(5): p.apply_async(long_time_task, args=(i,)) print('Waiting for all subprocesses done...') p.close() p.join() print('All subprocess done.') """ #代码解读: #对Pool对象调用join()方法会等待所有子进程执行完毕, #调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。 #请注意输出的结果,task 0,1,2,3是立刻执行的,而task 4要等待前面某个task完成后才执行, #这是因为Pool的默认大小在我的电脑上是4,因此,最多同时执行4个进程。 #这是Pool有意设计的限制,并不是操作系统的限制。如果改成: #p = Pool(5) #就可以同时跑5个进程 """ 在命令行下运行 输出结果: Parent process 11084. Waiting for all subprocesses done... Run task 0 (10880)... Run task 1 (10792)... Run task 2 (11160)... Run task 3 (10328)... Task 0 runs 1.00 seconds. Run task 4 (10880)... Task 1 runs 1.00 seconds. Task 2 runs 1.00 seconds. Task 3 runs 1.00 seconds. Task 4 runs 1.00 seconds. All subprocess done. """ #多线程 #Python的标准库提供了两个模块:_thread和threading,_thread是低级模块, #threading是高级模块,对_thread进行了封装。 #绝大多数情况下,我们只需要使用threading这个高级模块。 import time, threading #新线程执行的代码 def loop(): print('thread %s is running...' % threading.current_thread().name) n = 0 while n < 5: n = n + 1 print('thread %s >>> %s' % (threading.current_thread().name, n)) time.sleep(0.1) print('thread %s ended.' % threading.current_thread().name) print('thread %s is running...' % threading.current_thread().name) t = threading.Thread(target=loop, name='LoopThread') t.start() t.join() print('thread %s ended.' % threading.current_thread().name) #由于任何进程默认就会启动一个线程,我们把该线程称为主线程,主线程又可以启动新的线程, #Python的threading模块有个current_thread()函数,它永远返回当前线程的实例。 #主线程实例的名字叫MainThread,子线程的名字在创建时指定,我们用LoopThread命名子线程。 #名字仅仅在打印时用来显示,完全没有其他意义, #如果不起名字Python就自动给线程命名为Thread-1,Thread-2…… """ 输出结果: thread MainThread is running... thread LoopThread is running... thread LoopThread >>> 1 thread LoopThread >>> 2 thread LoopThread >>> 3 thread LoopThread >>> 4 thread LoopThread >>> 5 thread LoopThread ended. thread MainThread ended. """ print('\n') #Lock #多线程和多进程最大的不同在于,多进程中,同一个变量,各自有一份拷贝存在于每个进程中, #互不影响,而多线程中,所有变量都由所有线程共享, #所以,任何一个变量都可以被任何一个线程修改, #因此,线程之间共享数据最大的危险在于多个线程同时改一个变量,把内容给改乱了。 import time, threading balance = 0 def change_it(n): global balance balance = balance + n balance = balance - n # 先存后取,结果应该为0: def run_thread(n): for i in range(1000000): change_it(n) t1 = threading.Thread(target = run_thread, args = (5,)) t2 = threading.Thread(target = run_thread, args = (8,)) t1.start() t2.start() t1.join() t2.join() print(balance) ## 最终balance不一定为0 """ t1和t2是交替运行的,如果操作系统以下面的顺序执行t1、t2: 初始值 balance = 0 t1: x1 = balance + 5 # x1 = 0 + 5 = 5 t2: x2 = balance + 8 # x2 = 0 + 8 = 8 t2: balance = x2 # balance = 8 t1: balance = x1 # balance = 5 t1: x1 = balance - 5 # x1 = 5 - 5 = 0 t1: balance = x1 # balance = 0 t2: x2 = balance - 8 # x2 = 0 - 8 = -8 t2: balance = x2 # balance = -8 结果 balance = -8 """ balance = 0 lock = threading.Lock() def run_thread(n): for i in range(100000): #先获取锁 lock.acquire() try: change_it(n) finally: lock.release() t1 = threading.Thread(target = run_thread, args = (5,)) t2 = threading.Thread(target = run_thread, args = (8,)) t1.start() t2.start() t1.join() t2.join() print(balance) ## 最终balance一定为0 #当多个线程同时执行lock.acquire()时,只有一个线程能成功地获取锁, #然后继续执行代码,其他线程就继续等待直到获得锁为止。 #获得锁的线程用完后一定要释放锁,否则那些苦苦等待锁的线程将永远等待下去,成为死线程。 #所以我们用try...finally来确保锁一定会被释放 print('\n') #多核CPU """ 用Python代码启动与CPU核心数量相同的N个线程,在4核CPU上可以监控到CPU占用率仅有102%,也就是仅使用了一核。 但是用C、C++或Java来改写相同的死循环,直接可以把全部核心跑满,4核就跑到400%,8核就跑到800%,为什么Python不行呢? 因为Python的线程虽然是真正的线程,但解释器执行代码时,有一个GIL锁:Global Interpreter Lock,任何Python线程执行前, 必须先获得GIL锁,然后,每执行100条字节码,解释器就自动释放GIL锁,让别的线程有机会执行。 这个GIL全局锁实际上把所有线程的执行代码都给上了锁,所以,多线程在Python中只能交替执行,即使100个线程跑在100核CPU上,也只能用到1个核。 GIL是Python解释器设计的历史遗留问题,通常我们用的解释器是官方实现的CPython,要真正利用多核,除非重写一个不带GIL的解释器。 所以,在Python中,可以使用多线程,但不要指望能有效利用多核。如果一定要通过多线程利用多核,那只能通过C扩展来实现,不过这样就失去了Python简单易用的特点。 不过,也不用过于担心,Python虽然不能利用多线程实现多核任务,但可以通过多进程实现多核任务。多个Python进程有各自独立的GIL锁,互不影响。 """
#Automatas def a_int(src): s = 1 for c in src: if s == 1 and c == "i": s = 2 elif s == 2 and c == "n": s = 3 elif s == 3 and c == "t": s = 4 else: s = -1 break return s == 4 def a_float(src): s = 1 for c in src: if s == 1 and c == 'f': s = 2 elif s == 2 and c == 'l': s = 3 elif s == 3 and c == 'o': s = 4 elif s == 4 and c == 'a': s = 5 elif s == 5 and c == 't': s = 6 else: s = -1 break return s == 6 def a_if(src): s = 1 for c in src: if s == 1 and c == 'i': s = 2 elif s == 2 and c == 'f': s = 3 else: s = -1 break return s == 3 def a_else(src): s = 1 for c in src: if s == 1 and c == 'e': s = 2 elif s == 2 and c == 'l': s = 3 elif s == 3 and c == 's': s = 4 elif s == 4 and c == 'e': s = 5 else: s = -1 break return s == 5 def a_for(src): s = 1 for c in src: if s == 1 and c == 'f': s = 2 elif s == 2 and c == 'o': s = 3 elif s == 3 and c == 'r': s = 4 else: s = -1 break return s == 4 def a_while(src): s = 1 for c in src: if s == 1 and c == "w": s = 2 elif s == 2 and c == "h": s = 3 elif s == 3 and c == "i": s = 4 elif s == 4 and c == "l": s = 5 elif s == 5 and c == "e": s = 6 else: s = -1 break return s == 6 def a_ParAbierto(src): s = 1 for c in src: if s == 1 and c == "(": s = 2 else: s = -1 break return s == 2 def a_ParCerrado(src): s = 1 for c in src: if s == 1 and c == ")": s = 2 else: s = -1 break return s == 2 def a_LLaAbierta(src): s = 1 for c in src: if s==1 and c == "{": s = 2 else: s = -1 break return s == 2 def a_LLaCerrada(src): s = 1 for c in src: if s == 1 and c == "}": s = 2 else: s = -1 break return s == 2 def a_Mas(src): s = 1 for c in src: if s == 1 and c == '+': s = 2 return s == 2 def a_Menos(src): s = 1 for c in src: if s == 1 and c == '-': s = 2 else: s = -1 break return s == 2 def a_Por(src): s = 1 for c in src: if s == 1 and c == '*': s = 2 else: s = -1 break return s == 2 def a_Dividido(src): s = 1 for c in src: if s == 1 and c == '/': s = 2 else: s = -1 break return s == 2 def a_Coma(src): s = 1 for c in src: if s == 1 and c == ',': s = 2 else: s = -1 break return s == 2 def a_PuntoComa(src): s = 1 for c in src: if s == 1 and c == ';': s = 2 else: s = -1 break return s == 2 def a_PuntoIgual(src): s = 1 for c in src: if s == 1 and c == ':': s = 2 elif s == 2 and c == '=': s = 3 else: s = -1 break return s == 3 def a_Igual(src): s = 1 for c in src: if s == 1 and c == '=': s = 2 else: s = -1 break return s == 2 def a_Menor(src): s = 1 for c in src: if s == 1 and c == '<': s = 2 else: s = -1 break return s == 2 def a_Mayor(src): s = 1 for c in src: if s == 1 and c == '>': s = 2 else: s = -1 break return s == 2 def a_MayorIgual(src): s = 1 for c in src: if s == 1 and c == '>': s = 2 elif s == 2 and c == '=': s = 3 else: s = -1 break return s == 3 def a_MenorIgual(src): s = 1 for c in src: if s == 1 and c == '<': s = 2 elif s == 2 and c == '=': s = 3 else: s = -1 break return s == 3 def a_Distinto(src): s = 1 for c in src: if s == 1 and c == '!': s = 2 elif s == 2 and c == '=': s = 3 else: s = -1 break return s == 3 def a_IgualIgual(src): s = 1 for c in src: if s == 1 and c == '=': s = 2 elif s == 2 and c == '=': s = 3 else: s = -1 break return s == 3 def a_Num(src): s = 1 for c in src: if s == 1 and c.isdigit(): s = 2 elif s == 2 and c.isdigit(): s = 2 else: s = -1 break return s == 2 def a_Id(src): s = 1 for c in src: if s == 1 and c.isalpha(): s = 2 elif s == 2 and c.isalpha(): s = 2 else: s = -1 break return s == 2 def ERROR_TOKEN_PARCIAL(src): s = 1 for c in src: if s == 1 and c == ":": s = 2 elif s == 1 and c == "!": s = 2 elif s == 1 and c == "=": s = 2 else: s = -1 break return s == 2 Token_Clasificacion = [ ("Int", a_int), ("Float", a_float), ("If", a_if), ("Else", a_else), ("For", a_for), ("While", a_while), ("(", a_ParAbierto), (")", a_ParCerrado), ("{", a_LLaAbierta), ("}", a_LLaCerrada), ("+", a_Mas), ("-", a_Menos), ("*", a_Por), ("/", a_Dividido), (",", a_Coma), (";", a_PuntoComa), (":=", a_PuntoIgual), ("<", a_Menor), (">", a_Mayor), (">=", a_MayorIgual), ("<=", a_MenorIgual), ("!=",a_Distinto), ("==", a_IgualIgual), ("Numero", a_Num), ("Identificador", a_Id), ("ERROR_TP", ERROR_TOKEN_PARCIAL) ] def lexer(src): tokens = [] src = src + " " i = 0 start = 0 state = 0 while i<len(src): c = src[i] word = src[start: i+1] if state == 0: if c.isspace(): i+=1 state = 0 else: start = i state = 1 elif state == 1: if es_aceptada(word) and not c.isspace(): i+=1 state = 1 else: i-=1 state = 2 elif state == 2: candidatos = [] candidatos = calc_candidatos(word) if len(candidatos) > 0: if candidatos[0] == "ERROR_TP": print ("ERROR_TP: La candena ingresada es invalida") else: token = (candidatos[0], word) tokens.append(token) else: tokens = [] print ("ERROR: La cadena ingresada es invalida") return tokens i+=1 start = i state = 0 else: print("ERROR: Cadena no aceptada") return tokens def es_aceptada(word): candidatos = calc_candidatos(word) if len(candidatos) > 0: return True else: return False def calc_candidatos(word): candidatos = [] for (clasi, afd) in Token_Clasificacion: if afd(word): candidatos.append(clasi) return candidatos #print ("1", lexer("for{ x>5, y<=26 };")) #print ("2", lexer("while (abc - 6)*77 float 553 ")) #print ("3", lexer("float hola := 123")) #print ("4", lexer(" % ")) #print ("5", lexer(" != kkkk ;")) #print ("6", lexer(" if >= { 123 } ac / hola (10-5)")) #print ("7", lexer(" int >= 885232 + asd (x/655622) ")) #print ("8", lexer(" abc123")) #print ("9", lexer("(x>4,55) int ((8*8)/(56 + 265)) ;")) #print ("10", lexer(" if 25 == true else 5"))
from holes import Hole, Rumba class Board: def __init__(self, num_holes): # Rumba MUST BE zeroth element of self.holes self.holes = [Rumba() if i == 0 else Hole() for i in range(num_holes)] def _harvest(self, hole_index): hole = self.holes[hole_index] seeds = hole.harvest() if seeds == 0: raise RuntimeError("Cannot harvest an empty hole!") return seeds def _seed(self, hole_index, seeds): # Spread seeds around the board while seeds > 0: self.holes[hole_index].seed() seeds -= 1 hole_index = self._next(hole_index) # Get last seeded hole last_hole_index = hole_index - 1 if last_hole_index == -1: last_hole_index = len(self.holes) - 1 return last_hole_index def harvest_and_seed(self, hole_index): seeds = self._harvest(hole_index) last_hole_index = self._seed(self._next(hole_index), seeds) return last_hole_index def _next(self, hole_index): return hole_index + 1 if hole_index < len(self.holes)-1 else 0
#P08_PythonProject_10 HargaBuah = {'apel' : 5000, 'jeruk' : 8500, 'mangga' : 7800, 'duku' : 6500} dataBuah =[] i = 1 nama = str(input('Nama buah yang dibeli :')) kg = int(input('Berapa Kg :')) print() try: harga = HargaBuah[nama] TotalHarga = harga*kg dataBuah.append(TotalHarga) i += 1 except KeyError: print('Nama buah tidak ditemukan') while True: tambah = str(input('Beli buah yang lain (y/n)?:')) if(tambah == 'y'): print() nama = str(input('Nama buah yang dibeli :')) kg = int(input('Berapa Kg :')) print() try: harga = HargaBuah[nama] TotalHarga = harga*kg dataBuah.append(TotalHarga) i += 1 except KeyError: print('Nama buah tidak ditemukan') if(tambah == 'n'): print('-----------------------------') databuah = tuple(dataBuah) print('Total Harga :',sum(databuah)) break
#P08_PythonProject_2 def dataStat(x): a = sum(x)/len(x) b = max(x) c = min(x) dataABC = [a,b,c] return dataABC while True: n = int(input('Masukkan banyak angka:')) break Nilai = [] i = 0 while(i < n): angka = int(input('Masukkan angka yang diinginkan:')) Nilai.append(angka) i += 1 printNilai = dataStat(Nilai) print(printNilai)
kode_karyawan = int(input('Masukkan Kode Karyawan :')) nama_karyawan = input('Masukkan Nama Karyawan:') golongan = input('Masukkan Golongan:') print('====================================') print('STRUK RINCIAN GAJI KARYAWAN') print('------------------------------------') print('Nama Karyawan :' + nama_karyawan + '(Kode Karyawan:' + str (kode_karyawan) + ')') print('Golongan :' + golongan) print('------------------------------------') if (golongan == 'A'): GajiPokok = 10000000 Potongan = 2.5 JmlPotongan = 2.5 / 100 * 10000000 GajiBersih = 10000000 - JmlPotongan elif (golongan == 'B'): GajiPokok = 8500000 Potongan = 2.0 JmlPotongan = 2.0/ 100 * 8500000 GajiBersih = 8500000 - JmlPotongan elif (golongan == 'C'): GajiPokok = 7000000 Potongan = 1.5 JmlPotongan = 1.5/ 100 * 7000000 GajiBersih = 7000000 - JmlPotongan elif (golongan == 'D'): GajiPokok = 5500000 Potongan = 1.0 JmlPotongan = 1.0/ 100 * 5500000 GajiBersih = 5500000- JmlPotongan print('GajiPokok: Rp' + str (GajiPokok)) print('Potongan(' + str (Potongan) + '%): Rp' + str(JmlPotongan)) print ('--------------------------------- -') print('GajiBersih: Rp' + str (GajiBersih))
name = input('What is your name? ') lenth_is = (len(name)) if lenth_is < 3: print('Name must be at least 3 characters.') print('Try again.') elif lenth_is > 50 : print ('Name can be a max of 50 characters.') else : print('Name looks good.')
course = ''' Good morning, Thanks for your email, we will get back to you as soon as we can. Regards, Miguel CEO ''' test2 = (course[:]) test3 = (test2 * 100) name = 'Jennifer' last = 'Perez' msg = name + ' ' + last print (msg) message = f'{name} [{last}] is a coder.' print (message) message2 = name + (name[0])+ 'is a coder' print (message2) lastMessage = f'{name} [{last}] is a coder' print (lastMessage) nombre = input('What is your name? ') apellido = input("What is your last name? ") message3 = f'Hola {nombre} {apellido}, you are on the right way! ' print (message3) course1 = ''' Good morning, Thanks for your email, we will get back to you as soon as we can. Regards, Miguel CEO ''' lenght_is = (len(course1)) message = f'This email contains {lenght_is} letters.' print (message)
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import LogisticRegression inputFile = 'MoviesDataset.csv' # Using panda to import the csv file and separate the summaries from the sentiments # header=0 skips the first line since it's just the titles df = pd.read_csv(inputFile, names=['Summary', 'Sentiment'], sep=',', header=0) print(df) # Keep the values into lists summary = df['Summary'].values sentiment = df['Sentiment'].values # Using test_train_split from the sklearn library to train the system # test_size is 1% (=0.01) so train_size becomes 99% # Also random_state is used (has default value = 'None'), so each run will provide different results x_reviews_train, x_reviews_test, y_reviews_train, y_reviews_test = train_test_split(summary, sentiment, test_size=0.1) vectorizer = CountVectorizer() vectorizer.fit(x_reviews_train) X_train = vectorizer.transform(x_reviews_train) X_test = vectorizer.transform(x_reviews_test) classifier = LogisticRegression() classifier.fit(X_train, y_reviews_train) accuracy = classifier.score(X_test, y_reviews_test) # accuracy number converted to percentage rounded to 2 floating points (and converted to string) print("Prediction accuracy:", str(round(float(accuracy*100), 2)) + "%\n") print("Below you can manually input a sentence and it's predicted sentiment will be returned\n") while 1: inp = input("Please type a sentence to (or 'exit' to terminate): ") if inp == "exit": print("Exiting...") break X_new = vectorizer.transform([inp]) if int(classifier.predict(X_new)) == 1: print("Sentence has:\tPositive sentiment\n") else: print("Sentence has:\tNegative sentiment\n")
for x in range(0, 151, 1): print(x) for i in range(5, 1005, 5): print(i) for i in range(0, 100, 1): if i % 10 == 0: print("Coding Dojo") elif i % 5 == 0: print("coding") sum = 0 for i in range(0, 500001, 1): if i % 2 == 1: sum += i print(i, sum) for i in range(2018, 0, -4): print(i) lowNum = 1 highNum = 10 mult = 2 for i in range(lowNum, highNum + 1): if i % mult == 0: print(i)
import urllib.request # urllib.request is a Python module for fetching URLs (Uniform Resource Locators). from bs4 import BeautifulSoup # Beautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying the parse tree. # import re # Python's regular expression library repos = [] # frameworks = ['angular', 'react', 'vue', 'ember', 'meteor', 'mithril', 'node', 'polymer', 'aurelia', 'backbone'] # max_pages = 100 # ads_per_page = 10 # max_ads = max_pages * ads_per_page search = "https://github.com/heagueron?tab=repositories" url = urllib.request.urlopen(search) soup = BeautifulSoup(url, features="html.parser") # print(soup) for repo in soup.select('a[itemprop="name codeRepository"]'): # href = adlink['href'] # subURL = "https://www.indeed.com" + href # subSOUP = BeautifulSoup(urllib.request.urlopen(subURL), features="html.parser") repo_name = repo.get_text().lower() print(repo_name) """ for desc in subSOUP.select('div[class*="jobsearch-JobComponent-description"]'): words = re.split("[ ,.:/?()\n\t\r]", desc.get_text().lower()) for word in words: word = word.strip() if word.endswith("'s"): word = word[:-2] if word.endswith(".js"): word = word[:-3] if word.endswith("js"): word = word[:-2] if len(word) < 2: continue if word not in frameworks: continue if word in counts: counts[word] += 1 else: counts[word] = 1 word_freq = [] for key, value in counts.items(): word_freq.append((value,key)) word_freq.sort(reverse=True) print(counts) """
import numpy as np def generate_matrix(m, n): Z = np.random.randint(0, 100, (m, n)) # Matrix for testing """ Z = np.array([ (1, 2, 3, 5), (2, 1, 2, 3), (3, 2, 1, 2), (4, 3, 2, 1), (5, 4, 3, 2) ]) """ print(Z) return Z def is_toepliz(Z, m, n): toe = True for index, element in np.ndenumerate(Z): # print(index, element) row_index, col_index = 1, 1 while ( (index[0] + row_index) <= (m-1) ) and ( (index[1] + col_index) <= (n-1) ): if element != Z[(index[0] + row_index), (index[1] + col_index)]: toe = False break row_index += 1 col_index += 1 if toe == False: break return toe def main(): # The size of the matrix: m = int( input("\nEnter number of rows (1 to 1000): ") ) n = int( input("\nEnter number of columns (1 to 1000): ") ) Z = generate_matrix(m, n) if is_toepliz(Z, m, n): print("The matrix is Toeplitz") else: print("The matrix is not Toeplitz") return if __name__ == "__main__": main()
""" Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo. """ reta_1 = float(input("Digite o comprimento da primeira reta: ")) reta_2 = float(input("Digite o comprimento da segunda reta: ")) reta_3 = float(input("Digite o comprimento da terceira reta: ")) if (reta_1 < (reta_2 + reta_3)) and (reta_2 < (reta_1 + reta_3)) and (reta_3 < (reta_1 + reta_2)): print("o Comprimento dos 3 retas podem formar um triângulo") else: print("A medida dos três não podem formar um triângulo!")
""" Faça um programa que leia três números e mostre qual é o maior e qual é o menor. """ """ numero_1 = float(input("Digite o primeiro número: ")) numero_2 = float(input("Digite o segundo número: ")) numero_3 = float(input("Digite o terceiro número: ")) if numero_1 > numero_2 and numero_1 > numero_3: print("numero {} é o maior número".format(numero_1)) elif numero_2 > numero_1 and numero_2 > numero_3: print("numero {} é o maior número".format(numero_2)) elif numero_3 > numero_1 and numero_3 > numero_2: print("numero {} é o maior número".format(numero_3)) else: print("Os número são iguais") """ numero_1 = float(input("Digite o primeiro número: ")) numero_2 = float(input("Digite o segundo número: ")) numero_3 = float(input("Digite o terceiro número: ")) maior = numero_1 if numero_2 > numero_3 and numero_2 > numero_1: maior = numero_2 if numero_3 > numero_1 and numero_3 > numero_2: maior = numero_3 menor = numero_1 if numero_2 < numero_3 and numero_2 < numero_1: menor = numero_2 if numero_3 < numero_2 and numero_3 < numero_1: menor = numero_3 print("O menor valor digitado foi {}".format(menor)) print("O maior valor digitado foi {}".format(maior))
""" Escreva um programa que pergunte a quantidade de Km percorrido por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado. """ dias = int(input("Digite quantos dias você ficou com o carro: ")) km = float(input("Digite quantos quilometros você percorreu: ")) pago = (dias * 60) + (km * 0.15) print("O total a pagar é de R${:.2f}".format(pago))
""" Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre todos os valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores. """ maior = 0 menor = 0 soma = 0 media = 0 contador = 0 resposta = '' while resposta != 'N': valor = int(input("Digite um valor: ")) soma += valor contador += 1 if contador == 1: maior = valor menor = valor else: if valor > maior: maior = valor elif valor < menor: menor = valor resposta = input("Deseja continuar? S/N: ").upper().strip()[0] media = soma / contador print("O maior número digitado foi {}".format(maior)) print("O menor número digitado foi {}".format(menor)) print("A média entre os {} números digitados foram: {}".format(contador, media))
""" Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA no nome. """ nome = str(input("Digite o seu nome:\n").strip().upper()) print("O seu nome {} tem 'SILVA' contido nele? {}".format(nome, "SILVA" in nome))
""" Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a média atingida: - Média abaixo de 5.0: REPROVADO - Média entre 5.0 e 6.9: RECUPERAÇÃO -Média 7.0 ou superior: APROVADO """ nota_1 = float(input("Digite a primeira nota: ")) nota_2 = float(input("Digite a segunda nota: ")) media = (nota_1 + nota_2) / 2 if media < 5.0: print("A sua média foi de {}, REPROVADO!".format(media)) elif media < 6.9: print("A sua média foi de {}, RECUPERAÇÃO!".format(media)) elif media <= 10: print("Asua média foi de {}, APROVADO!".format(media)) else: print("Suas medias não estão no criterio de 0 a 10!")
""" Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final mostre os 10 primeiros termos dessa progressão. """ """ a1 = int(input("Digite o primeiro termo: ")) a2 = int(input("Digite a razão de uma PA: ")) pa = a1 if a1 > 0 or a1 == 0: for numero in range(1, 10 + 1): print(pa, end=" -> ") pa += a2 elif a1 < 0: for numero in range(1, 10 + 1): print(pa) pa -= a2 print("Fim") """ primeiro = int(input("Digite o primeiro termo: ")) razao = int(input("Digite a razão de uma PA: ")) decimo = primeiro + (10 - 1) * razao for c in range(primeiro, decimo + razao, razao): print("{} ".format(c), end=" -> ") print("Acabou")
""" Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo, calcule e mostre o comprimento da hipotesusa. """ """ co = float(input("Comprimento do cateto oposto: ")) ca = float(input("Comprimento do cateto adjacente: ")) hi = ((co ** 2) + (ca ** 2)) ** (1/2) print('A hipotenusa vai medir {}'.format(hi)) """ from math import hypot cateto_oposto = float(input("Digite o cateto oposto do triangulo retângulo: ")) cateto_adjacente = float(input("Digite o cateto adjacente do triângulo retângulo: ")) hipotenusa = hypot(cateto_oposto, cateto_adjacente) print("A hipotenusa vai medir {:.2f}".format(hipotenusa))
# Copy File # Choose My Type file # Choose Local Disk # print(' Do you want to keep stealing files? ') # print(' if you want to Choose [1]') # print(" if you dont want to Choose [2]") # T2 = str(input('Choose [1] or [2] : ')) # if ('1' or '[1]') in T2 : # B = str(input('Enter Local path files : ')) # E = str(input('Enter Paste Local Disk : ')) # T3 = str(input('Enter Type file : ')).lower() # path = r'{}'.format(B) # destination = '{}:\\'.format(E) # for f in allfile: # if f[-len(T3):] == T3 : # source = os.path.join(path,f) # dest = os.path.join(destination,f) # print(source) # print(dest) # shutil.move(source,dest) # print('----') # else : # exit() import os import shutil def main(): A = str(input('Enter Local path files : ')) P = str(input('Enter Paste Local Disk : ')) T1 = str(input('Enter Type file : ')).lower() path = r'{}'.format(A) destination = '{}:\\'.format(P) allfile = os.listdir(path) for f in allfile: if f[-len(T1):] == T1 : source = os.path.join(path,f) dest = os.path.join(destination,f) print(source) print(dest) shutil.move(source,dest) print('----') print(te) test = int(input('case : ')) if test == 1 : main() elif test != 1 : exit()
""" Dado um número inteiro não negativo n, determinar n! Exemplo: 5! = 5*4*3*2*1 3! = 3*2*1 # Usando exemplo decrementando: # Início num = int(input("Digite um número: ")) # Vamos supor que num=4, cont seria cont=4-1, ou seja, cont=3 cont = num - 1 # Será uma variável auxiliar que ficará sendo decrementada em 1 produto = num while cont > 1: # 4 = 4 * 3 produto = produto * cont # cont = 4 - 1, cont=3 cont -= 1 print(num,"! =",produto) # Fim Usando incrementando """ # Início num = int(input("Digite um número: ")) produto = 1 cont = 2 while cont <= num: produto = produto * cont cont += 1 print(num,"! =",produto)
""" Dada uma sequência de números inteiros não nulos, finalize a lista em 0, imprimir quadrados. """ num = int(input("Digite o primeiro número: ")) while num != 0: print(num,"ao quadrado =",num*num) num = int(input("Digite o próximo número: ")) if num == 0: print("Valor nulo. Finalizando programa!!")
""" Faça um programa para um caixa eletrônico. O programa deverá perguntar ao usuário o valor do saque e depois informar quantas notas de cada valor serão fornecidas. As notas disponíveis serão às de 1, 5, 10, 50 e 100 reais. O valor mínimo é de 10 reais e o máximo de 600 reais. O programa não deve se preocupar com a quantidade de notas existentes na máquina: Exemplo 01: Para sacar a quantia de 256 reais, o programa fornece duas notas de 100, uma de 50, uma de 5 e uma de 1; Exemplo 02: Para sacar a quantia de 399 reais, o programa fornece 03 notas de 100, uma nota de 50, quatro de 10, uma de 5 e quatro de 1. """ saque = int(input("Digite o valor do saque: ")) if 10 <= saque <= 600: notas_cem = saque//100 saque = saque % 100 notas_cinquenta = saque//50 saque = saque % 50 notas_dez = saque//10 saque = saque % 10 notas_cinco = saque//5 saque = saque % 5 notas_um = saque//1 if notas_cem > 0: print(notas_cem, "notas de R$ 100") if notas_cinquenta > 0: print(notas_cinquenta, "notas de R$ 50") if notas_dez > 0: print(notas_dez, "notas de R$ 10") if notas_cinco > 0: print(notas_cinco, "notas de R$ 5") if notas_um > 0: print(notas_um, "notas de R$ 1") else: print("Nao é possivel fazer o saque")
num1, num2 = 15,10 print("x =",num1) print("y =",num2) print(num1,"+",num2,"=",num1+num2) print(num1,"-",num2,"=",num1-num2) print(num1,"/",num2,"=",num1/num2) print(num1,"//",num2,"=",num1//num2) print(num1,"resto",num2,"=",num1%num2)
""" Faça um programa que leia três números e mostre-os em ordem decrescente """ num1 = int(input("Digite o primeiro número: ")) num2 = int(input("Digite o segundo número: ")) num3 = int(input("Digite o terceiro número: ")) if num1 >= num2 >= num3: print(num1, num2, num3) elif num1 >= num3 >= num2: print(num1, num3, num2) elif num2 >= num1 >= num3: print(num2, num1, num3) elif num2 >= num3 >= num1: print(num2, num3, num1) elif num3 >= num1 >= num2: print(num3, num1, num2) else: print(num3, num2, num1)
from tkinter import * from PIL import Image,ImageTk window=Tk() window.geometry('500x500') window.title('Registration Form') # root=Tk() # root.geometry('500x500') # root.title('Registration Form2') width = 100 height = 100 img=Image.open("D:/Python/tikinter/clipart.jpg") img = img.resize((width,height),Image.ANTIALIAS) photo=ImageTk.PhotoImage(img) lab=Label(image=photo) lab.pack() # img=Image.open("D:/Python/tikinter/shtk.jpg") # photo1=ImageTk.PhotoImage(img) # lab=Label(image=photo1) # lab.pack() fn1=StringVar() fn2=StringVar() fn3=StringVar() var=StringVar() def printt(): first=fn1.get() sec=fn2.get() index=fn3.get() var1=var.get() print(f"Your Fullname is :{first} {sec}") print(f"Your Index is :{index}") print(f"Your Country is :{var1}") def end(): exit() lable1=Label(window,text="Registration Form",relief="solid",width=20,font=('arial',19,'bold')) lable1.place(x=90,y=110) lable2=Label(window,text="Frist Name:",font=('arial',10,'bold')) lable2.place(x=90,y=160) entry1=Entry(window,textvar=fn1) entry1.place(x=200,y=160) lable3=Label(window,text="Last Name:",font=('arial',10,'bold')) lable3.place(x=90,y=200) entry1=Entry(window,textvar=fn2) entry1.place(x=200,y=200) lable4=Label(window,text="Index:",font=('arial',10,'bold')) lable4.place(x=90,y=240) entry1=Entry(window,textvar=fn3) entry1.place(x=200,y=240) lable4=Label(window,text="Country:",font=('arial',10,'bold')) lable4.place(x=90,y=280) list1=['Sri Lanka','India','USA','Canada','German'] droplist=OptionMenu(window,var,*list1) var.set('Select country') droplist.config(width=15) droplist.place(x=200,y=280) b1=Button(window,text='login',relief='solid',width=12,font=('aril',10),command=printt) b1.place(x=90,y=350) b2=Button(window,text='Quit',relief='solid',width=12,font=('aril',10),command=end) b2.place(x=300,y=350) window.mainloop()
# -*- coding: utf-8 -*- """ Created on Thu Jul 25 12:59:17 2019 @author: AShete """ # implementation of switch case # Using Dictionary def add_nums(a,b): return a+b def sub_nums(a,b): return a-b def mul_nums(a,b): return a*b def div_nums(a,b): return a/b def default(): return "Invalid Input !" switcher={ 1:add_nums(10,20), 2:sub_nums(30,20), 3:mul_nums(5,5), 4:div_nums(25,5), 5:default() } def switch(key): return switcher.get(key,default) print("Result : ",switch(6)) # Simple switch case print("## Mathematical Operations ##") print("1. Addition") print("2. Substraction") print("3. Multiplication") print("4. Division") choice=input("Enter your choice (1|2|3|4): ") num1=int(input("Enter 1st Number : ")) num2=int(input("Enter 2nd Number : ")) if choice=="1": result=add_nums(num1,num2) print("Result : ",result) elif choice=="2": result=sub_nums(num1,num2) print("Result : ",result) elif choice=="3": result=mul_nums(num1,num2) print("Result : ",result) elif choice=="4": result=div_nums(num1,num2) print("Result : ",result) else: print("Invalid Input !")
""" Stop and think: words with which prefix should you remove from tweets? #, @? """ import re #regular expressions module # Define abbreviations # as regular expressions together with their expansions # (\b marks the word boundary): re_repl = { r"\br\b": "are", r"\bu\b": "you", r"\bhaha\b": "ha", r"\bhahaha\b": "ha", r"\bdon't\b": "do not", r"\bdoesn't\b": "does not", r"\bdidn't\b": "did not", r"\bhasn't\b": "has not", r"\bhaven't\b": "have not", r"\bhadn't\b": "had not", r"\bwon't\b": "will not", r"\bwouldn't\b": "would not", r"\bcan't\b": "can not", r"\bcannot\b": "can not" } emo_repl = { # positive emoticons "&lt;3": " good ", ":d": " good ", # :D in lower case ":dd": " good ", # :DD in lower case "8)": " good ", ":-)": " good ", ":)": " good ", ";)": " good ", "(-:": " good ", "(:": " good ", # negative emoticons: ":/": " bad ", ":&gt;": " sad ", ":')": " sad ", ":-(": " bad ", ":(": " bad ", ":S": " bad ", ":-S": " bad ", } # make sure that e.g. :dd is replaced before :d emo_repl_order = [k for (k_len,k) in reversed(sorted([(len(k),k) for k in emo_repl.keys()]))] def clean_tweet(tweet, emo_repl_order, emo_repl, re_repl ): tweet = tweet.lower() for k in emo_repl_order: tweet = tweet.replace(k, emo_repl[k]) for r, repl in re_repl.items(): tweet = re.sub(r, repl, tweet) return tweet
def berechneUrlaubsanspruch(): if alter <18: urlaubsanspruch=30 elif alter <55: urlaubsanspruch=26 else: urlaubsanspruch=28 if behinderung==1: urlaubsanspruch=urlaubsanspruch+5 else: urlaubsanspruch=urlaubsanspruch if beschäftigungsläner<=10: urlaubsanspruch=urlaubsanspruch else: urlaubsanspruch=urlaubsanspruch+2 return urlaubsanspruch def main(): alter = int(input("Alter: ")) behinderung = int(input("Behinderung 0/nein,1/ja")) beschäftigungslänge = int(input("Beschäftigungslänge:")) urlaubsanspruch = berechneUrlaubsanspruch(alter, behinderung, beschäftigungslänge) print(urlaubsanspruch) main()
from enum import Enum class SideType(Enum): TYPE_WIDTH = 'width' TYPE_HEIGHT = 'height' class RightAngleShape: def set_side(self, size, side): pass def area_of(self): pass class Rectangle(RightAngleShape): def __init__(self, width, height): self.width = width self.height = height def set_side(self, size, side): if SideType.TYPE_WIDTH == side: self.width = size if SideType.TYPE_HEIGHT == side: self.height = size def set_width(self, width): self.set_side(width, SideType.TYPE_WIDTH) def set_height(self, height): self.set_side(height, SideType.TYPE_HEIGHT) def area_of(self): return self.width * self.height class Square(RightAngleShape): def __init__(self, size): self.edge = size def set_side(self, size, side=None): self.edge = size def set_width(self, width): self.set_side(width) def area_of(self): return self.edge ** 2 square = Square(10) rect = Rectangle(5, 10) def test_shape_size(figure): figure.set_width(10) figure.set_height(20) return figure.area_of() #print(test_shape_size(square)) print(test_shape_size(rect)) ''' предусловия не могут быть усилены в подклассе постусловия не могут быть ослаблены в подклассе '''
class Floor: def __init__(self): self.name = 'floor' def build(self): print(f'Build {self.name}') class Ceiling: def __init__(self): self.name = 'ceiling' def build(self): print(f'Build {self.name}') class Wall: def __init__(self): self.name = 'wall' def build(self): print(f'Build {self.name}') class Building: def __init__(self, floor, ceiling, wall): self.floor = floor self.ceiling = ceiling self.wall = wall house = Building(Floor(), Ceiling(), Wall()) house.floor.build() house.wall.build() house.ceiling.build()
''' 589. N-ary Tree Preorder Traversal Easy Given the root of an n-ary tree, return the preorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: [1,3,5,6,2,4] https://leetcode.com/problems/n-ary-tree-preorder-traversal/ ''' """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def preorder(self, root: 'Node') -> List[int]: self.retVal = [] def helper(root): if root: self.retVal.append(root.val) for child in root.children: helper(child) helper(root) return self.retVal
''' 382. Linked List Random Node Medium Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. Follow up: What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space? Example: // Init a singly linked list [1,2,3]. ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); Solution solution = new Solution(head); // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. solution.getRandom(); https://leetcode.com/problems/linked-list-random-node/ ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next import random class Solution: def __init__(self, head: ListNode): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. """ self.data = [] while head: self.data.append(head.val) head = head.next # 4/7 Passed # self.curr = 1 # self.len = -1 # self.head = head def getRandom(self) -> int: """ Returns a random node's value. """ return random.choice(self.data) # i, node = 1, self.head # while i < self.curr: # if node.next != None: # node = node.next # else: # self.len = i # self.curr = 1 # node = self.head # i += 1 # self.curr += 1 # return node.val # Your Solution object will be instantiated and called as such: # obj = Solution(head) # param_1 = obj.getRandom()
''' 1345. Jump Game IV Hard Given an array of integers arr, you are initially positioned at the first index of the array. In one step you can jump from index i to index: i + 1 where: i + 1 < arr.length. i - 1 where: i - 1 >= 0. j where: arr[i] == arr[j] and i != j. Return the minimum number of steps to reach the last index of the array. Notice that you can not jump outside of the array at any time. Example 1: Input: arr = [100,-23,-23,404,100,23,23,23,3,404] Output: 3 Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array. https://leetcode.com/problems/jump-game-iv/ ''' class Solution: def minJumps(self, arr: List[int]) -> int: n = len(arr) d = defaultdict(list) for i, num in enumerate(arr): d[num].append(i) queue = deque([(0, 0)]) visited, visited_groups = set(), set() while queue: steps, index = queue.popleft() if index == n - 1: return steps for neib in [index - 1, index + 1]: if 0 <= neib < n and neib not in visited: visited.add(neib) queue.append((steps + 1, neib)) if arr[index] not in visited_groups: for neib in d[arr[index]]: if neib not in visited: visited.add(neib) queue.append((steps + 1, neib)) visited_groups.add(arr[index])
''' 754. Reach a Number Medium You are standing at position 0 on an infinite number line. There is a goal at position target. On each move, you can either go left or right. During the n-th move (starting from 1), you take n steps. Return the minimum number of steps required to reach the destination. Example 1: Input: target = 3 Output: 2 Explanation: On the first move we step from 0 to 1. On the second step we step from 1 to 3. https://leetcode.com/problems/reach-a-number/ ''' class Solution: def reachNumber(self, target: int) -> int: target = abs(target) i = 0 while target > 0: i += 1 target -= i return i if target % 2 == 0 else i + 1 + i%2
''' 1448. Count Good Nodes in Binary Tree Medium Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X. Return the number of good nodes in the binary tree. Example 1: Input: root = [3,1,4,3,null,1,5] Output: 4 Explanation: Nodes in blue are good. Root Node (3) is always a good node. Node 4 -> (3,4) is the maximum value in the path starting from the root. Node 5 -> (3,4,5) is the maximum value in the path Node 3 -> (3,1,3) is the maximum value in the path. https://leetcode.com/problems/count-good-nodes-in-binary-tree/ ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def goodNodes(self, root: TreeNode) -> int: retVal = 0 def helper(node, minVal): nonlocal retVal if not node: return if node.val >= minVal: retVal+= 1 minVal = node.val helper(node.left, minVal) helper(node.right, minVal) helper(root, float('-inf')) return retVal
''' 47. Permutations II Medium Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order. Example 1: Input: nums = [1,1,2] Output: [[1,1,2], [1,2,1], [2,1,1]] https://leetcode.com/problems/permutations-ii/ ''' class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: retVal = [] def helper(curr, dic): if len(curr) == len(nums): retVal.append(list(curr)) return for num in dic: if dic[num] > 0: curr.append(num) dic[num] -= 1 helper(curr, dic) curr.pop() dic[num] += 1 helper([], Counter(nums)) return retVal
''' 991. Broken Calculator Medium On a broken calculator that has a number showing on its display, we can perform two operations: Double: Multiply the number on the display by 2, or; Decrement: Subtract 1 from the number on the display. Initially, the calculator is displaying the number X. Return the minimum number of operations needed to display the number Y. Example 1: Input: X = 2, Y = 3 Output: 2 Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}. https://leetcode.com/problems/broken-calculator/ ''' class Solution: def brokenCalc(self, X: int, Y: int) -> int: retVal = 0 while Y > X: retVal += 1 if Y % 2: Y += 1 else: Y //= 2 return retVal + X - Y
''' 816. Ambiguous Coordinates Medium We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces, and ended up with the string s. Return a list of strings representing all possibilities for what our original coordinates could have been. Our original representation never had extraneous zeroes, so we never started with numbers like "00", "0.0", "0.00", "1.0", "001", "00.01", or any other number that can be represented with less digits. Also, a decimal point within a number never occurs without at least one digit occuring before it, so we never started with numbers like ".1". The final answer list can be returned in any order. Also note that all coordinates in the final answer have exactly one space between them (occurring after the comma.) Example 1: Input: s = "(123)" Output: ["(1, 23)", "(12, 3)", "(1.2, 3)", "(1, 2.3)"] https://leetcode.com/problems/ambiguous-coordinates/ ''' class Solution: def ambiguousCoordinates(self, s: str) -> List[str]: results = set() isvalid = lambda x: len(str(int(x))) == len(x) def getvalidnums(s): nums = [] if isvalid(s): nums.append(s) for i in range(1, len(s)): if isvalid(s[:i]) and isvalid(s[i:][::-1]) and s[i:] != '0': nums.append(f'{s[:i]}.{s[i:]}') return nums for i in range(2, len(s)-1): lnums = getvalidnums(s[1:i]) rnums = getvalidnums(s[i:-1]) for x, y in product(lnums, rnums): results.add(f'({x}, {y})') return results
''' 988. Smallest String Starting From Leaf Medium Given the root of a binary tree, each node has a value from 0 to 25 representing the letters 'a' to 'z': a value of 0 represents 'a', a value of 1 represents 'b', and so on. Find the lexicographically smallest string that starts at a leaf of this tree and ends at the root. (As a reminder, any shorter prefix of a string is lexicographically smaller: for example, "ab" is lexicographically smaller than "aba". A leaf of a node is a node that has no children.) Example 1: Input: [0,1,2,3,4,3,4] Output: "dba" https://leetcode.com/problems/smallest-string-starting-from-leaf/ ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def smallestFromLeaf(self, root): """ :type root: TreeNode :rtype: str """ retVal = [] def helper(node, temp): if node: if not node.left and not node.right: retVal.append(chr(node.val + 97)+temp) return if node.left: helper(node.left, chr(node.val + 97)+temp) if node.right: helper(node.right, chr(node.val + 97)+temp) return temp = '' helper(root, temp) return sorted(retVal)[0]
''' 690. Employee Importance Easy You are given a data structure of employee information, which includes the employee's unique id, his importance value and his direct subordinates' id. For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct. Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all his subordinates. Example 1: Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1 Output: 11 Explanation: Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11. https://leetcode.com/problems/employee-importance/ ''' """ # Employee info class Employee(object): def __init__(self, id, importance, subordinates): ################# :type id: int :type importance: int :type subordinates: List[int] ################# # It's the unique id of each node. # unique id of this employee self.id = id # the importance value of this employee self.importance = importance # the id of direct subordinates self.subordinates = subordinates """ class Solution(object): def getImportance(self, employees, id): """ :type employees: List[Employee] :type id: int :rtype: int """ emp = {} for e in employees: emp[e.id] = e retVal = emp[id].importance lst = emp[id].subordinates while lst: curr = lst.pop() retVal += emp[curr].importance lst += emp[curr].subordinates return retVal
''' 44. Wildcard Matching Hard Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). Note: s could be empty and contains only lowercase letters a-z. p could be empty and contains only lowercase letters a-z, and characters like ? or *. Example 1: Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa". https://leetcode.com/problems/wildcard-matching/ ''' class Solution: def isMatch(self, s: str, p: str) -> bool: lens, lenp = len(s), len(p) i, j = 0, 0 star , temp = -1, -1 while i < lens: if j < lenp and p[j] == '*': star = j temp = i j +=1 elif j < lenp and (p[j] == '?' or p[j] == s[i]): j +=1 i +=1 elif star == -1: return False else: i = temp + 1 j = star + 1 temp += 1 for a in p[j:]: if a != '*': return False return True # DP Solution # dp = [[False for _ in range(len(p)+1)] for i in range(len(s)+1)] # dp[0][0] = True # for j in range(1, len(p)+1): # if p[j-1] != '*': # break # dp[0][j] = True # for i in range(1, len(s)+1): # for j in range(1, len(p)+1): # if p[j-1] == '?' or s[i-1] == p[j-1]: # dp[i][j] = dp[i-1][j-1] # elif p[j-1] == '*': # dp[i][j] = dp[i-1][j-1] or dp[i-1][j] or dp[i][j-1] # return dp[-1][-1]
''' 1649. Create Sorted Array through Instructions Hard Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The cost of each insertion is the minimum of the following: The number of elements currently in nums that are strictly less than instructions[i]. The number of elements currently in nums that are strictly greater than instructions[i]. For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5]. Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 109 + 7 Example 1: Input: instructions = [1,5,6,2] Output: 1 Explanation: Begin with nums = []. Insert 1 with cost min(0, 0) = 0, now nums = [1]. Insert 5 with cost min(1, 0) = 0, now nums = [1,5]. Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6]. Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6]. The total cost is 0 + 0 + 0 + 1 = 1. https://leetcode.com/problems/create-sorted-array-through-instructions/ ''' from sortedcontainers import SortedList class Solution: def createSortedArray(self, instructions: List[int]) -> int: sortL = SortedList() retVal = 0 for val in instructions: retVal += min(sortL.bisect_left(val), len(sortL) - sortL.bisect_right(val)) retVal %= (10**9 + 7) sortL.add(val) return retVal
''' 735. Asteroid Collision Medium We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. Example 1: Input: asteroids = [5,10,-5] Output: [5,10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. https://leetcode.com/problems/asteroid-collision/ ''' class Solution: def asteroidCollision(self, asteroids: List[int]) -> List[int]: retVal = [] for val in asteroids: if val > 0: retVal.append(val) else: while retVal and retVal[-1] > 0 and retVal[-1] < abs(val): retVal.pop() if not retVal or retVal[-1]<0: retVal.append(val) elif retVal[-1] == abs(val): retVal.pop() return retVal
''' 124. Binary Tree Maximum Path Sum Hard Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. Example 1: Input: [1,2,3] 1 / \ 2 3 Output: 6 https://leetcode.com/problems/binary-tree-maximum-path-sum/ ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right import heapq class Solution: def maxPathSum(self, root: TreeNode) -> int: retlist = [] def helper(node): if not node: return 0 else: l = helper(node.left) r = helper(node.right) intermidiate = max(l+node.val, r+node.val, node.val) heapq.heappush(retlist, -1 * intermidiate) heapq.heappush(retlist, -1 * (l+node.val+r)) return intermidiate helper(root) return heapq.heappop(retlist) * -1
''' 1365. How Many Numbers Are Smaller Than the Current Number Easy Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]. Return the answer in an array. Example 1: Input: nums = [8,1,2,2,3] Output: [4,0,1,1,3] Explanation: For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). For nums[1]=1 does not exist any smaller number than it. For nums[2]=2 there exist one smaller number than it (1). For nums[3]=2 there exist one smaller number than it (1). For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2). https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/ ''' class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: sorted_list = nums[::] sorted_list.sort() dic, k = {}, 0 for i in range(0,len(sorted_list)): if i == 0: dic[sorted_list[i]] = 0 elif sorted_list[i-1] != sorted_list[i]: dic[sorted_list[i]] = k k += 1 retVal = [] for num in nums: retVal.append(dic[num]) return retVal
''' 946. Validate Stack Sequences Medium Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack. Example 1: Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] Output: true Explanation: We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 https://leetcode.com/problems/validate-stack-sequences/ ''' class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack = [] i = 0 for val in pushed: if val == popped[i]: i += 1 while i < len(popped) and stack and stack[-1] == popped[i]: i += 1 stack.pop() else: stack.append(val) if not stack: return True return stack[::-1] == popped[i:]
# Definition for a binary tree node. ''' 1339. Maximum Product of Splitted Binary Tree Medium Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7. Note that you need to maximize the answer before taking the mod and not after taking it. Example 1: Input: root = [1,2,3,4,5,6] Output: 110 Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10) https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/ ''' # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxProduct(self, root: Optional[TreeNode]) -> int: sumVal = 0 lst = [root] while lst: node = lst.pop(0) sumVal += node.val if node.left: lst.append(node.left) if node.right: lst.append(node.right) sumVals = [] def subTreeSum(node): # print(sumVals) if not node: return 0 lsum, rsum = 0, 0 if node.left: lsum = subTreeSum(node.left) if node.right: rsum = subTreeSum(node.right) # print(node.val, lsum, rsum) curVal = node.val + lsum + rsum # print(curVal) sumVals.append(abs(sumVal-curVal)*curVal) return curVal subTreeSum(root) # print(sumVals) return max(sumVals) % (10**9 + 7)
''' 23. Merge k Sorted Lists Hard You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. Example 1: Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4->4->5->6 https://leetcode.com/problems/merge-k-sorted-lists/ ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: arr= [] for i in range(len(lists)): head = lists[i] while head: arr.append(head.val) head = head.next arr.sort() # print(arr) head = temp = ListNode() while arr: temp.next = ListNode(arr.pop(0)) temp = temp.next return head.next # def mergeTwoLists(l1, l2): # """ # :type l1: ListNode # :type l2: ListNode # :rtype: ListNode # """ # curr = dummy = ListNode(0) # while l1 and l2: # if l1.val < l2.val: # curr.next = l1 # l1 = l1.next # else: # curr.next = l2 # l2 = l2.next # curr = curr.next # curr.next = l1 or l2 # return dummy.next # if not lists: # return None # i,j = 0 , len(lists)-1 # while j >0: # if i >= j: # i = 0 # else: # lists[i] = mergeTwoLists(lists[i], lists[j]) # i += 1 # j -= 1 # return lists[0]
''' 594. Longest Harmonious Subsequence Easy We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1. Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences. A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Example 1: Input: nums = [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence is [3,2,2,2,3]. https://leetcode.com/problems/longest-harmonious-subsequence/ ''' class Solution: def findLHS(self, nums: List[int]) -> int: dic = Counter(nums) retVal = 0 for val in dic.keys(): if val+1 in dic: retVal = max(retVal, dic[val+1] + dic[val]) return retVal
''' 390. Elimination Game Medium There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other number afterward until you reach the end of the list. Repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers. We keep repeating the steps again, alternating left to right and right to left, until a single number remains. Find the last number that remains starting with a list of length n. Example: Input: n = 9, 1 2 3 4 5 6 7 8 9 2 4 6 8 2 6 6 Output: 6 https://leetcode.com/problems/elimination-game/ ''' class Solution: def lastRemaining(self, n: int) -> int: return self.helper(n, 1) def helper(self, n , flag): if n==1: return 1 if flag: return 2*self.helper(n//2, 0) elif (n%2): return 2*self.helper(n//2, 1) else: return 2*self.helper(n//2, 1)-1 # Brute Force # arr = range(1, n+1) # while len(arr) > 1: # arr = arr[1::2][::-1] # return arr[0]
''' 60. Permutation Sequence Medium Share The set [1,2,3,...,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 inclusive. Given k will be between 1 and n! inclusive. Example 1: Input: n = 3, k = 3 Output: "213" https://leetcode.com/problems/permutation-sequence/ ''' class Solution: def getPermutation(self, n: int, k: int) -> str: sortedList = list(range(1,n+1)) retVal = "" for i in range(n,0,-1): q = (k-1)//factorial(i-1) k -= q*factorial(i-1) retVal += str(sortedList[q]) sortedList.remove(sortedList[q]) return retVal
''' 1332. Remove Palindromic Subsequences Easy Given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s. Return the minimum number of steps to make the given string empty. A string is a subsequence of a given string, if it is generated by deleting some characters of a given string without changing its order. A string is called palindrome if is one that reads the same backward as well as forward. Example 1: Input: s = "ababa" Output: 1 Explanation: String is already palindrome https://leetcode.com/problems/remove-palindromic-subsequences/ ''' class Solution(object): def removePalindromeSub(self, s): """ :type s: str :rtype: int """ if s == '': return 0 elif s == s[::-1]: return 1 return 2
''' 456. 132 Pattern Medium Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list. Note: n will be less than 15,000. Example 1: Input: [1, 2, 3, 4] Output: False Explanation: There is no 132 pattern in the sequence. https://leetcode.com/problems/132-pattern/ ''' class Solution: def find132pattern(self, nums: List[int]) -> bool: stack = [] minVal = float('-inf') for i in range(len(nums)-1, -1, -1): if nums[i] < minVal: return True while stack and stack[-1] < nums[i]: minVal = stack.pop() stack.append(nums[i]) return False # TLE # if not nums or len(nums) < 3: # return False # minVal = nums[0] # for i in range(1, len(nums)): # if nums[i] > minVal: # for j in range(i+1, len(nums)): # if nums[j] < nums[i] and nums[j] > minVal: # return True # minVal = min(minVal, nums[i]) # return False # Failed attempt # flag = 2 # prev = maxVal = nums[0] # for i in range(1,len(nums)): # print("before", flag, nums[i], prev, maxVal) # if flag == 2: # if nums[i] > prev: # maxVal = nums[i] # flag -= 1 # else: # prev = min(prev, nums[i]) # elif flag == 1: # if nums[i] > prev and nums[i] < maxVal: # flag -=1 # return True # elif nums[i] < prev: # prev = maxVal # maxVal = nums[i] # print("after", flag, nums[i], prev, maxVal) # return False
''' 99. Recover Binary Search Tree Hard Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Example 1: Input: [1,3,null,null,2] 1 / 3 \ 2 Output: [3,1,null,null,2] 3 / 1 \ 2 https://leetcode.com/problems/recover-binary-search-tree/ ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def __init__(self): self.prev = None self.swaplist = [] def recoverTree(self, root): """ :type root: TreeNode :rtype: None Do not return anything, modify root in-place instead. """ self.traversal(root) if len(self.swaplist) == 1: self.swap(self.swaplist[0][0], self.swaplist[0][1]) elif len(self.swaplist) == 2: self.swap(self.swaplist[0][0], self.swaplist[1][1]) def traversal(self, root): if root == None: return self.traversal(root.left) if self.prev and self.prev.val > root.val: self.swaplist.append((self.prev, root)) self.prev = root self.traversal(root.right) def swap(self, val1, val2): val1.val, val2.val = val2.val, val1.val
''' 474. Ones and Zeroes Medium You are given an array of binary strings strs and two integers m and n. Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset. A set x is a subset of a set y if all elements of x are also elements of y. Example 1: Input: strs = ["10","0001","111001","1","0"], m = 5, n = 3 Output: 4 Explanation: The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4. Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}. {"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3. https://leetcode.com/problems/ones-and-zeroes/ ''' class Solution: def findMaxForm(self, strs: List[str], m: int, n: int) -> int: arr = [[s.count('0'), s.count('1')] for s in strs] @lru_cache(None) def dp(i, m, n): if i == len(strs): return 0 retVal = dp(i+1, m, n) if m >= arr[i][0] and n >= arr[i][1]: retVal = max(retVal, dp(i+1, m-arr[i][0], n-arr[i][1]) + 1) return retVal return dp(0, m, n)
''' 916. Word Subsets Medium We are given two arrays A and B of words. Each word is a string of lowercase letters. Now, say that word b is a subset of word a if every letter in b occurs in a, including multiplicity. For example, "wrr" is a subset of "warrior", but is not a subset of "world". Now say a word a from A is universal if for every b in B, b is a subset of a. Return a list of all universal words in A. You can return the words in any order. Example 1: Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","o"] Output: ["facebook","google","leetcode"] https://leetcode.com/problems/word-subsets/ ''' class Solution: def wordSubsets(self, A: List[str], B: List[str]) -> List[str]: bCount = defaultdict(int) for b in B: temp = Counter(b) for key in temp: bCount[key] = max(bCount[key], temp[key]) retVal = [] # print(bCount) for a in A: cntA = Counter(a) fail = False for key in bCount: if key not in cntA or bCount[key] > cntA[key]: print(key) fail = True break if not fail: retVal.append(a) return retVal # TLE # cntArr = [] # for b in B: # cntArr.append(Counter(b)) # retVal = [] # # print(cntArr) # for a in A: # cntA = Counter(a) # fail = False # for dic in cntArr: # for key in dic: # if key not in cntA or dic[key] > cntA[key]: # fail = True # break # if not fail: # retVal.append(a) # return retVal
''' 1313. Decompress Run-Length Encoded List Easy We are given a list nums of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. Return the decompressed list. Example 1: Input: nums = [1,2,3,4] Output: [2,4,4,4] Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2]. The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4]. At the end the concatenation [2] + [4,4,4] is [2,4,4,4]. https://leetcode.com/problems/decompress-run-length-encoded-list/ ''' class Solution: def decompressRLElist(self, nums: List[int]) -> List[int]: result=[] i, times = 0,1 while (i < len(nums)): if i % 2 == 0: times = nums[i] else: tmp = (str(nums[i]) + ',') * times result.append(tmp[:-1]) i += 1 return result # retVal = [] # for i in range(0, len(nums)-1, 2): # val1, val2 = nums[i], nums[i+1] # retVal += [val2] * val1 # return retVal
''' 36. Valid Sudoku Medium Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition. Note: A Sudoku board (partially filled) could be valid but is not necessarily solvable. Only the filled cells need to be validated according to the mentioned rules. Example 1: Input: board = [["5","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] Output: true https://leetcode.com/problems/valid-sudoku/ ''' class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: rows, col, box = defaultdict(set), defaultdict(set), defaultdict(set) for i in range(len(board)): for j in range(len(board[i])): val = board[i][j] if val != '.': if val in rows[i]: return False rows[i].add(val) if val in col[j]: return False col[j].add(val) k = (i//3) * 3 + j//3 if val in box[k]: return False box[k].add(val) return True
''' 430. Flatten a Multilevel Doubly Linked List Medium You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below. Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list. Example 1: Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] Output: [1,2,3,7,8,11,12,9,10,4,5,6] Explanation: We use the multilevel linked list from Example 1 above: 1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL The serialization of each level is as follows: [1,2,3,4,5,6,null] [7,8,9,10,null] [11,12,null] To serialize all levels together we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes: [1,2,3,4,5,6,null] [null,null,7,8,9,10,null] [null,11,12,null] Merging the serialization of each level and removing trailing nulls we obtain: [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/ ''' """ # Definition for a Node. class Node: def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child """ class Solution: def flatten(self, head: 'Node') -> 'Node': temp = head nextQ= [] while temp: if temp.child: if temp.next: nextQ.append(temp.next) temp.next = temp.child temp.child.prev = temp temp.child = None temp = temp.next else: if temp.next: temp = temp.next elif nextQ: val = nextQ.pop(-1) val.prev = temp temp.next = val else: break return head
''' 231. Power of Two Easy Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: true Explanation: 20 = 1 https://leetcode.com/problems/power-of-two/ ''' class Solution: def isPowerOfTwo(self, n: int) -> bool: if n == 0 : return False binary = str(bin(n)[3:]) return binary.count('1') == 0 # if n == 1: # return True # a = 2 # while a <= n: # if n == a: # return True # a*=2 # return False
''' 1658. Minimum Operations to Reduce X to Zero Medium You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it's possible, otherwise, return -1. Example 1: Input: nums = [1,1,4,2,3], x = 5 Output: 2 Explanation: The optimal solution is to remove the last two elements to reduce x to zero. https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/ ''' class Solution: def minOperations(self, nums: List[int], x: int) -> int: total=sum(nums) if total<x: return -1 if total==x: return len(nums) target=total-x curr=0 retVal=-1 i=j=0 for a in nums: curr+=a j+=1 while curr>target: curr-=nums[i] i+=1 j-=1 if curr==target and j>retVal: retVal=j return -1 if retVal==-1 else len(nums)-retVal # b, e, abadB, abadE, retVal = 0 , len(nums) -1, False, False, 0 # while x > 0: # print(b, e, abadB, abadE, retVal, x) # if not abadB: # if e >= b: # if nums[b] >= nums[e] or abadE: # if x-nums[b] >= 0: # x = x-nums[b] # retVal += 1 # b += 1 # else: # abadB = True # else: # abadB = True # if not abadE: # if b <= e: # if nums[e] >= nums[b] or abadB: # if x - nums[e] >= 0: # x = x- nums[e] # retVal += 1 # e -= 1 # else: # abadE = True # else: # abadE = True # if abadE and abadB: # return -1 # return retVal
''' 190. Reverse Bits Easy Reverse bits of a given 32 bits unsigned integer. Example 1: Input: 00000010100101000001111010011100 Output: 00111001011110000010100101000000 Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000. https://leetcode.com/problems/reverse-bits/ ''' class Solution: def reverseBits(self, n: int) -> int: retVal = 0 for i in range(32): retVal = (retVal << 1) + (n & 1) n >>= 1 return retVal
''' 713. Subarray Product Less Than K Medium Your are given an array of positive integers nums. Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k. Example 1: Input: nums = [10, 5, 2, 6], k = 100 Output: 8 Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]. Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k. https://leetcode.com/problems/subarray-product-less-than-k/ ''' class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: i,j, retVal, curr = 0, 0, 0, 1 while j < len(nums): curr *= nums[j] while curr >= k and i <=j: curr/=nums[i] i += 1 retVal += j -i + 1 j +=1 return retVal # i,j, retVal, curr = 0, 0, 0, 0 # while j < len(nums): # if nums[j] < k: # if curr !=0: # if curr*nums[j] < k: # curr *= nums[j] # else: # while i< j and curr*nums[j] >= k: # curr/=nums[i] # i += 1 # curr *= nums[j] # else: # curr = nums[j] # retVal = retVal + (j-i) + 1 # j +=1 # return retVal
''' 880. Decoded String at Index Medium An encoded string S is given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken: If the character read is a letter, that letter is written onto the tape. If the character read is a digit (say d), the entire current tape is repeatedly written d-1 more times in total. Now for some encoded string S, and an index K, find and return the K-th letter (1 indexed) in the decoded string. Example 1: Input: S = "leet2code3", K = 10 Output: "o" Explanation: The decoded string is "leetleetcodeleetleetcodeleetleetcode". The 10th letter in the string is "o". https://leetcode.com/problems/decoded-string-at-index/ ''' class Solution: def decodeAtIndex(self, S: str, K: int) -> str: size = 0 for char in S: if '1' < char <='9': size *= int(char) else: size += 1 for char in reversed(S): K %= size if K == 0 and char.isalpha(): return char if '1' < char <='9': size /= int(char) else: size -= 1 # T L E # i, tmp,cnt = 0, '', 0 # while i <= K and i <len(S): # print(tmp, S, i) # if '1' < S[i] <='9': # tmp = tmp * int(S[i]) # S = tmp + S[i+1:] # i = len(tmp)-1 # else: # tmp += S[i] # i += 1 # print(S) # return S[K-1]
''' 169. Majority Element Easy Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. Example 1: Input: [3,2,3] Output: 3 https://leetcode.com/problems/majority-element/ ''' from collections import Counter class Solution: def majorityElement(self, nums: List[int]) -> int: dic = Counter(nums) for val in dic: if dic[val] > len(nums)//2: return val
''' 1039. Minimum Score Triangulation of Polygon Medium Share Given N, consider a convex N-sided polygon with vertices labelled A[0], A[i], ..., A[N-1] in clockwise order. Suppose you triangulate the polygon into N-2 triangles. For each triangle, the value of that triangle is the product of the labels of the vertices, and the total score of the triangulation is the sum of these values over all N-2 triangles in the triangulation. Return the smallest possible total score that you can achieve with some triangulation of the polygon. Example 1: Input: [1,2,3] Output: 6 Explanation: The polygon is already triangulated, and the score of the only triangle is 6. https://leetcode.com/problems/minimum-score-triangulation-of-polygon/ ''' class Solution(object): def minScoreTriangulation(self, A): """ :type A: List[int] :rtype: int """ arr = [[0] * len(A) for i in xrange(len(A))] for point in xrange(2, len(A)): for i in xrange(len(A) - point): j = i + point arr[i][j] = min(arr[i][k] + arr[k][j] + A[i] * A[j] * A[k] for k in xrange(i + 1, j)) return arr[0][len(A) - 1] # retVal = [] # for i in range(len(A)): # minus = False # if i == len(A)-1: # if A[i-1] < A[0]: # sec= A[i-1] # minus = True # else: # sec = A[0] # tempsec = sec # sec = sec * A[i] # if minus: # third = min(A[:i-2]) # else: # third = min(A[1:i]) # else: # if A[i-1] < A[i+1]: # sec= A[i-1] # minus = True # else: # sec = A[i+1] # tempsec = sec # sec = sec * A[i] # if minus: # if i ==0: # third = min(A[i+1:i-1]) # else: # third = min(A[:i-1] + A[i+1:]) # else: # third = min(A[:i] + A[i+2:]) # print(A[i], tempsec, third) # retVal.append(sec * third) # print(retVal) # return retVal
''' 140. Word Break II Hard Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. Note: The same word in the dictionary may be reused multiple times in the segmentation. You may assume the dictionary does not contain duplicate words. Example 1: Input: s = "catsanddog" wordDict = ["cat", "cats", "and", "sand", "dog"] Output: [ "cats and dog", "cat sand dog" ] https://leetcode.com/problems/word-break-ii/ ''' class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: wordLets = set(''.join(wordDict)) wordDict = set(wordDict) #Fast lookup stringLets = set(s) if stringLets - wordLets: return [] retVal = [] n = len(s) def dfs(temp = [], index = 0): if index == n: retVal.append(' '.join(temp)) return for i in range(index, n+1): if s[index:i] in wordDict: dfs(temp+[s[index:i]], i) dfs() return retVal
''' 154. Find Minimum in Rotated Sorted Array II Hard Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). Find the minimum element. The array may contain duplicates. Example 1: Input: [1,3,5] Output: 1 https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ ''' class Solution: def findMin(self, nums: List[int]) -> int: retVal = nums[0] for i in range(1, len(nums)): if nums[i] < retVal: retVal = nums[i] return retVal
''' 394. Decode String Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. Example 1: Input: s = "3[a]2[bc]" Output: "aaabcbc" https://leetcode.com/problems/decode-string/ ''' class Solution: def decodeString(self, s: str) -> str: retVal,val, temp, i = '', [], [], 0 while i < len(s): char = s[i] if '0' < char <= '9': tempVal = '' while '0' <= s[i] <= '9': tempVal += s[i] i += 1 val.append(int(tempVal)) temp.append('') elif char == ']': if len(temp) > 1: temp[-2] += temp[-1]*val[-1] else: retVal += temp[-1]*val[-1] val.pop() temp.pop() elif char == '[': i += 1 continue elif len(val) > 0: temp[-1] += char else: retVal += char i += 1 return retVal
''' 201. Bitwise AND of Numbers Range Medium Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. Example 1: Input: [5,7] Output: 4 https://leetcode.com/problems/bitwise-and-of-numbers-range/ ''' class Solution: def rangeBitwiseAnd(self, m: int, n: int) -> int: while(m<n): n = n &(n-1) return n # if m == n: # return m # retVal,a,b = 1,m,n # while a > 1: # a = a//2 # b = b//2 # retVal *= 2 # if a==b and a==1: # return retVal # else: # return 0
''' 95. Unique Binary Search Trees II Medium Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order. Example 1: Input: n = 3 Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]] https://leetcode.com/problems/unique-binary-search-trees-ii/ ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def generateTrees(self, n: int) -> List[Optional[TreeNode]]: if n == 0: return [] if n == 1: return [TreeNode(1)] dp = {} def helper(l, r): nonlocal dp if (l,r) in dp: return dp[(l,r)] if l > r: return [None] trees = [] for root in range(l, r+1): for left in helper(l, root-1): for right in helper(root+1, r): node = TreeNode(root) node.left = left node.right = right trees.append(node) dp[(l,r)] = trees return trees return helper(1, n)
''' 1026. Maximum Difference Between Node and Ancestor Medium Given the root of a binary tree, find the maximum value V for which there exist different nodes A and B where V = |A.val - B.val| and A is an ancestor of B. A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B. Example 1: Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] Output: 7 Explanation: We have various ancestor-node differences, some of which are given below : |8 - 3| = 5 |3 - 7| = 4 |8 - 1| = 7 |10 - 13| = 3 Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7. https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/ ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxAncestorDiff(self, root: TreeNode) -> int: if not root: return 0 def helper(root, temp_max, temp_min): if not root: return temp_max - temp_min temp_max = max(temp_max, root.val) temp_min = min(temp_min, root.val) l_val = helper(root.left, temp_max, temp_min) r_val = helper(root.right, temp_max, temp_min) return max(l_val, r_val) return helper(root, root.val, root.val)
''' 589. N-ary Tree Preorder Traversal Easy Given an n-ary tree, return the preorder traversal of its nodes' values. For example, given a 3-ary tree: Return its preorder traversal as: [1,3,5,6,2,4]. Note: Recursive solution is trivial, could you do it iteratively? https://leetcode.com/problems/n-ary-tree-preorder-traversal/ ''' """ # Definition for a Node. class Node: def __init__(self, val, children): self.val = val self.children = children """ class Solution: def preorder(self, root: 'Node') -> List[int]: if not root: return [] l, retVal = [], [] l.append(root) while len(l): k =l.pop(0) retVal.append(k.val) if k.children: l = k.children + l return retVal
''' 463. Island Perimeter Easy You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. Example: Input: [[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] Output: 16 Explanation: The perimeter is the 16 yellow stripes in the image below: https://leetcode.com/problems/island-perimeter/ ''' class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: retVal = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: retVal += 4 if i > 0 and grid[i-1][j] == 1: retVal -= 2 if j > 0 and grid[i][j-1] == 1: retVal -= 2 return retVal # self.retVal = 0 # visited = [[0 for _ in range(len(grid[0]))] for _ in range(len(grid))] # for i in range(len(grid)): # for j in range(len(grid[i])): # if grid[i][j]: # self.dfs(i, j, grid, visited) # return self.retVal # # def dfs(self, i, j, grid, visited): # if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[i]): # self.retVal += 1 # return # if visited[i][j]: # return # else: # if grid[i][j] == 1: # visited[i][j] = 1 # for val in [(-1,0),(1,0),(0,-1),(0,-1)]: # self.dfs(i+val[0], j + val[1], grid, visited) # else: # self.retVal += 1
''' 143. Reorder List Medium Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You may not modify the values in the list's nodes, only nodes itself may be changed. Example 1: Given 1->2->3->4, reorder it to 1->4->2->3. https://leetcode.com/problems/reorder-list/ ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ lst = [] cur = head while(cur): lst.append(cur) cur = cur.next lst1 = lst[:len(lst)//2] lst2 = lst[len(lst)//2:] lst2.reverse() lst = [] for i in range(len(lst2)): try: lst.append(lst1[i]) except IndexError: pass lst.append(lst2[i]) for i in range(len(lst)): try: lst[i].next = lst[i+1] except IndexError: lst[i].next = None
''' 966. Vowel Spellchecker Medium Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word. For a given query word, the spell checker handles two categories of spelling mistakes: Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist. Example: wordlist = ["yellow"], query = "YellOw": correct = "yellow" Example: wordlist = ["Yellow"], query = "yellow": correct = "Yellow" Example: wordlist = ["yellow"], query = "yellow": correct = "yellow" Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist. Example: wordlist = ["YellOw"], query = "yollow": correct = "YellOw" Example: wordlist = ["YellOw"], query = "yeellow": correct = "" (no match) Example: wordlist = ["YellOw"], query = "yllw": correct = "" (no match) In addition, the spell checker operates under the following precedence rules: When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back. When the query matches a word up to capitlization, you should return the first such match in the wordlist. When the query matches a word up to vowel errors, you should return the first such match in the wordlist. If the query has no matches in the wordlist, you should return the empty string. Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i]. Example 1: Input: wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"] Output: ["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"] https://leetcode.com/problems/vowel-spellchecker/ ''' class Solution: def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: exact_word = set(wordlist) words_case = {} words_vowels = {} for word in wordlist: wordlower = word.lower() words_case.setdefault(wordlower, word) wordMasked = "".join('*' if c in 'aeiou' else c for c in wordlower) words_vowels.setdefault(wordMasked, word) # print(words_case,words_vowels) retVal = [] for query in queries: # print(retVal) if query in exact_word: retVal.append(query) # print(query) continue wordlower = query.lower() if wordlower in words_case: # print(wordlower) retVal.append(words_case[wordlower]) continue wordMasked = "".join('*' if c in 'aeiou' else c for c in wordlower) if wordMasked in words_vowels: # print(wordMasked) retVal.append(words_vowels[wordMasked]) continue retVal.append("") return retVal
''' 404. Sum of Left Leaves Easy Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. https://leetcode.com/problems/sum-of-left-leaves/ ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: def helper(root): if root is None: return 0 sumVal = 0 if root.left is not None and root.left.left is None and root.left.right is None : sumVal = root.left.val return sumVal + helper(root.left) + helper(root.right) if root is None : return 0 return helper(root) ''' retVal = {'val': 0} def helper(node): if not node.left and not node.right: retVal['val'] += node.val if not root: return 0 lst = [root] while lst: node = lst.pop() if node.left: helper(node.left) lst.append(node.left) if node.right: lst.append(node.right) return retVal['val'] '''
for i in range(0,100): if i % 15 == 0: print "beep boop" elif i % 5 == 0: print "boop" elif i % 3 == 0: print "beep" else: print i
a=input(" ") b=a[::-1] if (a==b): print("yes") else: print("no")
from math import pi var1=10 def greeting(x,y): z="Hello, "+x+" "+y return z def sphere_volume(x): x=float(x) y=4/3*(pi)*(x**3) return y
magicians = ["amy", "lucy", "jimmy"] for magician in magicians: print(magician) """ output: amy lucy jimmy """ #Regular Errors: #IndentationError: expected an indented block #IndentationError: unexpected indent #SyntaxError: invalid syntax for value in range(1,5): print(value) # output : 1,2,3,4 # if we want the output is 1,2,3,4,5 # then we need rang(1,6) instead #creating a list of # numbers = list(range(1,6)) print(numbers)#[1, 2, 3, 4, 5] even_numbers = list(range(2,11,2)) print(even_numbers) #[2, 4, 6, 8, 10] squares = [] for value in range(1,11): square = value**2 squares.append(square) #squares.append(value**2) print(squares) #simple form squares = [value**2 for value in range(1,11)] print(squares) """ output: [1] [1, 4] [1, 4, 9] [1, 4, 9, 16] [1, 4, 9, 16, 25] [1, 4, 9, 16, 25, 36] [1, 4, 9, 16, 25, 36, 49] [1, 4, 9, 16, 25, 36, 49, 64] [1, 4, 9, 16, 25, 36, 49, 64, 81] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] """ digits = [1,2,3,4,5,6,7,8,9,0] print(min(digits))#min number print(max(digits))#max number print(sum(digits))#sum of all numbers in digits squares = [value**2 for value in range(1,11)] print(squares) #copy list my_foods =['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[1:] print(my_foods) print(friend_foods) dimensions = (200, 50) for dimension in dimensions: print(dimension) dimensions = (400,100) for dimension in dimensions: print(dimension) # we can't change Tuple
# Review for input() and while loop message = raw_input("Tell me something, and I will repeat it back to you: ") print(message) name = raw_input("Please enter your name: ") print("Hello, " + name + "!") prompt = "If you tell us who you are, we can personalize the messages you see." prompt += "\nWhat is your first name? " name = raw_input(prompt) print("\nHello, " + name + "!") age = raw_input("how old are you?") age = int(age) print(age>=18) """ for python 2.7 we use raw_input() instead of input() """