text
stringlengths
37
1.41M
import json filename = 'favorite_number.json' try: with open(filename) as f: favorite_number = json.load(f) except FileNotFoundError: with open(filename, 'w') as f: prompt = "Let me know your favorite number: " favorite_number = input(prompt) json.dump(favorite_number, f) print("Number saved.") else: prompt = "I know your favorite number!" prompt += " It's " + favorite_number + '.' print(prompt)
def word_counter(filename, word): try: with open(filename) as f: contents = f.read() except FileNotFoundError: print("The file doesn't exist. Please check it again!") else: times = contents.lower().count(word) print("The word '%s' appears %i times in this file." % (word, times)) filename = 'alice.txt' word_counter(filename, 'alice')
while True: try: a = input("Input A('q' for quit): ") if a != 'q': a = int(a) else: break b = input("Input B('q' for quit): ") if b != 'q': b = int(b) else: break except ValueError: print("You must input only integers!") else: sum = a + b print("The sum of %i and %i is %i.\n" % (a, b, sum))
from string import ascii_lowercase import itertools ouija=[] a=int(input()) for i,c in zip(range(1,27),ascii_lowercase): if len(ouija)==a: break for j in range (1,i+1): ouija.append(i) if len(ouija)==a: break for k in range (1,i+1): ouija.append(c) if len(ouija)==a: break print(ouija[a-1])
from Interface import Beverage, AbstractFactory class IcedTea(Beverage): def make(self): print("Making iced tea!") def sip(self): print("Sip iced tea!") class HotTea(Beverage): def make(self): print("Making hot tea!") def sip(self): print("Sip hot tea!") class TeaFactory(AbstractFactory): def getBeverage(self, type='hot'): if type.lower() == 'hot': return HotTea() elif type.lower() == 'cold': return IcedTea()
#!/usr/bin/python class CharGrid(dict): """ Grid of single characters for drawing ascii art. Keys are (row,col) """ def __init__(self): self.maxRow = 0 # total number of rows self.maxCol = 0 # total number of cols self._defaultVal = ' ' def __checkkey(self,key): """ Make sure key is a valid key """ if not isinstance(key,tuple): raise Exception("Key must be 2-tuple, got %r"%key) if not len(key) == 2: raise Exception("Key must be 2-tuple, got %d-tuple"%len(key)) if not (isinstance(key[0],int) and isinstance(key[1],int)): raise Exception("Key value must be of type (int,int), got (%s,%s)"%(key[0].__class__.__name__,key[1].__class__.__name__)) def __getitem__(self,key): """ Get a single character from the grid """ self.__checkkey(key) # If value does not already exist - send back default value # Increase our 'size' to report if necessary # Don't add it though - this unnecessarily increases the size if not key in self: self.maxRow = max(key[0],self.maxRow) self.maxCol = max(key[1],self.maxCol) return self._defaultVal return super(CharGrid,self).__getitem__(key) def __setitem__(self,key,val): """ Set a single character or string into the grid starting at key""" self.__checkkey(key) if not isinstance(val,str): raise Exception("Val must be 'str', got %r"%val) if len(val) < 1: raise Exception("Val must be at least 1 character long, got %d (%s)"%(len(val),val)) cOffset = 0 for c in val: row = key[0] col = key[1]+cOffset # Update size values if necessary if not (row,col) in self: self.maxRow = max(row,self.maxRow) self.maxCol = max(col,self.maxCol) # Set value super(CharGrid,self).__setitem__((row,col),c) cOffset += 1 def insertRowsAbove(self,row,num): """ add a new row above 'row' (shifting existing rows down) """ keys = filter(lambda k: k[0] >= row,self.keys()) self.__moveCells(keys,(num,0)) def insertColsToLeft(self,col,num): """ add a new column to the left of 'col' (shifting existing cols right """ keys = filter(lambda k: k[1] >= col,self.keys()) self.__moveCells(keys,(0,num)) def __moveCells(self,keys,direction): """ Called by insertRowAbove... Moves all cells in 'keys' in 'direction'. Each key is 'keys' specified by (row,col). Direction specified by (rowOffset,colOffset). """ while len(keys) > 0: keys = self.__moveCell(keys[0],keys,direction) def __moveCell(self,srcKey,keys,direction): """ Called by __moveCells - recursively moves cells to move srcKey cell """ self.__checkkey(srcKey) self.__checkkey(direction) destKey = (srcKey[0]+direction[0],srcKey[1]+direction[1]) # If destination already exists if destKey in self: keys = self.__moveCell(destKey,keys,direction) # copy contents and pop key from self and tmp keylist self[destKey] = self[srcKey] self.pop(srcKey) keys.pop(keys.index(srcKey)) return keys def __str__(self): imgbuf = "" for r in range(self.maxRow+1): rowbuf = list() for c in range(self.maxCol+1): rowbuf.append(self[(r,c)]) imgbuf+= "".join(rowbuf)+"\n" return imgbuf
import random winning_num=random.randint(1,10) print("WELCOME TO Number guessing game: guess the number between 1 to 10") Player1=input("Enter Player1 name:") Player2=input("Enter Player2 name:") num1=int(input(f"{Player1} enter number:")) num2=int(input(f"{Player2} enter number:")) game_over=False guess1=0 guess2=0 while not game_over: guess1 += 1 guess2 += 1 if (num1==winning_num and num2==winning_num): print(f"{Player1} you win, you guessed {guess1} times") print(f"{Player2} you win, you guessed {guess2} times") break elif (num1==winning_num and num2<winning_num): win1=(f"{Player1} you win, you guessed {guess1} times") print(win1) print(f"{Player2} your guess is low") num2=int(input(f"{Player2} guess again:")) game_over = True while game_over: guess2 += 1 if num2==winning_num: win2=(f"{Player2} you win, you guessed {guess2} times") print(win2) break elif num2<winning_num: print(f"{Player2} your guess is low") num2=int(input(f"{Player2} guess again:")) elif num2>winning_num: print(f"{Player2} your guess is high") num2=int(input(f"{Player2} guess again:")) elif (num1==winning_num and num2>winning_num): win1=(f"{Player1} you win, you guessed {guess1} times") print(win1) print(f"{Player2} your guess is high") num2=int(input(f"{Player2} guess again:")) game_over = True while game_over: guess2 += 1 if num2==winning_num: win2=(f"{Player2} you win, you guessed {guess2} times") print(win2) break elif num2<winning_num: print(f"{Player2} your guess is low") num2=int(input(f"{Player2} guess again:")) elif num2>winning_num: print(f"{Player2} your guess is high") num2=int(input(f"{Player2} guess again:")) elif (num1<winning_num and num2==winning_num): win2=(f"{Player2} you win, you guessed {guess2} times") print(win2) print(f"{Player1} your guess is low") num1=int(input(f"{Player1} guess again:")) game_over = True while game_over: guess1 += 1 if num1==winning_num: win1=(f"{Player1} you win, you guessed {guess1} times") print(win1) break elif num1<winning_num: print(f"{Player1} your guess is low") num1=int(input(f"{Player1} guess again:")) elif num1>winning_num: print(f"{Player1} your guess is high") num1=int(input(f"{Player1} guess again:")) elif (num1>winning_num and num2==winning_num): win2=(f"{Player2} you win, you guessed {guess2} times") print(win2) print(f"{Player1} your guess is high") num1=int(input(f"{Player2} guess again:")) game_over = True while game_over: guess1 += 1 if num1==winning_num: win1=(f"{Player1} you win, you guessed {guess1} times") print(win1) break elif num1<winning_num: print(f"{Player1} your guess is low") num1=int(input(f"{Player1} guess again:")) elif num1>winning_num: print(f"{Player1} your guess is high") num1=int(input(f"{Player1} guess again:")) elif (num1<winning_num and num2<winning_num): print(f"{Player1} your guess is low") print(f"{Player2} your guess is low") num1=int(input(f"{Player1} guess again:")) num2=int(input(f"{Player2} guess again:")) elif (num1<winning_num and num2>winning_num): print(f"{Player1} your guess is low") print(f"{Player2} your guess is high") num1=int(input(f"{Player1} guess again:")) num2=int(input(f"{Player2} guess again:")) elif (num1>winning_num and num2>winning_num): print(f"{Player1} your guess is high") print(f"{Player2} your guess is high") num1=int(input(f"{Player1} guess again:")) num2=int(input(f"{Player2} guess again:")) elif (num1>winning_num and num2<winning_num): print(f"{Player1} your guess is high") print(f"{Player2} your guess is low") num1=int(input(f"{Player1} guess again:")) num2=int(input(f"{Player2} guess again:")) if game_over: print("\nFinal score:") print(win1) print(win2) print("\nFinal result:") if (guess1<guess2): print(f"{Player1} you win") elif (guess1>guess2): print(f"{Player2} you win") elif (guess1==guess2): print("Both are winner")
import pandas as pd import matplotlib.pyplot as plt def create_chart(): df = pd.read_excel("portfolio.xlsx", "Érték") # columns of dates and portfolio value dates_vs = df['Dátum'] values = df['Portfolió Érték'] # It defines the style of figure plt.style.use('seaborn-darkgrid') plt.plot_date(dates_vs, values, linestyle='solid') # It rotates and formats dates on x axis plt.gcf().autofmt_xdate() #plt.title("Portfolió Értékének Alakulása") plt.ylabel("Portfólió Értéke (USD)") # Adjusts the padding plt.tight_layout() # it displays the figure #plt.show() # it saves the figure in png plt.savefig("chart.png") #create_chart()
# -*- coding: utf-8 -*- """ Created on Thu Apr 8 17:09:13 2021 @author: Tony Zhou """ # -*- coding: utf-8 -*- """ Created on Thu Apr 8 16:46:56 2021 @author: Tony Zhou """ from collections import defaultdict class Graph: def __init__(self, graph): self.graph = graph self. ROW = len(graph) # Using BFS as a searching algorithm def searching_algo_BFS(self, s, t, parent): visited = [False] * (self.ROW) queue = [] queue.append(s) visited[s] = True while queue: u = queue.pop(0) for ind, val in enumerate(self.graph[u]): if visited[ind] == False and val > 0: queue.append(ind) visited[ind] = True parent[ind] = u return True if visited[t] else False # Applying fordfulkerson algorithm def ford_fulkerson(self, source, sink): parent = [-1] * (self.ROW) max_flow = 0 while self.searching_algo_BFS(source, sink, parent): path_flow = float("Inf") s = sink while(s != source): path_flow = min(path_flow, self.graph[parent[s]][s]) s = parent[s] # Adding the path flows max_flow += path_flow # Updating the residual values of edges v = sink while(v != source): u = parent[v] self.graph[u][v] -= path_flow self.graph[v][u] += path_flow v = parent[v] return max_flow def takeInput(): fl = input() fl = fl.split(' ') num_nuts = int(fl[0]) num_bolts = int(fl[1]) bolt_status = [] for i in range(num_nuts): temp = input() temp = temp.split(' ') bolt_status.append(split(temp)) return bolt_status,num_nuts,num_bolts def redraw_Graph(bst,nn,nb): length = nn + nb + 2 graph = [] # add source and sink to the graph info source = [] sink = [] # firstly build source and sink node for i in range(length): source.append(0) sink.append(0) for i in range(nn+1): if i == 0: continue else: source[i] = 1 graph.append(source) # Then construct the part where nut nodes are directed to bolt nodes middleBlock = [] for i in range(nn): tempNode = [] for j in range(length): if j <= nn: tempNode.append(0) elif j == length-1: tempNode.append(0) else: col=j-(nn+1) tempNode.append(int(bst[i][j-(nn+1)])) graph.append(tempNode) middleBlock.append(tempNode) # Then construct the slots node that direct to the sink endBlock = [] for i in range(nb): tempNode = [] for j in range(length): if j == length-1: tempNode.append(1) else: tempNode.append(0) graph.append(tempNode) endBlock.append(tempNode) # Finally build up the graph with source, middlepart graph.append(sink) return graph def split(word): return [char for char in word] def driver(): bst,nn,nb = takeInput() s = 0 t = nn+nb+1 g = redraw_Graph(bst, nn, nb) graph = Graph(g) print(graph.ford_fulkerson(s,t)) if __name__ == "__main__": driver()
# Artificial Neural Networks # Part 1 - Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('churn_modelling_ann.csv') X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, -1].values # Encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelEncoder_X1 = LabelEncoder() labelEncoder_X2 = LabelEncoder() X[:, 1] = labelEncoder_X1.fit_transform(X[:, 1]) X[:, 2] = labelEncoder_X2.fit_transform(X[:, 2]) oneHotEncoder = OneHotEncoder(categorical_features=[1]) X = oneHotEncoder.fit_transform(X).toarray() X = X[:, 1:] # Spliting the dataset into the Training set & Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) #--------------------------------------------------------- # Part 2 - Making the Artificial Neural Networks #--------------------------------------------------------- # Importing the Keras libraries and packages import keras from keras.models import Sequential from keras.layers import Dense, Dropout # Initialising the ANN classifier = Sequential() # Adding the input layer (input_dim) and the first hidden layer (units) with dropout classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11)) classifier.add(Dropout(rate = 0.1)) # Adding the second hidden layer with dropout classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu')) classifier.add(Dropout(rate = 0.1)) # Adding the output layer classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid')) # Compiling the ANN classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # Fitting the ANN to the Training set classifier.fit(X_train, y_train, batch_size = 10, epochs = 100) #--------------------------------------------------------- # Part 3 - Making the predictions and evaluating the model #--------------------------------------------------------- # Predicting the Test set results y_pred = classifier.predict(X_test) y_pred = (y_pred > 0.5) # Predicting a single new observation """Predict if the customer with the following informations will leave the bank: Geography: France Credit Score: 600 Gender: Male Age: 40 Tenure: 3 Balance: 60,000 Number of Products: 2 Has Credit Card: Yes Is Active Member: Yes Estimated Salary: 50,000 """ new_prediction = classifier.predict( sc_X.transform(np.array([ [0.0, 0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000] ])) ) new_prediction = (new_prediction > 0.5) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) #--------------------------------------------------------- # Part 4 - Evaluating, Improving and Tuning the ANN #--------------------------------------------------------- # Evaluating the ANN from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score from keras.models import Sequential from keras.layers import Dense def build_classifier(): classifier = Sequential() classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11)) classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu')) classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid')) classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) return classifier classifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, epochs = 100) accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10) mean = accuracies.mean() variance = accuracies.std() # Improving the ANN # Dropout regularization to reduce overfitting if needed # Tuning the ANN from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import GridSearchCV from keras.models import Sequential from keras.layers import Dense def build_classifier(optimizer): classifier = Sequential() classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11)) classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu')) classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid')) classifier.compile(optimizer = optimizer, loss = 'binary_crossentropy', metrics = ['accuracy']) return classifier classifier = KerasClassifier(build_fn = build_classifier) parameters = { 'batch_size' : [25, 32], 'epochs' : [100, 500], 'optimizer' : ['adam', 'rmsprop'] } grid_search = GridSearchCV(estimator = classifier, param_grid = parameters, scoring = 'accuracy', cv = 10) grid_search = grid_search.fit(X_train, y_train) best_parameters = grid_search.best_params_ best_accuracy = grid_search.best_score_
""" This file has functions to generate addition facts at random, of the form '3 + 4 = ___' and '3 + ___ = 7'. Within a python session from the same folder that the file is in, load the library with: from mathfacts import * then use the mathproblem_series function to generate n problems with: mathproblem_series(n) or mathproblem_series() for a default of n=20 problems. """ def mathproblem(a,b,left=False): """ writes an equation for the math fact a+b=c in which the empty spot is on the right (c is unknown), or on the left if left is True (b is unknown). In other words, the equation is: a + b = ___ or a + ___ = c Examples: >>> mathproblem(1,4) '1 + 4 = __' >>> mathproblem(1,4,True) '1 + __ = 5' """ c = a+b s = str(a) + " + " if left: s += "__ = " + str(c) else: s += str(b) + " = __" return s import random def mathproblem_series(n = 20): """ print a series of n math problems, randomly generated with integers in 1-10. Example: >>> random.seed(4321) # for reproducibility when testing >>> mathproblem_series(n=4) 1. 5 + __ = 6 2. 2 + __ = 5 3. 2 + 1 = __ 4. 10 + __ = 11 """ s = '' for i in range(0,n): a = random.randrange(1,11) # from 1: to avoid easy problems 0 + b = __ # to 10: to include 10 + b = __ b = random.randrange(1,11) left = bool(random.randrange(0,2)) if i>0: s += "\n" s += str(i+1) + ". " + mathproblem(a,b,left) print(s) return None
# !/usr/bin/python3 # -*- coding:utf-8 -*- # author: Ming Luo # time: 2020/9/4 13:51 # 假设两个线程t1和t2都要对全局变量g_num(默认是0)进行加1运算,t1和t2都各对g_num加10次,g_num的最终结果应该为20 # 但是由于是多线程同时操作,有可能出现下面情况: # 1. 在g_num=0时,t1取得g_num=0.此时系统把t1调度为"sleeping"状态,把t2转换为"running"状态,t2也获得g_num=0 # 2. 然后t2对得到的值进行加1并赋给g_num,使得g_num=1 # 3. 然后系统又把t2调度为"sleeping",把t1转为"running"线程t1又把它之前得到的0加1后赋值给g_num。 # 4. 这样导致虽然t1和t2都对g_num加1,但结果仍然是g_num=1 import threading import time g_num = 0 def work1(num): global g_num for i in range(num): g_num += 1 print("work1:", g_num) def work2(num): global g_num for i in range(num): g_num += 1 print("work2:", g_num) def main(): t1 = threading.Thread(target=work1, args=(1000000,)) t2 = threading.Thread(target=work2, args=(1000000,)) t1.start() t2.start() time.sleep(5) print("result:", g_num) if __name__ == '__main__': main() # work1: 1156620 # work2: 1241692 # result: 1241692 # 产生资源竞争,最终得不到正确结果
# !/usr/bin/python3 # -*- coding:utf-8 -*- # author: Ming Luo # time: 2020/9/8 15:40 class Fibonacci: def __init__(self, all_num): self.all_num = all_num self.current_num = 0 self.a = 0 self.b = 1 def __iter__(self): return self def __next__(self): if self.current_num < self.all_num: ret = self.a self.a, self.b = self.b, self.a + self.b self.current_num += 1 return ret else: raise StopIteration fibo = Fibonacci(10) for num in fibo: print(num) list(num) # 也是通过迭代取当中的值,然后再放入list中返回 tuple(num) # 也是通过迭代取当中的值,然后再放入tuple中返回
def convert(num): raind = "" if (num % 3 == 0): raind = raind + "Pling" if (num % 5 == 0): raind = raind + "Plang" if (num % 7 == 0): raind = raind + "Plong" if (raind == ""): return str(num) else: return raind
#!/usr/bin/python3 # -*- coding: utf-8 -*- # overload_print.py # DISCLAIMER DO NOT USE THIS CODE # overloads the print statement # # https://github.com/w13b3/do_not_use-py/tree/master/overload_print # # usage: # from overload_print import print import logging from typing import Optional, Any, Union, TextIO, NoReturn def print(*args: Any, level: Union[str, int] = 'DEBUG', sep: Optional[str] = ' ', end: Optional[str] = None, file: TextIO = None, flush: bool = False) -> NoReturn: """ print overloading and logger in one method. using logger.log for overloading print statements so your code can log to see something in the python console use the following just under the imports: import logging logging.basicConfig(level=logging.DEBUG) more info see: help(logging.log) help(print) arguments: :param args: everything print() usually can handle. :type args: Any optional keyword arguments: :param level: logging levels as strings or as integers :type level: Union[int, str] :param sep: string inserted between values, default a space. :type sep: str :raises TypeError: When kwarg sep is not a string :param end: string appended after the last value, default a newline. :type end: str :raises TypeError: When kwarg end is not a string :param file: a file-like object (stream). :type file: TextIO :raises AttributeError: if the file has no attribute 'write' :param flush: whether to forcibly flush the stream. :type flush: bool :return: print returns nothing :rtype: None """ # keyword contracts if not isinstance(sep, (str, type(None))): # sep must be None or a string raise TypeError(f'sep must be None or a string, not {type(sep).__qualname__}') if not isinstance(end, (str, type(None))): # end must be None or a string raise TypeError(f'end must be None or a string, not {type(end).__qualname__}') if file is not None and not hasattr(file, 'write'): raise AttributeError(f"{type(file).__qualname__!r} object has no attribute 'write'") print_message = str(sep).join([str(arg) for arg in args]) # separate arguments _end = '' if end is None else end # if end is given, use that. else use an empty string # append end character anti __magic__ tamper wise by using a class variable print_message = type('', (object,), {'get_value': f'{print_message}{_end}'}).get_value if len(args) <= 0: # if the length of the arguments are zero print a blank line return getattr(__import__('builtins'), 'print')(end='\n', file=file, flush=flush) # not recursive if file is not None: file_end = '' if bool(_end) else '\n' # write-to-file end is usually a '\n' try: # try to write to the file file.write(f'{print_message}{file_end}') except Exception as e: # could not open or write to the file logging.exception(e, print) # log the exception if isinstance(level, str): # if the level parameter is a string level = int(getattr(logging, level.strip().upper())) # get the equivalent logging int if bool(flush): # force to flush the stream getattr(__import__('sys'), 'stdout').flush() logging.log(level, str(print_message)) # -> None if __name__ == '__main__': """ Local confidence test """ from contextlib import suppress logging.basicConfig(level=logging.DEBUG) # logging.getLogger().addHandler(logging.StreamHandler()) builtin_print = getattr(__import__('builtins'), 'print') print('debug', 'no arguments') print() # do not log an print without arguments print('level', 'eciN'[::-1], level=69) print('critical', level='critical') print('error', level='ErroR ') # <- yes this works print('warning', level='warning') print('info', level=logging.INFO) print('debug', level='debug') print('notset', level='notset') def adbmal(n: int) -> int: return n + n * n // n print(adbmal(5), print( '', f'{builtin_print!r}', f'{print!r}', False, None, float(000_000.000_1), int(100_000), 5j, list('list'), tuple('tuple'), (type(tuple('None')),), {'s', 'e', 't'}, {'dict': 'ionary', }, type(type), '\N{Wavy Dash}', sep='\n\t', end='\n \U0001F600' )) # test the keyword contracts sep_, end_, file_ = range(3) with suppress(TypeError): print(None, sep=0) sep_ = f'sep is not suppressed' with suppress(TypeError): print(None, end=1) end_ = f'end is not suppressed' with suppress(AttributeError): print(None, file=2) file_ = f'file is not suppressed' # if done correctly nothing happens. print(sep_, end_, file_) if not (sep_, end_, file_) == (*range(3),) else None
#!/usr/bin/python from time import sleep a = 5 b = 0 def meth(c): print("GIRAFFE") sleep(c) print("DUCK") sleep(c) while b<a: meth(2) b = b + 1 print(";D")
#importing libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt #loading dataset dataset = pd.read_csv('dataset.csv') #summarizing dataset print(dataset.shape) print(dataset.head(5)) #Segregating Dataset into Input X & Output Y X = dataset.iloc[:, :-1].values X Y = dataset.iloc[:, -1].values Y #Splitting Dataset for Testing our Model from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test = train_test_split(X,Y,test_size=0.20,random_state=0) #Training Dataset using Decision Tree from sklearn.tree import DecisionTreeRegressor model = DecisionTreeRegressor() model.fit(x_train, y_train) #Visualizing Graph X_val = np.arange(min(x_train), max(x_train), 0.01) X_val = X_val.reshape((len(X_val), 1)) plt.scatter(x_train, y_train, color = 'green') plt.plot(X_val, model.predict(X_val), color = 'red') plt.title('Height prediction using DecisionTree') plt.xlabel('Age') plt.ylabel('Height') plt.figure() plt.show() #Prediction for all test data for validation ypred = model.predict(x_test) from sklearn.metrics import r2_score,mean_squared_error mse = mean_squared_error(y_test,ypred) rmse=np.sqrt(mse) print("Root Mean Square Error:",rmse) r2score = r2_score(y_test,ypred) print("R2Score",r2score*100)
import sys import time import random import datetime def slowprt(str): for char in str: sys.stdout.write(char) sys.stdout.flush() time.sleep(.06) if char == ',': time.sleep(.3) if char in ".?!": time.sleep(.6) exit_prompts = ["bye now!", "see you soon.", "goodbye.", "talk to you later, then."] greet_prompts = ["hello. :)", "greetings, user.", "good morning, user.", "good afternoon, user.", "good evening, user."] greetings = ["hello", "hi", "good morning", "good afternoon", "good evening"] current_time = datetime.datetime.now() def main(): ''' print("sabrina: ", end='') slowprt("greetings, user. i am sabrina, artifical not-very-intelligent intelligence.\n") print(" " * 9, end='') slowprt("i follow a very simple rule-based algorithm for deriving answers to your prompts, whatever they may be.\n") print(" " * 9, end='') slowprt("please be patient with me as i am constantly \"evolving\" to suit your needs.\n") print("sabrina: ", end='') slowprt("if at any point, you would like to exit the program, you can easily do so by typing\n") print(" " * 9, end='') slowprt("\"exitprgm\" into the given textspace.") print("sabrina: ", end='') slowprt("now then, where shall we begin?\n") ''' while(True): ans = input("user: ") print("sabrina: ", end='') # exit case if ans == "exitprgm": slowprt(random.choice(exit_prompts) + '\n') sys.exit(0) # greetings if any(word in ans.lower() for word in greetings): fault = False time_of_day = "default" if "morning" in ans: time_of_day = "morning" elif "afternoon" in ans: time_of_day = "afternoon" elif "evening" in ans: time_of_day = "evening" # morning if 5 <= current_time.hour <= 12: if time_of_day in ["afternoon","evening"]: fault = True slowprt("it's not " + time_of_day + ", silly kid.\n") c = random.choice([0,1,2]) # afternoon elif 13 <= current_time.hour <= 18: if time_of_day in ["morning","evening"]: fault = True slowprt("everyone has their own way of spelling \"afternoon\", but i've decided that your way is wrong.\n") c = random.choice([0,1,3]) # evening elif 19 <= current_time.hour <= 23: if time_of_day in ["morning","afternoon"]: fault = True slowprt("hm.. wouldn't exactly call it \"" + time_of_day + "\" right now.\n") c = random.choice([0,1,4]) # other else: c = random.randint(0,1) if not fault: slowprt(greet_prompts[c] + '\n') main()
# # 一个二叉树样例 # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # root = TreeNode(1) # root.left = TreeNode(2) # root.right = TreeNode(3) # root.left.left = TreeNode(4) # # def duplicateInArray(nums): # """ # :type nums: List[int] # :rtype int # """ # n = len(nums) # length of the nums # i = 0 # index # if n == 0: # return -1 # for i in range(n): # if nums[i] >= n or nums[i] < 0: # return -1 # while i < n: # if nums[i] == i: # i += 1 # elif nums[i] == nums[nums[i]]: # return nums[i] # else: # temp = nums[i] # nums[i] = nums[temp] # nums[temp] = temp # return -1 # nums = [3, 1, -10, 1, 1, 4, 3, 10, 1, 1] # a = duplicateInArray(nums) ############################# 14 # def duplicateInArray(nums): # """ # :type nums: List[int] # :rtype int # """ # n = len(nums) # label = [0] * n # for i in range(len(nums)): # if label[nums[i]] == 0: # label[nums[i]] = 1 # else: # return nums[i] # def duplicateInArray2(nums): # a = 1 # b = len(nums) - 1 # while a < b: # mid = (b+a)//2 # count = 0 # for i in range(len(nums)): # if a <= nums[i] <= mid: # count += 1 # if count > mid - a + 1: # b = mid # else: # a = mid +1 # return b # # int l = 1, r = nums.size() - 1; # # while (l < r) { # # int mid = l + r >> 1; // 划分的区间:[l, mid], [mid + 1, r] # # int s = 0; # # for (auto x : nums) s += x >= l && x <= mid; # # if (s > mid - l + 1) r = mid; # # else l = mid + 1; # # } # # return r; # nums = [2, 3, 5, 4, 3, 2, 6, 7] # a = duplicateInArray2(nums) # print(a) # ################### 16 # def replaceSpaces(s): # """ # :type s: str # :rtype: str # """ # n = len(s) # i = 0 # while i < n: # if s[i] == ' ': # s = s[:i] + '%20' + s[i+1:] # n += 2 # i += 2 # i += 1 # return s # s = " h jPW5a y rZ 4 6E" # s = replaceSpaces(s) # print(s) ############### 21 # def Fibonacci(n): # """ # :type n: int # :rtype: int # """ # nums = [0,1] # for i in range(n): # nums.append(nums[-1]+nums[-2]) # return nums[-1] # a = Fibonacci(39) # print(a) ############## 22 # def findMin(nums): # """ # :type nums: List[int] # :rtype: int # """ # if nums == []: # return -1 # left = 0 # right = len(nums) -1 # mid = 0 # while nums[left] >= nums[right]: # if right - left == 1: # mid = right # break # if nums[mid] == nums[left] == nums[right]: # return findMinInOrder(left,right) # elif nums[mid] >= nums[left]: # left = mid # elif nums[mid] <= nums[right]: # right = mid # mid = (left + right) // 2 # return nums[mid] # def findMinInOrder(left,right): # res = nums[left] # for i in range(left,right+1): # if nums[i] < res: # res = nums[i] # return res # nums = [1,0,1,1,1] # a = findMin(nums) # print(a) ################### 18 # preorder = [3, 9, 20, 15, 7] # inorder = [9, 3, 15, 20, 7] # def buildTree(preorder, inorder): # """ # :type preorder: List[int] # :type inorder: List[int] # :rtype: TreeNode # """ # def rebuildTree(preorder,inorder,res): # while preorder: # root = preorder[0] # rootid = inorder.index(root) # res.append(root) # res += rebuildTree(preorder[1:1+rootid],inorder[:rootid],res) # res += rebuildTree(preorder[1+rootid:],inorder[rootid+1:],res) # return res # res = [] # rebuildTree(preorder,inorder,res) # return res # a = buildTree(preorder,inorder) # print(a) ################################# 20 # class MyQueue(object): # def __init__(self): # """ # Initialize your data structure here. # """ # self.stack1 = [] # self.stack2 = [] # def push(self, x): # """ # Push element x to the back of queue. # :type x: int # :rtype: void # """ # if self.stack1: # self.stack1.append(x) # else: # while self.stack2: # self.stack1.append(self.stack2.pop()) # self.stack1.append(x) # def pop(self): # """ # Removes the element from in front of queue and returns that element. # :rtype: int # """ # if self.stack2: # return self.stack2.pop() # elif self.stack1: # while self.stack1: # self.stack2.append(self.stack1.pop()) # return self.stack2.pop() # else: # return None # def peek(self): # """ # Get the front element. # :rtype: int # """ # if self.stack2: # item = self.stack2.pop() # self.stack2.append(item) # return item # elif self.stack1: # while self.stack1: # self.stack2.append(self.stack1.pop()) # item = self.stack2.pop() # self.stack2.append(item) # return item # else: # return None # def empty(self): # """ # Returns whether the queue is empty. # :rtype: bool # """ # while self.stack1: # self.stack1.pop() # while self.stack2: # self.stack2.pop() # a = MyQueue() # a.push(4) ##########################23 # class Solution(object): # def hasPath(self, matrix, string): # """ # :type matrix: List[List[str]] # :type string: str # :rtype: bool # """ # def hasPathCore(self,x,y,string,matrix,label): # if not string: # return True # if x<0 or x>=m or y<0 or y>=n or matrix[x][y]!= string[0] or label[x][y] == 1: # return False # label[x][y] = 1 # if hasPathCore(self,x-1,y,string[1:],matrix,label) or \ # hasPathCore(self,x+1,y,string[1:],matrix,label) or \ # hasPathCore(self,x,y-1,string[1:],matrix,label) or \ # hasPathCore(self,x,y+1,string[1:],matrix,label): # return True # label[x][y] = 0 # return False # if not matrix or not string: # return False # m = len(matrix) # n = len(matrix[0]) # label = [[0]*n for i in range(m)] # for i in range(m): # for j in range(n): # if hasPathCore(self,i,j,string,matrix,label): # return True # return False # matrix=[ # ["C", "A", "A"], # ["A", "A", "A"], # ["B", "C", "D"]] # s1="AAB" # a = Solution() # print(a.hasPath(matrix,s1)) # s2="ASAE" # print(a.hasPath(matrix,s2)) #######################24 # k=0 # m=5 # n=6 # class Solution(object): # def movingCount(self, threshold, rows, cols): # """ # :type threshold: int # :type rows: int # :type cols: int # :rtype: int # """ # def movingCountCore(i,j,label,count): # if i < 0 or i >= rows or j < 0 or j >= cols or label[i][j] == 1: # return count # if check(i,j,threshold): # label[i][j] = 1 # count += 1 # else: # return count # count = movingCountCore(i-1,j,label,count) # count = movingCountCore(i+1,j,label,count) # count = movingCountCore(i,j-1,label,count) # count = movingCountCore(i,j+1,label,count) # return count # def check(i,j,threshold): # num = 0 # while i > 0 or j > 0: # num += i % 10 # num += j % 10 # i //= 10 # j //= 10 # if num <= threshold: # return True # else: # return False # label = [[0]*cols for i in range(rows)] # count = 0 # count = movingCountCore(0,0,label,count) # return count # a = Solution() # b = a.movingCount(k,m,n) # print(b) #################### 26 # n = 100 # n &= 0xFFFFFFFF # num = 0 # while n != 0: # num += n & 1 # n >>= 1 # print(num) #################### 27 # class Solution(object): # def isNumber(self, s): # """ # :type s: str # :rtype: bool # """ # dict = ['0','1','2','3','4','5','6','7','8','9'] # i = 0 # point = 0 # flag = 0 # if s[i] == '+' or s[i] =='-': # i += 1 # flag = 1 # while i < len(s): # if s[i] in dict: # i += 1 # elif s[i] == '.': # point += 1 # if point != 1 or i == 0 or ((flag == 1)&(i == 1)): # return False # else: # i += 1 # continue # elif s[i] == 'e' or s[i] == 'E': # i += 1 # if i == len(s) or i == 1: # return False # else: # break # else: # return False # if i < len(s): # if (s[i] == '+' or s[i] =='-'): # i += 1 # while i < len(s): # if s[i] not in dict: # return False # else: # i += 1 # return True # s = "3.1416" # a = Solution() # print(a.isNumber(s)) ################## 28 # class Solution(object): # def reOrderArray(self, array): # """ # :type array: List[int] # :rtype: void # """ # odd = [] # even = [] # for i in range(len(array)): # if array[i] % 2 == 1: # odd.append(array[i]) # else: # even.append(array[i]) # return odd + even # array = [2, 9, 9, 5, 3, 2, 9, 6, 0, 4] # a = Solution() # print(a.reOrderArray(array)) #################### 39 # class Solution(object): # def hasSubtree(self, pRoot1, pRoot2): # """ # :type pRoot1: TreeNode # :type pRoot2: TreeNode # :rtype: bool # """ # if not pRoot1 or not pRoot2: # return False # else: # return self.checkTree(pRoot1, pRoot2) # def checkTree(self, pRoot1, pRoot2): # if pRoot2 == None: # return True # elif pRoot1 == None: # return False # res = False # if pRoot1.val == pRoot2.val: # res = self.checkTree(pRoot1.left, pRoot2.left) and self.checkTree(pRoot1.right, pRoot2.right) # else: # return res or self.checkTree(pRoot1.left, pRoot2) or self.checkTree(pRoot1.right, pRoot2) # # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # pRoot1 = TreeNode(8) # # pRoot1.left = TreeNode(8) # # pRoot1.right = TreeNode(7) # # pRoot1.left.left = TreeNode(9) # # pRoot1.left.right = TreeNode(2) # # pRoot1.left.right.left = TreeNode(4) # # pRoot1.left.right.right = TreeNode(7) # # pRoot2 = TreeNode(8) # # pRoot2.left = TreeNode(9) # # pRoot2.right = TreeNode(2) # pRoot1 = TreeNode(8) # pRoot1.left = TreeNode(8) # pRoot1.right = TreeNode(7) # pRoot1.left.left = TreeNode(9) # pRoot1.left.right = TreeNode(2) # pRoot1.left.right.left = TreeNode(4) # pRoot1.left.right.right = TreeNode(7) # pRoot2 = TreeNode(8) # pRoot2.left = TreeNode(9) # pRoot2.right = TreeNode(2) # a = Solution() # b = a.hasSubtree(pRoot1, pRoot2) # print(b) ##################### 69 # class Solution(object): # def getNumberSameAsIndex(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # left = 0 # right = len(nums) - 1 # res = (left + right)//2 # while left <= right: # if nums[res] == res: # return res # elif nums[res] > res: # right = res - 1 # res = (left + right)//2 # else: # left = res + 1 # res = (left + right)//2 # return -1 # nums = [1,2,3] # a = Solution() # b = a.getNumberSameAsIndex(nums) # print(b) ################################# # n = 0 # a = [9] # b = [0] # for i in range(1,10): # a.append((i+1) * 9 * 10 ** i + a[-1]) # b.append((i + 1) * 10 ** i - a[-2] - 1) # for i in range(10): # if n < a[i]: # num = str((n + b[i]) // (i+1)) # j = (n + b[i]) % (i+1) # print(num[j]) # print(a,b) ############################ 53 # class Solution(object): # def getLeastNumbers_Solution(self, input, k): # """ # :type input: list[int] # :type k: int # :rtype: list[int] # """ # res = [float('inf')]*k # for i in range(len(input)): # if input[i] < res[k-1]: # res = self.reshape(res, input[i]) # return res # def reshape(self, res, k): # for i in range(len(res)): # if res[i] > k: # res.insert(i,k) # res.pop() # return res # a = Solution() # input = range(10) # k = 4 # b = a.getLeastNumbers_Solution(input,k) # print(b) ################################# # class Solution(object): # def lastRemaining(self, n, m): # """ # :type n: int # :type m: int # :rtype: int # """ # nums = list(range(n)) # return self.deleteNum(nums,m) # def deleteNum(self,nums,m): # if len(nums) == 1: # return nums[0] # else: # if m >= len(nums): # m %= len(nums) # nums[:] = nums[m + 1:] + nums[:m] # return self.deleteNum(nums,m) # n = 5 # m = 3 # a = Solution() # b = a.lastRemaining(n,m) # print(b) ###################### # class Solution: # def __init__(self): # self.nums = [] # def insert(self, num): # """ # :type num: int # :rtype: void # """ # res = [] # for i in range(len(num)): # if self.nums == []: # self.nums.append(num[i]) # res.append(self.getMedian) # elif num[i] > self.nums[-1]: # self.nums.append(num[i]) # res.append(self.getMedian) # else: # for j in range(len(self.nums)): # if num[i] <= self.nums[j]: # self.nums.insert(j,num[i]) # break # res.append(self.getMedian) # def getMedian(self): # """ # :rtype: float # """ # n = len(self.nums) # if n%2 == 1: # return self.nums[n//2] # else: # return (self.nums[n//2] + self.nums[n//2 - 1])/2 # num = [-3, -1, 1, 0, -4] # # m = 3 # a = Solution() # b = a.insert(num) # print(b) ######################### # nums = [3, 32, 321] # class Solution(object): # def printMinNumber(self, nums): # """ # :type nums: List[int] # :rtype: str # """ # if nums == []: return '' # nums = self.strReshape(nums) # nums = self.bubble_sort(nums) # return ''.join(nums) # def bubble_sort(self, nums): # for i in range(len(nums) - 1): # for j in range(len(nums) - i - 1): # if nums[j] + nums[j + 1] > nums[j + 1] + nums[j]: # nums[j], nums[j + 1] = nums[j + 1], nums[j] # return nums # def strReshape(self, nums): # tmp = [] # for i in range(len(nums)): # tmp.append(str(nums[i])) # return tmp # a = Solution() # b = a.printMinNumber(nums) # print(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 printFromTopToBottom(self, root): # """ # :type root: TreeNode # :rtype: List[List[int]] # """ # if not root: return [] # res = [] # Tree = [root] # layer = 0 # while Tree: # res1 = [] # Tree1 = [] # for i in range(len(Tree)): # if layer % 2 == 0: # res1.append(Tree[i].val) # else: # res1.append(Tree[-i - 1].val) # if Tree[i].left: # Tree1.append(Tree[i].left) # if Tree[i].right: # Tree1.append(Tree[i].right) # res.append(res1) # Tree = Tree1 # layer += 1 # return res # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # tree = TreeNode(9) # tree.right = TreeNode(16) # tree.right.left = TreeNode(7) # tree.right.right = TreeNode(12) # tree.right.left.left = TreeNode(14) # tree.right.right.right = TreeNode(11) # tree.right.left.left.left = TreeNode(2) # a = Solution() # b = a.printFromTopToBottom(tree) # print(b) ################################# # class Solution: # def getTranslationCount(self, s): # """ # :type s: str # :rtype: int # """ # num = str(s) # if len(num) in [0, 1]: # return len(num) # res = [0, 1] # for i in range(1, len(num)): # if int(num[i-1:i+1]) < 26 and int(num[i-1]) != 0: # res.append(res[-1] + res[-2]) # else: # res.append(res[-1]) # return res[-1] # s = 70476768 # a = Solution() # b = a.getTranslationCount(s) # print(b) ################# # class Solution: # def longestSubstringWithoutDuplication(self, s): # """ # :type s: str # :rtype: int # """ # st = {} # first,length = 0,0 # for i in range(len(s)): # if s[i] in st: # first = max(st[s[i]],first) # length = max(length,i - first + 1) # st[s[i]] = i + 1 # return length # s = 'asdfdasf' # a = Solution() # b = a.longestSubstringWithoutDuplication(s) # print(b) ######################### # class Solution(object): # def getMaxValue(self, grid): # """ # :type grid: List[List[int]] # :rtype: int # """ # m = len(grid) # n = len(grid[0]) # res = [[0] * n for i in range(m)] # for i in range(m): # for j in range(n): # if i == 0 and j == 0: # res[0][0] = grid[0][0] # elif i == 0: # res[i][j] += res[i][j-1] + grid[i][j] # elif j == 0: # res[i][j] += res[i-1][j] + grid[i][j] # else: # res[i][j] = max(res[i][j-1], res[i-1][j]) + grid[i][j] # return res[m - 1][n - 1] # grid = [[4, 7, 4], [9, 7, 7]] # a = Solution() # b = a.getMaxValue(grid) # print(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 findPath(self, root, sum): # """ # :type root: TreeNode # :type sum: int # :rtype: List[List[int]] # """ # res = [] # result = [] # self.checkPath(root, sum, res, result) # return result # def checkPath(self, root, sum, res, result): # if not root: # return None # res.append(root.val) # sum -= root.val # if sum == 0: # if not root.left or not root.right: # result.append(res[:]) # if root.left: # self.checkPath(root.left, sum, res, result) # if root.right: # self.checkPath(root.right, sum, res, result) # res.pop() # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # root = None # # root = TreeNode(6) # # root.right = TreeNode(2) # # root.right.left = TreeNode(3) # # root.right.left.right = TreeNode(2) # # root.right.right = TreeNode(5) ############## # class Solution(object): # def numberOf1Between1AndN_Solution(self, n): # """ # :type n: int # :rtype: int # """ # res = 0 # for i in range(n + 1): # res += self.check(i) # return res # def check(self, n): # res = 0 # while n != 0: # if n % 10 == 1: # res += 1 # n //= 10 # return res # n = 1 # a = Solution() # b = a.numberOf1Between1AndN_Solution(n) # print(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: # def __init__(self): # self.res = [] # self.head = None # def serialize(self, root): # """Encodes a tree to a single string. # :type root: TreeNode # :rtype: str # """ # if not root: # return self.res # else: # self.res.append(root.val) # return self.seializeCore([root]) # def seializeCore(self, Tree): # if not Tree: # return self.res # else: # newTree = [] # for i in range(len(Tree)): # if Tree[i].left: # self.res.append(Tree[i].left.val) # newTree.append(Tree[i].left) # else: # self.res.append(None) # if Tree[i].right: # self.res.append(Tree[i].right.val) # newTree.append(Tree[i].right) # else: # self.res.append(None) # Tree = newTree # return self.seializeCore(Tree) # def deserialize(self, data): # """Decodes your encoded data to tree. # :type data: str # :rtype: TreeNode # """ # if not data: # return self.head # else: # self.head = TreeNode(data[0]) # data.pop(0) # return self.deserializeCore([self.head], data) # def deserializeCore(self, tree, data): # if not data: # return self.head # else: # newtree = [] # for i in range(len(tree)): # if data[0]: # tree[i].left = TreeNode(data[0]) # newtree.append(tree[i].left) # data.pop(0) # if data[0]: # tree[i].right = TreeNode(data[0]) # newtree.append(tree[i].right) # data.pop(0) # tree = newtree # return self.deserializeCore(tree, data) # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # root = TreeNode(6) # root.right = TreeNode(2) # root.right.left = TreeNode(3) # root.right.left.right = TreeNode(2) # root.right.right = TreeNode(5) # a = Solution() # b = a.serialize(root) # c = [6, None, 2, 3, 5, None, 2, None, None, None, None] # d = a.deserialize(c) # print(b) # print(d) ########################## # class Solution: # def firstNotRepeatingChar(self, s): # """ # :type s: str # :rtype: str # """ # d = {} # for i in range(len(s)): # if s[i] in d.keys(): # d[s[i]] += 1 # else: # d[s[i]] = 1 # s = list(d.keys()) # for i in range(len(s)): # if d[s[i]] == 1: # return s[i] # return '#' # s = 'fsafg' # a = Solution() # b = a.firstNotRepeatingChar(s) # print(b) ############################ # class Solution: # def __init__(self): # self.d = {} # self.k = [] # def firstAppearingOnce(self): # """ # :rtype: str # """ # for i in range(len(self.k)): # if self.d[self.k[i]] == 1: # return self.k[i] # return '#' # def insert(self, char): # """ # :type char: str # :rtype: void # """ # if char in self.k: # self.d[char] += 1 # else: # self.d[char] = 1 # self.k.append(char) # a = Solution() # a.insert('1') # print(a.firstAppearingOnce()) ############################ # class Solution(object): # def getNumberOfK(self, nums, k): # """ # :type nums: list[int] # :type k: int # :rtype: int # """ # if not nums: # return 0 # left = 0 # right = len(nums) # mid = (left + right) // 2 # midnum = -1 # while left <= right: # if nums[mid] < k: # left = mid + 1 # mid = (left + right) // 2 # elif nums[mid] > k: # right = mid - 1 # mid = (left + right) // 2 # else: # midnum = mid # break # if midnum == -1: # return 0 # leftIndex = self.getLeft(midnum, nums, k) # rightIndex = self.getRight(midnum, nums, k) # return rightIndex - leftIndex + 1 # def getLeft(self, midnum, nums, k): # left = 0 # right = midnum # mid = (left + right)//2 # while left < right: # if nums[mid] == k: # right = mid # else: # left = mid + 1 # mid = (left + right) // 2 # return right # def getRight(self, midnum, nums, k): # left = midnum # right = len(nums) - 1 # mid = (left + right)//2 # if nums[right] == k: # return right # while left < right: # if nums[mid] == k: # left = mid # mid = (left + right) // 2 # right -= 1 # else: # right = mid - 1 # mid = (left + right) // 2 # return left # nums = [0,0,0,0,1,1,1,2,2,2,2,2,2] # k = 2 # a = Solution() # b = a.getNumberOfK(nums, k) # print(b) ################################ # class Solution(object): # def findContinuousSequence(self, k): # """ # :type sum: int # :rtype: List[List[int]] # """ # if k <= 2: # return [] # left = k // 2 # right = left + 1 # res = [] # while left >= 1: # if sum(list(range(left, right + 1))) == k: # res.append(list(range(left, right + 1))) # left -= 1 # elif sum(list(range(left, right + 1))) < k: # right += 1 # else: # left -= 1 # right -= 1 # return res ################################ # class Solution(object): # def numberOfDice(self, n): # """ # :type n: int # :rtype: List[int] # """ # res = [] # for i in range(1, n + 1): # if i == 1: # res = [1] * 6 # else: # res = self.newRes(res, i) # return res # def newRes(self, res, n): # newres = [0] * (5 * n + 1) # for i in range(6): # for j in range(len(res)): # newres[i + j] += res[j] # return newres # class Solution(object): # def findNumsAppearOnce(self, nums): # """ # :type nums: List[int] # :rtype: List[int] # """ # res = 0 # for i in range(len(nums)): # res ^= nums[i] # index = 0 # while (res & 1) == 0: # res >>= 1 # index += 1 # a = b = 0 # for i in nums: # if self.fun(i, index): # a ^= i # else: # b ^= i # return [a, b] # def fun(self, num, index): # num = num >> index # return num & 1 ############################ # class Solution(object): # def strToInt(self, str): # """ # :type str: str # :rtype: int # """ # if not str: return 0 # length = len(str) # nums = '0123456789' # i = 0 # while str[i] == ' ' and i <= length - 1: # i += 1 # num = '' # flag = 1 # if i == length - 1: # return 0 # if str[i] == '+': # flag = 1 # i += 1 # elif str[i] == '-': # flag = -1 # i += 1 # while i <= length - 1 and str[i] in nums: # num += str[i] # i += 1 # n = int(num) * flag # if n > 2**31 - 1: # return 'INT_MAX' # elif n < - 2 ** 31: # return 'INT_MIN' # return n # str = 'la123' # a = Solution() # b = a.strToInt(str) # print(b) ########################## # class Solution(object): # def isContinuous(self, numbers): # """ # :type numbers: List[int] # :rtype: bool # """ # numbers.sort() # KingNum = 0 # n = 0 # d = [0,1,2,3,4,5,6,7,8,9,10,11,12,13] # if numbers == [] or numbers == [0] * 5: # return False # for i in range(5): # if numbers[i] == 0: # KingNum += 1 # elif numbers[i] not in d or numbers[i] == numbers[i-1]: # return False # elif n == 0: # n = d.index(numbers[i]) + 1 # elif numbers[i] in d: # if numbers[i] == d[n]: # n += 1 # elif numbers[i] - d[n] <= KingNum: # KingNum -= numbers[i] - d[n] # n += numbers[i] - d[n] + 1 # else: # return False # else: # return False # return True # a = Solution() # numbers = [0,1,3,5,0] # b = a.isContinuous(numbers) # print(b) ############################## # class Solution(object): # def lowestCommonAncestor(self, root, p, q): # """ # :type root: TreeNode # :type p: TreeNode # :type q: TreeNode # :rtype: TreeNode # """ # if (root.left == p and root.right == q) or (root.left == q and root.right == p): # return root # elif not root.left or not root.right: # if root.left: # return self.lowestCommonAncestor(root.left, p, q) # elif root.right: # return self.lowestCommonAncestor(root.right, p, q) # else: # return None # else: # self.lowestCommonAncestor(root.left, p, q) # self.lowestCommonAncestor(root.right, p, q) # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # a = Solution() # root = TreeNode(1) # p = None # q = None # b = a.lowestCommonAncestor(root,p,q) # print(b) ###################################### # class Solution(object): # def findNumberAppearingOnce(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # s = [0] * 5 # n = 0 # for i in range(len(nums)): # s = self.addNum(nums[i], s) # for j in range(len(s)): # n = n * 10 + s[j] % 3 # return int(str(n), 2) # def addNum(self, n, s): # i = -1 # while n != 0: # if n & 1 == 1: # s[i] += 1 # n >>= 1 # i -= 1 # return s # a = Solution() # nums = [1,1,1,2,2,2,3,4,4,4] # b = a.findNumberAppearingOnce(nums) # print(b) ###################### # class Solution(object): # def isPopOrder(self, pushV, popV): # """ # :type pushV: list[int] # :type popV: list[int] # :rtype: bool # """ # res = [] # while pushV or popV: # if pushV and pushV[0] == popV[0]: # pushV.pop(0) # popV.pop(0) # elif res and popV[0] == res[-1]: # res.pop() # popV.pop(0) # elif pushV: # res.append(pushV[0]) # pushV.pop(0) # else: # return False # if not res: # return True # else: # return False ############################## # class Solution: # def verifySequenceOfBST(self, sequence): # """ # :type sequence: List[int] # :rtype: bool # """ # if not sequence: # return True # index = len(sequence) - 1 # for i in range(len(sequence)): # if sequence[i] > sequence[-1]: # index = i # break # for i in range(index, len(sequence)): # if sequence[i] < sequence[-1]: # return False # return self.verifySequenceOfBST(sequence[:index]) and self.verifySequenceOfBST(sequence[index:-1]) # class Solution(object): # def __init__(self): # self.count = 0 # def kthNode(self, pRoot, k): # if not pRoot: # return None # node = self.kthNode(pRoot.left, k) # if node: # return node # self.count += 1 # if self.count == k: # return pRoot # node = self.kthNode(pRoot.right, k) # if node: # return node # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Tree = TreeNode(2) # Tree.left = TreeNode(1) # Tree.right = TreeNode(3) # a = Solution() # sequence = [2,1,3] # b = a.kthNode(Tree, 3) # print(b) ####################################### # class Solution(object): # def strToInt(self, s): # """ # :type str: str # :rtype: int # """ # n = '' # index = 0 # length = len(s) # d = '0123456789' # flag = 1 # last = ' ' # while index < length: # if last == ' ' and s[index] in d: # break # elif s[index] == '-': # flag = -1 # index += 1 # break # elif s[index] == '+': # flag = 1 # index += 1 # break # else: # last = s[index] # index += 1 # while index < length and s[index] in d: # n += s[index] # index += 1 # if n == '': # return 0 # else: # n = int(n) * flag # if n > 2 ** 31 - 1: # return 'INT_MAX' # elif n < - 2 ** 31: # return 'INT_MIN' # else: # return n # a = Solution() # b = a.strToInt('la123') # print(b) ########################### # def findKthUgly(k): # ugly = [] # ugly.append(1) # index = 1 # index2 = 0 # index3 = 0 # index5 = 0 # while index < k: # val = min(ugly[index2]*2, ugly[index3]*3, ugly[index5]*5) # if ugly[index2]*2 == val: # index2 += 1 # if ugly[index3]*3 == val: # index3 += 1 # if ugly[index5]*5 == val: # index5 += 1 # ugly.append(val) # index += 1 # return ugly[-1] # print(findKthUgly(20)) ################################## # class Solution(object): # def add(self, num1, num2): # """ # :type num1: int # :type num2: int # :rtype: int # """ # while num2: # num1, num2 = (num1 ^ num2) & 0xFFFFFFFF, ((num1 & num2) << 1) & 0xFFFFFFFF # return num1 if num1 <= 0x7FFFFFFF else ~(num1^0xFFFFFFFF) # a = Solution() # b = a.add(2147483647, -4) # print(b) ######################################### # import os # import pandas as pd # unames = ['text'] # users = pd.read_table('test.dat',sep='::',header=None,names=unames) # text = 'Title="example: 2d finite-element data"\n\ # variables ="x","y","S1"\n\ # zone N=8,E=3, datapacking=block\n\ # varlocation=([3]=cellcentered)\n\ # zonetype=fequadrilateral\n\ # 0 0 0 0 1 1 1 1 \n\ # 0 1 2 3 0 1 2 3\n\ # 10\n\ # -5\n\ # 1.0\n\ # 1 5 6 2\n\ # 2 6 7 3\n\ # 3 7 8 4\n' # f = open("test.dat", "r+") # f.write(text) # f.close # print(text) ################################### 108 # nums = [-10,-3,0,5,9] # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # class Solution: # def sortedArrayToBST(self, nums): # if not nums: # return None # n = len(nums) // 2 # head = TreeNode(nums[n]) # head.left = self.sortedArrayToBST(nums[:n]) # head.right = self.sortedArrayToBST(nums[n + 1:]) # return head # a = Solution() # b = a.sortedArrayToBST(nums) # print('finish') # class Solution(object): # def getIntersectionNode(self, headA, headB): # """ # :type head1, head1: ListNode # :rtype: ListNode # """ # if not headA or not headB: # return None # hA = [] # hB = [] # node = None # while not headA: # hA.append(headA) # headA = headA.next # while not headB: # hB.append(headB) # headB = headB.next # while len(hA)>0 and len(hB) > 0: # a = hA.pop() # b = hB.pop() # if a == b: # node = a # else: # break # return node # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # headA = ListNode(4) # headA.next = ListNode(1) # headB = ListNode(5) # headB.next = ListNode(1) # a = Solution() # b = a.getIntersectionNode(headA, headB) # class Solution(object): # def isIsomorphic(self, s, t): # """ # :type s: str # :type t: str # :rtype: bool # """ # d = {} # for i in range(len(s)): # if s[i] in d: # if d[s[i]] == t[i]: # continue # else: # return False # else: # if t[i] in d.values(): # return False # d[s[i]] = t[i] # return True # a = Solution() # b = a.isIsomorphic('ab', 'aa') # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # class Solution: # def rotateRight(self, head: ListNode, k: int) -> ListNode: # if not head: # return None # tail = head # length = 1 # while tail.next: # tail = tail.next # length += 1 # k %= length # if k == 0: # return head # breaknode = head # while k != 1: # breaknode = breaknode.next # k -= 1 # newhead = breaknode.next # breaknode.next = None # tail.next = head # return newhead # head = ListNode(1) # head.next = ListNode(2) # a = Solution() # b = a.rotateRight(head, 1) # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # class Solution: # def binaryTreePaths(self, root): # res = [] # if not root: # return res # self.core(root, [], res) # return res # def core(self, root, path, res): # path.append(root.val) # if not root.left and not root.right: # res.append(path) # path.pop() # return # if root.left: # self.core(root.left, path, res) # if root.right: # self.core(root.right, path, res) # root = TreeNode(1) # root.left = TreeNode(2) # root.right = TreeNode(3) # root.left.left = TreeNode(4) # a = Solution() # b = a.binaryTreePaths(root) # print(b) # class Solution: # def generateMatrix(self, n): # matrix = [] # lo = n*n + 1 # while lo > 1: # lo, hi = lo - len(matrix), lo # a = [list(range(lo, hi))] # b = list(zip(*matrix[::-1])) # matrix = a + b # return matrix # a = Solution() # b = a.generateMatrix(3) # print(b) # class Solution(object): # def reverseVowels(self, s): # """ # :type s: str # :rtype: str # """ # return s # a = Solution() # b = a.reverseVowels('hello') # print(b) # class MinStack(object): # def __init__(self): # """ # initialize your data structure here. # """ # self.stack = [] # self.minNum = [] # def push(self, x): # """ # :type x: int # :rtype: None # """ # self.stack.append(x) # if not self.minNum: # self.minNum.append(x) # elif x < self.minNum[-1]: # self.minNum.append(x) # else: # self.minNum.append(self.minNum[-1]) # def pop(self): # """ # :rtype: None # """ # if not self.stack: # return None # self.minNum.pop() # return self.stack.pop() # def top(self): # """ # :rtype: int # """ # if not self.stack: # return None # return self.stack[-1] # def getMin(self): # """ # :rtype: int # """ # if not self.stack: # return None # return self.minNum[-1] # a = MinStack() # a.push(-2) # a.push(0) # a.push(-3) # print(a.pop()) # print(a.top()) # print(a.getMin) # # 一个二叉树样例 # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # root = TreeNode(1) # root.left = TreeNode(2) # root.right = TreeNode(3) # root.left.left = TreeNode(4) # class Solution: # def binaryTreePaths(self, root): # if not root: # return [] # res = [] # self.core(root,'',res) # return res # def core(self, root, path, res): # path += str(root.val) # if not root.left and not root.right: # res.append(path) # if root.left: # self.core(root.left, path + '->', res) # if root.right: # self.core(root.right, path + '->', res) # class Solution: # def sumOfLeftLeaves(self, root): # if not root: # return 0 # num = 0 # num = self.sumCore(root, num, 0) # return num # def sumCore(self, root, num, flag): # if not root.left and not root.right: # num += root.val * flag # if root.left: # num = self.sumCore(root.left, num, 1) # if root.right: # num = self.sumCore(root.right, num, 0) # return num # a = Solution() # b = a.sumOfLeftLeaves(root) # print(b) # class Solution(object): # def lengthOfLongestSubstring(self, s): # """ # :type s: str # :rtype: int # """ # d = {} # length = [0] # for i in range(len(s)): # if s[i] not in d: # d[s[i]] = i # length.append(length[-1] + 1) # else: # length.append(max(length[-1], i - d[s[i]])) # d[s[i]] = i # return max(length) # a = Solution() # b = a.lengthOfLongestSubstring("pwwkew") # print(b) # class Solution: # def isNumber(self, s: str) -> bool: # #define a DFA # state = [{}, # {'blank': 1, 'sign': 2, 'digit':3, '.':4}, # {'digit':3, '.':4}, # {'digit':3, '.':5, 'e':6, 'blank':9}, # {'digit':5}, # {'digit':5, 'e':6, 'blank':9}, # {'sign':7, 'digit':8}, # {'digit':8}, # {'digit':8, 'blank':9}, # {'blank':9}] # currentState = 1 # for c in s: # if c >= '0' and c <= '9': # c = 'digit' # if c == ' ': # c = 'blank' # if c in ['+', '-']: # c = 'sign' # if c not in state[currentState].keys(): # return False # currentState = state[currentState][c] # if currentState not in [3,5,8,9]: # return False # return True # a = Solution() # b = a.isNumber(" +323123.e12103") # print(b) # class Solution: # def findNthDigit(self, n: int) -> int: # # a = [] # # b = [] # # for i in range(10): # # a.append(9 * 10 ** i) # # b.append((i + 1) * 10 ** i - a[i]) # # if n <= 9: # # return n # # elif n <= 189: # # num = str((n + 10)//2) # # i = 1 - (n + 9) % 2 # # return num[i] # # elif n <= 2889: # # num = str((n + 110) // 3) # # i = 2 - (n + 191) % 3 # # return num[i] # # elif n <= 38889: # # num = str((n + 1110) // 4) # # i = 3 - (n + 1110) % 4 # # return num[i] # a = [9] # b = [0] # for i in range(1,10): # a.append((i+1) * 9 * 10 ** i + a[-1]) # b.append((i + 1) * 10 ** i - a[-2] - 1) # for i in range(10): # if n <= a[i]: # num = str((n + b[i]) // (i+1)) # j = (n + b[i]) % (i+1) # return num[j] # a = Solution() # b = a.findNthDigit(9) # print(b) # class Solution: # def readBinaryWatch(self, num): # hour = 0 # minute = num - hour # res = [] # while 0 <= hour <= 3: # if minute >= 6: # hour += 1 # minute -= 1 # elif minute < 0: # break # else: # hours = self.Hours(hour) # minutes = self.Minutes(minute) # for i in hours: # for j in minutes: # res.append(i +':' + j) # hour += 1 # minute -= 1 # return res # def Hours(self, hour): # if hour == 0: # return ['0'] # elif hour == 1: # return ['1', '2', '4', '8'] # elif hour == 2: # return ['3', '5', '6', '9', '10'] # elif hour == 3: # return ['7', '11'] # def Minutes(self, minutes): # res = [] # for i in range(60): # m = i # n = 0 # while m != 0: # n += m & 1 # m >>= 1 # if n == minutes: # if i < 10: # res.append('0' + str(i)) # else: # res.append(str(i)) # return res # a = Solution() # b = a.readBinaryWatch(3) # print(b) # # 一个二叉树样例 # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # root = TreeNode(10) # root.left = TreeNode(5) # root.right = TreeNode(-3) # root.left.left = TreeNode(3) # root.left.left.left = TreeNode(3) # root.left.left.right = TreeNode(-2) # root.left.right = TreeNode(2) # root.left.right.right = TreeNode(1) # root.right.right = TreeNode(11) # class Solution(object): # def pathSum(self, root, s): # return self.helper(root, s, [s]) # def helper(self, node, origin, targets): # if not node: return 0 # hit = 0 # for t in targets: # if not t-node.val: hit += 1 # count if sum == target # targets = [t-node.val for t in targets]+[origin] # update the targets # return hit+self.helper(node.left, origin, targets)+self.helper(node.right, origin, targets) # a = Solution() # b = a.pathSum(root, 8) # print(b) # class Solution: # def longestPalindrome(self, s: str) -> str: # res = '' # for i in range(len(s)): # tmp = self.helper(s,i,i) # if len(tmp) > len(res): # res = tmp # tmp = self.helper(s,i,i+1) # if len(tmp) > len(res): # res = tmp # return res # def helper(self,s,i,j): # while i >= 0 and j < len(s) and s[i] == s[j]: # i -= 1; j += 1 # return s[i-1:j] # a = Solution() # b = a.longestPalindrome("babad") # class Solution: # def myAtoi(self, s: str) -> int: # res = 0 # flag = 1 # symbol = 0 # for i in range(len(s)): # if s[i] == ' ': # continue # if s[i] == '+' or s[i] == '-': # if s[i] == '+' and symbol == 0: # flag = 1 # symbol = 1 # continue # elif s[i] == '-' and symbol == 0: # flag = -1 # symbol = 1 # continue # else: # return res # if s[i] <'0' or s[i]>'9': # break # else: # res = res*10 + int(s[i]) # res *= flag # if res > 2 ** 31 - 1: # return 2 ** 31 - 1 # elif res < - 2 ** 31: # return - 2 ** 31 # else: # return res # class Solution: # def myAtoi(self, s: str) -> int: # state = [{}, # {'blank': 1, 'sign': 2, 'digit':3, 'alphabet':4}, # {'digit':3}, # {'digit':3, 'alphabet':5, 'blank':5}, # {'digit':3, 'sign':2, 'alphabet':4}, # {'alphabet':5}] # currentState = 1 # res = '' # for c in s: # if c == ' ': # b = 'blank' # elif c >= '0' and c <= '9': # b = 'digit' # elif c == ' ': # b = 'blank' # elif c in ['+', '-']: # b = 'sign' # else: # b = 'alphabet' # if b not in state[currentState].keys(): # return 0 # currentState = state[currentState][b] # if currentState in [2,3]: # res += c # if currentState not in [3,5]: # return 0 # res = int(res) # if res > 2 ** 31 - 1: # return 2 ** 31 - 1 # elif res < - 2 ** 31: # return - 2 ** 31 # else: # return res # a = Solution() # b = a.myAtoi('4193 with words') # print(b) # class Solution: # def nextPermutation(self, nums): # """ # Do not return anything, modify nums in-place instead. # """ # minNum = nums[-1] # length = len(nums) # flag = 0 # for i in range(1, length + 1): # if nums[-i] < minNum: # d = nums[length-i:] # a = max(d) # d.remove(a) # d.sort() # nums = nums[0:length-i] + [a] + d # flag = 1 # break # else: # minNum = nums[-i] # if not flag: # nums.sort() # return nums # a = Solution() # b = a.nextPermutation([1,2,3]) # print(b) # class Solution(object): # def minPathSum(self, grid): # """ # :type grid: List[List[int]] # :rtype: int # """ # length = [[0] * len(grid[0]) for i in range(len(grid))] # for i in range(len(grid)): # for j in range(len(grid[0])): # if i == 0 and j == 0: # length[i][j] = grid[i][j] # elif i == 0: # length[i][j] = length[i][j-1] + grid[i][j] # elif j == 0: # length[i][j] = length[i-1][j] + grid[i][j] # else: # length[i][j] = min(length[i-1][j], length[i][j-1]) + grid[i][j] # return length[i][j] # a = Solution() # b = a.minPathSum([[1,2,5],[3,2,1]]) # print(b) # class Solution(object): # def uniquePathsWithObstacles(self, obstacleGrid): # """ # :type obstacleGrid: List[List[int]] # :rtype: int # """ # m = len(obstacleGrid) # n = len(obstacleGrid[0]) # d = [[0] * n for i in range(m)] # for i in range(m): # for j in range(n): # if i == 0 and j == 0: # d[i][j] = obstacleGrid[i][j] ^ 1 # elif i == 0: # d[i][j] = d[i][j-1] * (obstacleGrid[i][j-1] ^ 1) # elif j == 0: # d[i][j] = d[i-1][j] * (obstacleGrid[i-1][j] ^ 1) # else: # d[i][j] = d[i-1][j] * (obstacleGrid[i-1][j] ^ 1) + d[i][j-1] * (obstacleGrid[i][j-1] ^ 1) # # 位运算优先级低于加减法运算 # return d[i][j] * (obstacleGrid[i][j] ^ 1) # a = Solution() # b = a.uniquePathsWithObstacles([[0,1],[0,0]]) # print(b) # class Solution(object): # def maxProduct(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # if len(nums) == 1: # return nums[0] # curMax = nums[0] # curMin = nums[0] # ans = nums[0] # for i in range(1, len(nums)): # curMax, curMin = max(curMax * nums[i], curMin * nums[i], nums[i]), min(curMax * nums[i], curMin * nums[i], nums[i]) # ans = max(curMax, ans) # return ans # a = Solution() # b = a.maxProduct([-4,-3,-2]) class Solution(object): def wordBreak(self, s, words): ok = [True] for i in range(1, len(s)+1): ok += any(ok[j] and s[j:i] in words for j in range(i)), return ok[-1] a = Solution() b = a.wordBreak("aaaaaaa",["aaaa","aaa"]) print(b)
# # @lc app=leetcode.cn id=23 lang=python3 # # [23] 合并K个排序链表 # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: head = ListNode(0) node = head nums = [] for i in range(len(lists)): n = lists[i] while n: nums.append(n.val) n = n.next nums.sort() for i in range(len(nums)): head.next = ListNode(nums[i]) head = head.next return node.next
def Answer14_1(): """ Callable object: functions, methods, class, callable class instances The difference between exec and eval: the exec is to exe the command in string and the eval is to calculate the value of a string expression """ def Answer14_2(): """ The difference between input() and raw_input(): raw_input() returns user input as a string; input() return the evaluation of the user input as a Python expression. In other words: input() == eval(raw_input()) """ if __name__ == "__main__": print("\nthe answer of 14_1 is:") print(Answer14_1.__doc__) print("\nthe answer of 14_2 is:") print(Answer14_2.__doc__)
from api import * import matplotlib.pyplot as plt import numpy as np import math def plot_67mm_diameter_graph(): x = np.array([200**2, 400**2, 600**2, 800**2, 1000**2, 1200**2, 1400**2, 1600**2, 1800**2, 2000**2, 2200**2, 2400**2,2600**2,2800**2]) y = np.array([0.066,0.277,0.574,1.116,1.535,2.503,3.232,4.41,5.238,6.164,8.456,10.08,11.475,13.759]) p2 = np.polyfit(x, y, 2) xp = np.linspace(x[0], x[len(x) - 1], 1000) plt.plot(x, y, "ro", label="67.5mm Diameter") plt.plot(xp, np.polyval(p2, xp), "r-") plt.title("RPM vs. Thrust", fontsize=16) plt.ylabel("Thrust", fontsize=12) plt.xlabel("RPM", fontsize=12) plt.grid(b=None, which='major', axis='both') slope = np.polyfit(np.log(x), np.log(y), 1) print("Slope:", slope[0]) plt.legend(loc="upper left") plt.savefig("diameter: 67mm.png") plt.show()
import unittest import quiz_20190617 class TestFizz(unittest.TestCase): #FIXME -- if zero then 1 should be return as string because next increments def test_zero(self): buzzer = quiz_20190617.FizzBuzzer(0) self.assertEqual(buzzer.next(),'1') def test_one(self): buzzer = quiz_20190617.FizzBuzzer(1) self.assertEqual(buzzer.next(),'2') def test_two_four(self): #when `x = FizzBuzzer(2)`, `x.next()` returns `"fizz"` and calling `x.next()` #a second time returns `"4"` buzzer =quiz_20190617. FizzBuzzer(2) self.assertEqual(buzzer.next(),'fizz') self.assertEqual(buzzer.next(),'4') if __name__=='__main__': unittest.main()
import tkinter as tk from struct import pack root = tk.Tk() choices = ('network one', 'network two', 'network three') lb1 = tk.Listbox(root) lb1.insert(1,*choices) lb1.pack() table = ('one', 'two', 'three') def clean(): # Reset var and delete all old options #for choices in lb1: lb1.delete(0, tk.END) #lb1.pack() #lb1.delete(i,len(lb1)) def insert(itemToInsert): # Insert list of new options (tk._setit hooks them up to var) #itemToInsert= ('one', 'two', 'three') for item in itemToInsert: lb1.insert(tk.END,item) def mutate(): pass # I made this quick refresh button to demonstrate tk.Button(root, text='Clean', command=clean).pack() tk.Button(root, text = 'Insert',command=lambda: insert(table)).pack() tk.Button(root, text = 'Mutate', command=clean).pack() root.mainloop()
import numpy as np a = np.arange(12).reshape(3, 4) print(a) # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] print(a.shape) # (3, 4) print(a.ravel()) # [ 0 1 2 3 4 5 6 7 8 9 10 11] print(a.reshape(6,2)) # [[ 0 1] # [ 2 3] # [ 4 5] # [ 6 7] # [ 8 9] # [10 11]] print(a.T) # [[ 0 4 8] # [ 1 5 9] # [ 2 6 10] # [ 3 7 11]] print(a.reshape(1,-1)) # If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated: # [[ 0 1 2 3 4 5 6 7 8 9 10 11]]
#!/usr/bin/env python3 from trivia_questions import TriviaQuestions MAX_PLAYERS = 6 class Game: def __init__(self, number_of_questions=50): self.players = [] self.places = [0] * MAX_PLAYERS self.purses = [0] * MAX_PLAYERS self.in_penalty_box = [0] * MAX_PLAYERS self.pop_questions = TriviaQuestions(number_of_questions, 'Pop').questions self.science_questions = [] self.sports_questions = [] self.rock_questions = [] self.number_of_questions_in_category = number_of_questions self.current_player = 0 self.is_getting_out_of_penalty_box = False for i in range(number_of_questions): self.pop_questions.append("Pop Question %s" % i) self.science_questions.append("Science Question %s" % i) self.sports_questions.append("Sports Question %s" % i) self.rock_questions.append("Rock Question %s" % i) def shuffle_questions(self): self.populate_list("Pop", self.pop_questions) self.rock_questions = [] self.shuffle_pop_questions() self.shuffle_rock_questions() def shuffle_pop_questions(self): self.pop_questions = [] self.populate_list("Pop", self.pop_questions) def shuffle_rock_questions(self): self.rock_questions = [] for i in range(self.number_of_questions_in_category): self.rock_questions.append("Rock Question %s" % i) # # def create_rock_question(self, index): # return "Rock Question %s" % index def add(self, player_name): self.players.append(player_name) self.places[self.how_many_players] = 0 self.purses[self.how_many_players] = 0 self.in_penalty_box[self.how_many_players] = False print(player_name + " was added") print("They are player number %s" % len(self.players)) return True @property def how_many_players(self): return len(self.players) def roll(self, roll): print("%s is the current player" % self.players[self.current_player]) print("They have rolled a %s" % roll) if self.in_penalty_box[self.current_player]: self.player_in_penalty_box(roll) else: self.player_not_in_penalty_box(roll) def player_not_in_penalty_box(self, roll): self.places[self.current_player] = self.places[self.current_player] + roll if self.places[self.current_player] > 11: self.places[self.current_player] = self.places[self.current_player] - 12 print(self.players[self.current_player] + \ '\'s new location is ' + \ str(self.places[self.current_player])) print("The category is %s" % self._current_category) self._ask_question() def player_in_penalty_box(self, roll): if roll % 2 != 0: self.is_getting_out_of_penalty_box = True print("%s is getting out of the penalty box" % self.players[self.current_player]) self.player_not_in_penalty_box(roll) else: print("%s is not getting out of the penalty box" % self.players[self.current_player]) self.is_getting_out_of_penalty_box = False def _ask_question(self): self._ask_question_for_category("Science", self.science_questions) self._ask_question_for_category("Pop", self.pop_questions) self._ask_question_for_category("Sports", self.sports_questions) self._ask_question_for_category("Rock", self.rock_questions) def _ask_question_for_category(self, label, list): if self._current_category == label: if len(list) > 0: print(list.pop(0)) else: self.populate_list(label, list) print(list.pop(0)) def populate_list(self, label, list): for i in range(self.number_of_questions_in_category): list.append("%s Question %s" % (label, i)) @property def _current_category(self): if self.places[self.current_player] == 0: return 'Pop' if self.places[self.current_player] == 4: return 'Pop' if self.places[self.current_player] == 8: return 'Pop' if self.places[self.current_player] == 1: return 'Science' if self.places[self.current_player] == 5: return 'Science' if self.places[self.current_player] == 9: return 'Science' if self.places[self.current_player] == 2: return 'Sports' if self.places[self.current_player] == 6: return 'Sports' if self.places[self.current_player] == 10: return 'Sports' return 'Rock' def was_correctly_answered(self): if self.in_penalty_box[self.current_player]: if self.is_getting_out_of_penalty_box: print('Answer was correct!!!!') self.purses[self.current_player] += 1 print(self.players[self.current_player] + \ ' now has ' + \ str(self.purses[self.current_player]) + \ ' Gold Coins.') winner = self._did_player_win() self.current_player += 1 if self.current_player == len(self.players): self.current_player = 0 return winner else: self.current_player += 1 if self.current_player == len(self.players): self.current_player = 0 return True else: print("Answer was correct!!!!") self.purses[self.current_player] += 1 print(self.players[self.current_player] + \ ' now has ' + \ str(self.purses[self.current_player]) + \ ' Gold Coins.') winner = self._did_player_win() self.current_player += 1 if self.current_player == len(self.players): self.current_player = 0 return winner def wrong_answer(self): print('Question was incorrectly answered') print(self.players[self.current_player] + " was sent to the penalty box") self.in_penalty_box[self.current_player] = True self.current_player += 1 if self.current_player == len(self.players): self.current_player = 0 return True # Player needs 6 coins to win def _did_player_win(self): return not (self.purses[self.current_player] == 6) from random import randrange def play(number_of_questions): not_a_winner = False game = Game(number_of_questions) game.add('Chet') game.add('Pat') game.add('Sue') while True: game.roll(randrange(1, 7)) if randrange(9) == 7: not_a_winner = game.wrong_answer() else: not_a_winner = game.was_correctly_answered() if not not_a_winner: break if __name__ == '__main__': play(5)
import random secret = random.randint(1,99) guess = 0 tries = 0 print "AHOY! I'm the Dread Pirate Roberts, and I have a sercret!" print " It is a number from 1 to 99. I'll give you 6 tries." while guess != secret and tries < 6: guess = int(raw_input("what's you guess? ")) if guess < secret: print "Too low, ye scurvy dog!" elif guess > secret: print "Too high,landlubber!" tries += 1 if guess == secret: print "Avast! you got is!" else: print "No more guesses!" print "The secret number was", secret
import numpy as np import random def mergeSort(arr): if len(arr) > 1: mid = len(arr)//2 L = arr[:mid] R = arr[mid:] mergeSort(L) mergeSort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i+=1 else: arr[k] = R[j] j+=1 k+=1 while i < len(L): arr[k] = L[i] i+=1 k+=1 while j < len(R): arr[k] = R[j] j+=1 k+=1 def printer(arr): print("{} : MergeSorted Array.".format(arr)) if __name__ == "__main__": array = [] array_size = random.randint(0,10) for i in range(array_size): elem = random.randint(0,10) array.append(elem) print("{} : Unsorted Array.".format(array)) mergeSort(array) printer(array)
#!/usr/bin/env python import re text = '0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f' patternNine = re.compile('9') matchOne = re.search(patternNine, text) print("Positions: %s, %s; Value: %s." %(matchOne.start(), matchOne.end(), matchOne.group(0))) #Positions: 27, 28; Value: 9. values = re.findall('[a-f]', text) print("Values: %s" %values) # Values: ['a', 'b', 'c', 'd', 'e', 'f']
#!/usr/bin/env python import re from pprint import pprint """ Grouping : allows to apply a quantifier to the entire group or to restrict alternation to part of the regex. ( ) Backreference : groups can be accessed as a variable. Backreferences allow to match the same content as previously matched by a capturing group. ( ) \1 ( ) ( ) \1 \2 (( )) ( ) \1 \2 \3 """ text = ''' <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> <div>Not a paragraph, but a div</div> <div></div> ''' # print('{}'.format(re.findall(r'<([dpiv]{1,3})>.+?<\/\1>', text))) # ['p', 'p', 'p', 'div'] # \1 (<([dpiv]{1,3})>.+?<\/\2>) # \2 ([dpiv]{1,3}) # \3 (.+?) tags = re.findall(r'(<([dpiv]{1,3})>(.+?)<\/\2>)', text) print('tags: {}'.format(tags)) # Output: list of tuples -> (\1, \2, \3) tags1 = re.findall(r'<([dpiv]{1,3})>(.+?)<\/\1>', text) print('tags1: {}'.format(tags1)) # ?: --> find content wrapped in tags but does not keep it tags2 = re.findall(r'<([dpiv]{1,3})>(?:.+?)<\/\1>', text) print('tags2: {}'.format(tags2)) # 1. does not keep \1 -> '<([dpiv]{1,3})>(.+?)<\/\1>' # 2. \2 content '[dpiv]{1,3}' assumes as \1 tags3 = re.findall(r'(?:<([dpiv]{1,3})>(.+?)<\/\1>)', text) print('tags3: {}'.format(tags3)) # pprint(tags) # pprint(tags1) # pprint(tags2) # pprint(tags3) print('tags == tags1: {}'.format(tags == tags1)) print('tags == tags2: {}'.format(tags == tags2)) print('tags == tags3: {}'.format(tags == tags3)) print('tags1 == tags2: {}'.format(tags1 == tags2)) print('tags1 == tags3: {}'.format(tags1 == tags3)) print('tags2 == tags3: {}'.format(tags2 == tags3)) # rebuild tags print('{}'.format(re.sub(r'(<(.+?)>)(.+?)(<\/\2>)', r'\1"\3"\4', text))) # for tag in tags: # grp_one, grp_two, grp_three = tag # print('{}'.format(grp_three)) # cpf = '888.471.660-80' # print('{}'.format(re.findall(r'[0-9]{3}\.[0-9]{3}\.[0-9]{3}-[0-9]{2}', cpf))) # print('{}'.format(re.findall(r'((?:[0-9]{3}\.){2}[0-9]{3}-[0-9]{2})', cpf)))
import datetime, random input_words = [] with open("words.txt") as f: lines = f.readlines() for val in lines: input_words.append(val) def bubblesort(num_list): for i in range(len(num_list)): for j in range(len(num_list) - 1, i, -1): if (num_list[j] < num_list[j - 1]): swap(num_list, j, j - 1) def swap(A, x, y): tmp = A[x] A[x] = A[y] A[y] = tmp def perforamnce_bubble_sort(array_size, iterations, input_data): array_size_values = [] time_values = [] for num in range(6): starting_time = datetime.datetime.now() for val in range(iterations): random_array = [input_words[random.randint(0,len(input_data)-1)] for i in range(array_size)] bubblesort(random_array) finishing_time = datetime.datetime.now() array_size_values.append(array_size) time_values.append((finishing_time - starting_time).microseconds) print((finishing_time - starting_time).microseconds, " microseconds taken by bubble sort to sort an array of size ", array_size , "for iterations ", iterations) array_size *= 10 return array_size_values, time_values perforamnce_bubble_sort(10,10,input_words)
#类名 #-首字母大写 #-切记不要使用拼音 class Computer: #构造函数 def __init__(self,vendor,cpu,price): self.vendor = vendor self.cpu = cpu self.price = price def play_game(self): print('play game!') lenovo = Computer('lenovo','intel','5000.00') print(lenovo.cpu) lenovo.play_game()
def revere_str(input_str): stack = [] target = [] for i in input_str: stack.append(i) while len(stack) != 0: target.append(stack.pop()) return target if __name__ == '__main__': print(revere_str('Hello,World!'), end='')
stack=[] left=['{','[',')'] right=['}',']',')'] # 依次遍历每个字符 for i in '{[()]}': # 如果当前字符是左括号 压栈 if i in left: # print(i) stack.append(i) # 如果当前字符是右括号 出栈 if i in right: # print(i) left_parentheses左括号 break终止整个循环 left_parentheses=stack.pop() left_index=left.index( left_parentheses) right_index=right.index(i) if left_index != right_index: print('不匹配') break # 当所有字符都处理完成后 if len(stack) is 0: print('匹配') else: print('不匹配')
""" topological sort of direct graph """ infinity = float("inf") class AdjGraphError(TypeError): pass class Graph: # basic graph class, using adjacent matrix def __init__(self, mat, unconn = 0): vnum1 = len(mat) for x in mat: if len(x) != vnum1: # Check square matrix raise ValueError("Argument for 'GraphA' is bad.") self.mat = [mat[i][:] for i in range(vnum1)] self.unconn = unconn self.vnum = vnum1 def vertex_num(self): return self.vnum def add_edge(self, vi, vj, val = 1): assert 0 <= vi < self.vnum and 0 <= vj < self.vnum self.mat[vi][vj] = val def add_vertex(self): raise AdjGraphError( "Adj Matrix does not support 'add_vertex'") def get_edge(self, vi, vj): assert 0 <= vi < self.vnum and 0 <= vj < self.vnum return self.mat[vi][vj] def out_edges(self, vi): assert 0 <= vi < self.vnum return self._out_edges(self.mat, vi, self.unconn) @staticmethod def _out_edges(mat, vi, unconn): edges = [] row = mat[vi] for i in range(len(row)): if row[i] != unconn: edges.append((i, row[i])) return edges def __str__(self): return "[\n" + "\n".join(map(str, self.mat)) + "\n]"\ + "\nUnconnected: " + str(infinity) class GraphA(Graph): def __init__(self, mat, unconn = 0): vnum1 = len(mat) for x in mat: if len(x) != vnum1: # Check square matrix raise ValueError("Argument for 'GraphA' is bad.") self.mat = [Graph._out_edges(mat, i, unconn) for i in range(vnum1)] self.vnum = vnum1 self.unconn = unconn def add_vertex(self): # For new vertex, return an index allocated self.mat.append([]) self.vnum += 1 return self.vnum def add_edge(self, vi, vj, val = 1): assert 0 <= vi < self.vnum and 0 <= vj < self.vnum row = self.mat[vi] for i in range(len(row)): if row[i][0] == vj: # replace a value for mat[vi][vj] self.mat[vi][i] = (vj, val) return if row[i][0] > vj: break else: i += 1 # adjust for the new entry at the end self.mat[vi].insert(i, (vj, val)) def get_edge(self, vi, vj): assert 0 <= vi < self.vnum and 0 <= vj < self.vnum for i, val in self.mat[vi]: if i == vj: return val return self.unconn def out_edges(self, vi): assert 0 <= vi < self.vnum return self.mat[vi] if __name__ == '__main__': ## g1 = Graph(10) ## g2 = Graph(10, infinity) ## print(str(g1)) ## print(str(g2)) gmat = [[0,0,3,4],[2,0,0,0],[4,1,0,0],[2,0,1,0]] g3 = GraphA(gmat, 0) g3.add_edge(0,3,5) g3.add_edge(1,3,6) g3.add_edge(3,1,9) print(str(g3))
# 1、一分为二 # 左边所有字符入栈,右边所有字符入队列 stack=[] queue=[] left=['a','b','c'] right=['c','b','a'] for i in 'abcdcba': if i in left: stack.append(i) if i in right: queue.append(i) # 2、栈和队列依次各出一个元素 result=[] for i in 'abcdcba': if i in left: result.append(stack.pop()) if i in right: result.append(queue.pop()) print(result) # left_index=left.index(left_zimu) # 左边元素 !=右边元素 不是回文 # # 3、当栈为空且队列为空,就是回文。
"chen",18,"male" #类的首字母是大写 #结点类 class Node: def __init__(self,date): self.date = date self.next = None node1 = Node(1) node2 = Node(2) node3 = Node(3) #node1的下一个是node2 node1.next = node2 #node2的下一个是node3 node2.next = node3 #如何打印单链表的所有节点的数据 print(node1.date) print(node2.date) print(node3.date) node = node1 node = node.next while node is not None: print(node.date) node = node.next
#1、抽象一个节点类 class Node: def __init__(self,data,next): self.data = data self.next = None#使得next为空。 #2、有三个节点 #三个节点的变量信息 n1 = Node(1) n2 = Node(2) n3 = Node(3) #3、表达每一个节点之间的关系 #n1的下一个节点为n2 n1.next = n2 #n2的下一个节点为n3 n2.next = n3
stack = [] # 压栈 stack.append(1) stack.append(2) stack.append(3) # ... stack.append(10) for i in range(1, 11): stack.append(i) for i in 'hello': print(i) a = stack.pop() print(a)
import random studentDict = {'Eric':80, 'Scott':75, 'Jessa':95, 'Mike':66} print("Dictionary Before Shuffling") print(studentDict) keys = list(studentDict.keys()) random.shuffle(keys) ShuffledStudentDict = dict() for key in keys: ShuffledStudentDict.update({key:studentDict[key]}) print("\nDictionary after Shuffling") print(ShuffledStudentDict)
# 1、编程实现字符串反转。 # # 输入:Hello,World! # # 输出:!dlroW,olleH str=input() stack=[] for i in str: stack.append(i) while len(stack)!=0: print(stack.pop(),end="")
# 1. ͸ֵ a = 1 LEFT = ['(','[','{'] # 2. if, for, whileȽṹ # 3. def add(a, b): # β c = a + b return c def print_a(a): print(a) sum = add(1,2) # 1,2 ʵ # 4.
#类名 # - 首字母大写 # - 切记不要使用拼音 class Computer: # 构造函数(名字与以前学习的函数名不同,且变量会自带self) def __init__(self,vendor,cpu,price): self.vendor = vendor self.cpu = cpu self.price = price def play_game(self): print('play game!') lenovo = Computer('lenovo','intel','5000.00') hp = Computer('hp','intel','7000.00') print(lenovo.cpu) print(hp.price) lenovo.play_game() class Student: def __init__(self,name,age,gender): self.name = name self.age = age self.gender = gender Jed = Student('Jed', '18', 'girl') print(Jed.gender) ''' def fly(self): print('flying') print(fly()) ''' # 抽象的方法是不合理的 # 必须符合客观世界的规律 # eg
l=input() a=[] b=[] for i in l: a.append(i) for j in range(1,len(l)+1): b.append(l[-j]) if a==b: print(True) else: print(False)
stack=[] #注释 #1、压栈 push python中压栈的操作是append() # stack.append(1) # stack.append(2) # stack.append(3) # for i in range(1,11): # stack.append(i) #ctrl+d复制 ctrl+x删除 ctrl+/快速注释以及反注释 #2、python中出栈的操作是pop() # print(stack.pop()) # print(stack.pop()) # print(stack.pop()) # while len(stack)!=0: # print(stack.pop()) stack=[] for i in 'hello,world': stack.append(i) result=[] while len(stack) is not 0: result.append(stack.pop()) print(''.join(result))
# coding: utf-8 # 结点类 class Node: # 类有两个属性:data 和 next def __init__(self, data): self.data = data self.next = None node1 = Node(1) node2 = Node(2) node3 = Node(3) # node1的下一个是node2 node1.next = node2 # node2的下一个是node3 node2.next = node3
num = input("请输入括号:") stack = [] for i in num: if i is "("or\ i is "["or\ i is "{": stack.append(i)#如果是左括号,则入栈 elif i == ")": s = stack.pop() if s == "(": continue else: print("不匹配")#是右括号,进行匹配 elif i == "]": s=stack.pop() if s == "[": continue else: print("不匹配")#是右括号,进行匹配 elif i == "}": s=stack.pop() if s == "{": continue else: print("不匹配")#是右括号,进行匹配 if len(stack)%2!=0: print("不匹配") else: print("匹配")
stack = [] # 压栈 stack.append(1) stack.append(2) stack.append(3) # ctrl+d复制 # ctrl+x剪切 # stack.append(10) for i in range(1,11): stack.append(i) stack.pop() print(a)
from LNode import LNode from LList1 import LList1 class LDNode(LNode): # class of Double Linked Nodes def __init__(self, prev, elem, nxt): LNode.__init__(self, elem, nxt) self.prev = prev class LDList(LList1): # class of Double Linked List def __init__(self): LList1.__init__(self) def prepend(self, elem): p = LDNode(None, elem, self.head) self.head = p if self.rear is None: # insert in empty list self.rear = p else: # otherwise, create the prev reference p.next.prev = p def append(self, elem): p = LDNode(self.rear, elem, None) self.rear = p if self.head is None: # insert in empty list self.head = p else: # otherwise, create the next reference p.prev.next = p def pop(self): if self.head is None: raise ValueError e = self.head.elem self.head = self.head.next if self.head is None: self.rear = None # it is empty now else: self.head.prev = None return e def poplast(self): if self.head is None: raise ValueError e = self.rear.elem self.rear = self.rear.prev if self.rear is None: self.head = None # it is empty now else: self.rear.next = None return e if __name__ == '__main__': mlist = LDList() for i in range(10): mlist.prepend(i) for i in range(11, 20): mlist.append(i) #mlist1.printall() while not mlist.isEmpty(): print(mlist.pop()) if not mlist.isEmpty(): print(mlist.poplast())
#{[()] str='{[()]}' stack=[] zuobian=['{' '[' '('] youbian=['}' ']' ')'] #1.依次遍历每一个字符,针对每一个字符进行处理 for i in str: print(i) if i in zuobian: stack.append(i) elif i in youbian: stack.append(i) if stack and stack[-1] == str[i]: stack.pop() else: stack.append(i) #3.如果是右括号 # 出栈并且与当前左括号进行匹配 # 如果匹配则继续 #4.当所有字符都处理完成后 # 栈不为空,返回False # 如果栈为空,则return True
str = input("请输入一个回文数:") original = [] inverted = [] for i in str: original.append(i) while len(original) != 0: inverted.append(original.pop()) for i in str: original.append(i) if original == inverted: print("True") else: print("False")
# 1. 变量定义和赋值 a = 1 LEFT = ['(', '[', '{'] # 2. if, for, while等结构语句 # 3.函数 def add(a,b): # 形参 c = a + b return c sum = add(1,2) # 1,2 实参
class Node: def __init__(self,value): self.value=value self.next=None class List: def __init__(self): self.head=Node(-1) #前插法 def insert_before(self,data): for i in data: node=Node(i) if self.head.next is None: self.head.next=node def list_print(self): node=self.head.next while node: print(node.value) node=node.next if __name__ == '__main__': my_list = List() my_list.insert_before([1, 2, 3, 4, 5]) my_list.list_print()
#括号匹配 ls = [] parens="{[()]}" for i in parens: if i=="("and"{"and"[": ls.append(i) elif i==")"and ls[-1]=="(": ls.pop() elif i=="}"and ls[-1]=="{": ls.pop() elif i=="]"and ls[-1]=="[": ls.pop() if len(ls)==0: print("True") else: print("False")
LEFT = ['(', '[', '{'] RIGHT = [')', ']', '}'] n=input() def check(input_str): stack=[] for ch in input_str: if ch in LEFT: stack.append(ch) elif ch in RIGHT: if len(stack)>0 and RIGHT.index(ch)==LEFT.index(stack.pop()): continue else: return False else: print("The string contains not only parentheses!") return False if len(stack)==0: return True return False # if __name__=="__main__": print(check(n))
str=input() match={'[':']','(':')','{':'}'} stack=[] status=0 for i in str: if i in match.keys(): stack.append(i) elif i in match.values(): if len(stack)!=0 : if match[stack[-1]]==i: stack.pop() else: status=1 break else: status=1 break if status==0: print('True') else: print('False')
# 1. һ class Node: def __init__(self, data): self.data = data self.next = None # 2. n1 = Node(1) n2 = Node(2) n3 = Node(3) n = Node(4) # 3. ÿһ֮Ĺϵ # n1һn2 n1.next = n2 # n2һn3 n2.next = n3
# coding: utf-8 #定义变量保存学生的姓名,年龄,性别 name = "justin" age = 18 gender = 'male' a = 1 b = 2 c = 3 class Student: #构造函数 #类里面的函数,第一个参数都是self def __init__(self,name,age,gender): self.name = name self.age = age self.gender = gender def study(self): print(self.name + 'stydying!') feng = Student('feng', 18, 'male') feng.study() #feng = Student('feng',18,'male') #print(feng.name) #print(feng.age) #print(feng.gender)
# 1. 一分为二 # 左边所有压栈 右边入队列 # 2.栈和队列 一次各出一个元素 # 左边的元素 != 右边的元素 则不是回文 # 3.当栈为空且队列为空时 则是回文 # 编程实现回文数判断。 # # # # 输入:abcdcba # 输出:True stack = [] queue = [] for i in "abcdcba": if i in 'abc': stack.append(i) if i in 'cba': queue.append(i) def check(r1,r2): r1=stack.pop(i) r2=queue.pop(i) while stack and queue is 0: print("true") else: print("false")
def reverse_str(input_str): stack = [] target = [] for ch in input_str: stack.append(ch) while len(stack) != 0: ch = stack.pop() target.append(ch) return target if __name__ == '__main__': reverse_str('Hello,World!')
class Node: def __init__(self,value): self.value = value self.next = None # 初始化节点 node1 = Node(1) node2 = Node(2) node3 = Node(3) for i in range(10): node = Node(i) #表达节点之间的关系 node1.next = node2 node2.next = node3 node3,next = None
# coding: utf-8 #结点类 class Node: #类两个属性data和next def __init__(self,data): self.data = data self.next =None #node1表示变量的定义 node1=Node(1)#结点,‘1’对应data node2=Node(2) node3=Node(3) node4=Node(4) node5=Node(5) #node1的next=node4 node1.next=node4 #node2的下一个是node5 node2.next=node5 #node4的下一个是node2 node4.next=node2 #node5的下一个是node3 node5.next=node3 #如何打印单链表的所有结点的数据 print(node1.data) print(node2.data) print(node3.data) #只告诉第一个结点的变量node1,如何打印所有结点的值 node=node1 print(node.data)#第一个结点的值 #node=node1.next node=node.next while node is not None: print(node.data) node=node.next
shuru=input() stack=[] left=['(','[','{'] right=[')',']','}'] for i in shuru: if i in left: stack.append(i) if i in right: print(right.index(i)) if left[right.index(i)]==stack[-1]: stack.pop() print('成功') else: print('错误')
stack=[] for i in 'hello world': stack.append(i) print(stack) while len(stack)!=0: print(stack.pop())
# -*- coding: UTF-8 -*- #定义变量保存所有学生的姓名、年龄、性别 name='jackson' age=18 gender='male' class student: #构造函数 #在类里面写的函数,的一个函数都是self def __init__(self,name,age,gender): self.name=name self.age=age self.gender=gender def study(self): print(self.name+' is studying') def describe(self): print(self.name+' is a handsome boy') def hobby(self): print(self.name+' is good at dancing and singing') jackson=student('jackson',18,'male') jackson.study() jackson.describe() jackson.hobby() # print(jackson.name) # print(jackson.age) # print(jackson.gender)
class Node: def __init__(self,data,next): self.data = data self.next = None # 有三个结点 n1 = Node(1) n2 = Node(2) n3 = Node(3) # n1的下一个结点是n2 n1.next = n2 # n2的下一个结点是n3 n2.next = n3
# 1.抽象一个结点类 class Node: def __init__(self, data): self.data = data self.next = None # 2.有三个结点 n1 = Node(1) n2 = Node(2) n3 = Node(3) # 3.三个结点之间的关系 # n1的下一个结点是n2 n1.next = n2 # n2的下一个结点是n3 n2.next = n3
#lab2、编程实现括号匹配。输入:{[()]} 输出:True stack = [] LEFT = ['{'] #1.针对每一个字符进行处理 for i in '{[()]}': #2.如果是左括号,则入栈 if i in LEFT: # print(i) KLP stack.append(i) #3.如果是右括号,则进行匹配 if i in RIGHT: #print(i) left_parentheses = stack.pop() left_index = LEFT .index(left_parent) right_index=RIGHT_index(i) if left_index !=right_index: print('不匹配') break #4.当所有的字符都处理完成后, if len(stack) is 0: print('匹配') else: print('不匹配') #判断栈是否为空
# coding: utf-8 # 结点类 class Node: # 类有两个属性:data 和next def __init__(self,data): self.data =data self.next = None node1 = Node(1) node2 = Node(2) node3 = Node(3) # node1的下一个是node2 node1.next = node2 # node2的下一个是node3 node2.next = node3 # 如何打印单链表的所有结点的数据 # print(node1.data) # print(node2.data) # print(node3.data) # 只告诉你第一个结点的变量node1 # 如何打印所有结点的值? node = node1 print(node.data) #第一个结点的值 # node = node1.next node = node.next node = node1 while node is not None: print(node.data)
# -*- coding: UTF-8 -*- #定义变量保存学生的姓名,年龄,性别 name = 'justin' age = 18 gender = 'male' a = 1 b = 2 c = 3 class Student: #构造函数 __init__(self): #类里面写的函数,第一个参数都是self #__函数__都有特殊含义 def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender def study(self): print(self.name + ' studying!') def birth(self): print(self.name + ' 0101') zhong = Student('zhong', 19, 'female') zhong.study() zhong.birth() #print(zhong.name) #print(zhong.age) #print(zhong.gender)
#定义变量保存学生的信息 name = 'justin' age = 18 gender = 'male' name2 = 'bob' age2 = 19 gender2 = 'female' class Student: #构造函数 #类里面写的函数,第一个参数都是self def __init__(self,name,age,gender): self.name = name self.age = age self.gender = gender def study(self): print(self.name + 'studying!') chen = Student('chen',18,'male') chen.study() #chen = Student('chen',18,'male') #print(chen.name) #print(chen.age) #print(chen,gender)
class database: tdb=[] def __init__(self,name,email,phn,salary,designation) : self.name=name self.email=email self.phn=phn self.salary=salary self.designation=designation def create_db(self): self.db={"name":self.name,"email":self.email,"phn":self.phn,"salary":self.salary,"designation":self.designation} return self.db def ad_db(self): database.tdb.append(self.create_db()) return database.tdb obj=database("ajay","ajaynath630@gmail.com",9618035625,56563,"manager") obj2=database("vijay","vijaynath630@gmail.com",9614523625,56463,"jmanager") print(obj.ad_db()) # print(obj2.ad_db())
class stack: def __init__(self,a): self.a=a def push(self,var): x= self.a.append(var) print(x) return x def pop(self): if len(self.a)>0: return self.a.pop() else: return len(self.a)<0 c=[5,8,6,3] b=stack(c) d=b.pop() m=b.push(8) print(d) print(m) from collections import deque
import csv import os file_to_load = os.path.join("Resources", "election_data.csv") file_to_output = os.path.join("analysis", "election_analysis.txt") total_votes = 0 with open(file_to_load) as election_data: reader = csv.reader(election_data header = next(reader) for row in reader: total_votes = total_votes + 1 name = row[2] if name not in candidates: candidaates[name] = 1 else:candidates[name] = candidates[name] + 1 print("Total Votes", total_votes) for candidate_name, vote_count in candidates.items(): percentage = vote_count / total_votes * 100 print(f"{candidate_name}: {vote_count}, {percentage}") #The total number of votes cast #A complete list of candidates who received votes # The percentage of votes each candidate won #The total number of votes each candidate won #The winner of the election based on popular vote. #As an example, your analysis should look similar to the one below:
# ANTAMIS THANASIS # PAPAIOANNOU GIANNIS #Simple lexical-syntax analyser for the EEL language import sys import fileinput print "\n**** LEXICAL/SYNTAX ANALYSER ****\n\nPlease enter a file name: " filename = raw_input() myfile = open(filename) temp = myfile.read(1) line = 0 if(temp == '\n'): line = line + 1 token = "" tk = "" ### lex() function for the lexical analysis def lex(): global temp phrase = "" global line global token while(temp == "\n" or temp == ' ' or temp == '\t'): ## Pass the tabs, spaces and new line characters temp = myfile.read(1) if(temp == "\n"): line = line + 1 if(temp == "/"): ## Check for comments temp = myfile.read(1) if(temp == "\n"): line = line + 1 if(temp == "*"): temp = myfile.read(1) if(temp == "\n"): line = line + 1 while(temp != "*"): temp = myfile.read(1) if(temp == "\n"): line = line + 1 if not temp: print("ERROR: EOF reached : '*/' expected") sys.exit() if(temp == "*"): temp = myfile.read(1) if(temp == "\n"): line = line + 1 if(temp == "/"): temp = myfile.read(1) if(temp == "\n"): line = line + 1 else: print("ERROR:'/' expected") elif(temp == "/"): myfile.readline() temp = myfile.read(1) if(temp == "\n"): line = line + 1 else: token = "divtk" return token while(temp == '\n' or temp == ' ' or temp == '\t'): temp = myfile.read(1) if(temp == "\n"): line = line + 1 if(temp.isalpha()): ## State 1: Check for alphabetical symbol phrase = phrase + temp temp = myfile.read(1) if(temp == "\n"): line = line + 1 count = 2 while(temp.isalpha() or temp.isdigit()): if(count <= 30): phrase = phrase + temp temp = myfile.read(1) if(temp == "\n"): line = line + 1 count += 1 else: while(temp.isalpha() or temp.isdigit()): temp = myfile.read(1) if(temp == "\n"): line = line + 1 print("WARNING: length of variable greater than 30 characters") if(phrase == "program"): ## Check for keywords token = "programtk" elif(phrase == "endprogram"): token = "endprogramtk" elif(phrase == "declare"): token = "declaretk" elif(phrase == "enddeclare"): token = "enddeclaretk" elif(phrase == "if"): token = "iftk" elif(phrase == "then"): token = "thentk" elif(phrase == "else"): token = "elsetk" elif(phrase == "endif"): token = "endiftk" elif(phrase == "while"): token = "whiletk" elif(phrase == "endwhile"): token = "endwhiletk" elif(phrase == "repeat"): token = "repeattk" elif(phrase == "endrepeat"): token = "endrepeattk" elif(phrase == "exit"): token = "exittk" elif(phrase == "switch"): token = "switchtk" elif(phrase == "case"): token = "casetk" elif(phrase == "endswitch"): token = "endswitchtk" elif(phrase == "forcase"): token = "forcasetk" elif(phrase == "when"): token = "whentk" elif(phrase == "endforcase"): token = "endforcasetk" elif(phrase == "procedure"): token = "proceduretk" elif(phrase == "endprocedure"): token = "endproceduretk" elif(phrase == "function"): token = "functiontk" elif(phrase == "endfunction"): token = "endfunctiontk" elif(phrase == "call"): token = "calltk" elif(phrase == "return"): token = "returntk" elif(phrase == "in"): token = "intk" elif(phrase == "inout"): token = "inouttk" elif(phrase == "and"): token = "andtk" elif(phrase == "or"): token = "ortk" elif(phrase == "not"): token = "nottk" elif(phrase == "true"): token = "truetk" elif(phrase == "false"): token = "falsetk" elif(phrase == "input"): token = "inputtk" elif(phrase == "print"): token = "printtk" else: token = "idtk" ## If not keyword, then id of variable elif(temp.isdigit()): ## Check for digit phrase = phrase + temp temp = myfile.read(1) if(temp == "\n"): line = line + 1 while(temp.isdigit()): phrase = phrase + temp if(-32767 <= int(phrase) <= 32767): temp = myfile.read(1) if(temp == "\n"): line = line + 1 elif(int(phrase) > 32767): print("ERROR: number out of bounds(number bigger than 32767)"+phrase) sys.exit() elif(int(phrase) < -32767): print("ERROR: number out of bounds(number smaller than -32767)") sys.exit() if(temp.isalpha()): print("ERROR:letter after number") sys.exit() token= "constanttk" elif(temp == "+"): ## Check for the remaining symbols of the language token = "plustk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 elif(temp == "-"): token = "minustk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 elif(temp == "*"): token = "multk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 elif(temp == "="): token = "equaltk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 elif(temp == "<"): temp = myfile.read(1) if(temp == "\n"): line = line + 1 if(temp == "="): token = "lessequaltk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 elif(temp == ">"): token = "morelesstk" temp = myfile.read(1) else: token = "lesstk" if(temp == "\n"): line = line + 1 elif(temp == ">"): temp = myfile.read(1) if(temp == "\n"): line = line + 1 if(temp == "="): token = "moreequaltk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 else: token = "moretk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 elif(temp == ":"): temp = myfile.read(1) if(temp == "\n"): line = line + 1 if(temp == "="): token = "assignmenttk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 else: token = "colontk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 elif(temp == ","): token = "commatk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 elif(temp == ";"): token = "semicolontk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 elif(temp == "("): token = "rightbrackettk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 elif(temp == ")"): token = "leftbrackettk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 elif(temp == "["): token = "rightsqbrackettk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 elif(temp == "]"): token = "leftsqbrackettk" temp = myfile.read(1) if(temp == "\n"): line = line + 1 elif not temp: print ("WARNING : EOF ") ## End of file reached token = "eoftk" else : ## Not known character print ("ERROR : invalid character: "+ temp + " : line : "+str(line)) sys.exit() temp = myfile.read(1) if(temp == "\n"): line = line + 1 return token ### FUNCTIONS FOR SYNTAX ANALYSIS def program(): global tk if(tk == "programtk"): tk = lex() if (tk== "idtk") : tk=lex() block() if ( tk == "endprogramtk"): tk = lex() print("*** LEXICAL/SYNTAX ANALYSIS COMPLETED SUCCCESSFULLY ***") else: print("ERROR : keyword 'endprogram' expected or ';' after statement "+": line: "+str(line)) sys.exit() else: print("ERROR : program name expected"+": line: "+str(line)) sys.exit() else: print("ERROR : keyword 'program' expected"+": line: "+str(line)) sys.exit() def block(): declarations() subprograms() statements() def declarations(): global tk if(tk == "declaretk"): tk = lex() varlist() if(tk == "enddeclaretk"): tk = lex() else: print ("ERROR : keyword 'enddeclare' expected"+": line: "+str(line)) sys.exit() def varlist(): global tk if(tk == "idtk"): tk = lex() while(tk == "commatk"): tk = lex() if(tk == "idtk"): tk = lex() else: print("ERROR : name of variable expected after ',' "+": line: "+str(line)) sys.exit() def subprograms(): global tk while(tk == "proceduretk" or tk == "functiontk"): procorfunc() def procorfunc(): global tk if(tk == "proceduretk"): tk = lex() if( tk == "idtk"): tk = lex() procorfuncbody() if(tk == "endproceduretk"): tk = lex() else: print("ERROR : keyword 'endprocedure' or ';' expected "+": line: "+str(line)) sys.exit() else: print("ERROR : name of procedure expected"+": line: "+str(line)) sys.exit() elif(tk == "functiontk"): tk = lex() if(tk == "idtk"): tk = lex() procorfuncbody() if(tk == "endfunctiontk"): tk = lex() else: print("ERROR : keyword 'endfunction' or ';' expected "+": line: "+str(line)) sys.exit() else: print("ERROR : name of function expected"+": line: "+str(line)) sys.exit() def procorfuncbody(): formalpars() block() def formalpars (): global tk if( tk == "rightbrackettk"): tk = lex() formalparlist() if(tk == "leftbrackettk"): tk = lex() else: print("ERROR : ')' expected after formal parameters of procedure or function "+": line: "+str(line)) sys.exit() else: print("ERROR : '(' expected before formal parameters of procedure or function "+": line: "+str(line)) sys.exit() def formalparlist(): formalparitem() global tk while(tk == "commatk"): tk = lex() formalparitem() def formalparitem(): global tk if(tk == "intk" or tk == "inouttk"): tk = lex() if(tk == "idtk"): tk = lex() else: print("ERROR: name of formal parameter expected "+": line: "+str(line)) sys.exit() else: print("ERROR: 'in' or 'inout' keyword expected before the name of formal parameter "+": line: "+str(line)) sys.exit() def statements(): global tk statement() while( tk == "semicolontk"): tk = lex() statement() def statement(): if(tk == "idtk"): assignmentstat() elif(tk == "iftk"): ifstat() elif(tk == "whiletk"): whilestat() elif(tk == "repeattk"): repeatstat() elif(tk == "exittk"): exitstat() elif(tk == "switchtk"): switchstat() elif(tk == "forcasetk"): forcasestat() elif(tk == "calltk"): callstat() elif(tk == "returntk"): returnstat() elif(tk == "inputtk"): inputstat() elif(tk == "printtk"): printstat() def assignmentstat(): global tk if(tk =="idtk"): tk = lex() if(tk == "assignmenttk"): tk =lex() expression() else: print("ERROR : ':=' expected"+": line: "+str(line)) sys.exit() else: print("ERROR : name of variable expected before assignment token "+": line: "+str(line)) sys.exit() def ifstat(): global tk if(tk == "iftk"): tk = lex() condition() if(tk == "thentk"): tk = lex() statements() elsepart() if(tk == "endiftk"): tk = lex() else: print ("ERROR : keyword 'endif' or ';' expected "+": line: "+str(line)) sys.exit() else: print("ERROR : keyword 'then' expected"+": line: "+str(line)) sys.exit() else: print ("ERROR : keyword 'if' expected"+": line: "+str(line)) sys.exit() def elsepart(): global tk if(tk == "elsetk"): tk = lex() statement() def repeatstat(): global tk if(tk == "repeattk"): tk = lex() statements() if(tk == "endrepeattk"): tk = lex() else: print("ERROR : keyword 'endrepeat' or ';' expected"+": line: "+str(line)) sys.exit() else: print("ERROR : keyword 'repeat' expected"+": line: "+str(line)) sys.exit() def exitstat(): global tk if(tk == "exittk"): tk = lex() else: print("ERROR : keyword 'exit' or ';' expected "+": line: "+str(line)) sys.exit() def whilestat(): global tk if(tk == "whiletk"): tk = lex() condition() statements() if(tk == "endwhiletk"): tk = lex() else: print("ERROR : keyword 'endwhile' or ';' expected "+": line: "+str(line)) sys.exit() else: print("ERROR : keyword 'while' expected"+": line: "+str(line)) sys.exit() def switchstat(): global tk if( tk == "switchtk"): tk = lex() expression() if(tk == "casetk"): while(tk == "casetk"): tk = lex() expression() if(tk == "colontk"): tk = lex() statements() else: print("ERROR : ':' expected"+": line: "+str(line)) sys.exit() else: print("ERROR : keyword 'case' expected"+": line: "+str(line)) sys.exit() if(tk == "endswitchtk"): tk = lex() else: print("ERROR: keyword 'endswitch' or ';' expected "+": line: "+str(line)) sys.exit() else : print("ERROR : keyword 'switch' expected"+": line: "+str(line)) sys.exit() def forcasestat(): global tk if( tk == "forcasetk"): tk = lex() if(tk == "whentk"): while(tk == "whentk"): tk = lex() condition() if(tk == "colontk"): tk = lex() statements() else: print("ERROR : ':' expected after condition "+": line: "+str(line)) sys.exit() else: print("ERROR : keyword 'when' expected"+": line: "+str(line)) sys.exit() if(tk == "endforcasetk"): tk = lex() else: print("ERROR: keyword 'endforcase' or ';' expected "+": line: "+str(line)) sys.exit() else: print("ERROR : keyword 'forcase' expected"+": line: "+str(line)) sys.exit() def callstat(): global tk if(tk == "calltk"): tk = lex() if(tk == "idtk"): tk = lex() actualpars() else: print("ERROR : name of procedure expected "+": line: "+str(line)) sys.exit() else: print("ERROR : keyword 'call' expected"+": line: "+str(line)) sys.exit() def returnstat(): global tk if(tk == "returntk"): tk = lex() expression() else: print("ERROR : keyword 'return' or ';' expected"+": line: "+str(line)) sys.exit() def printstat(): global tk if(tk == "printtk"): tk = lex() expression() else: print("ERROR : keyword 'print' expected"+": line: "+str(line)) sys.exit() def inputstat(): global tk if(tk == "inputtk"): tk = lex() if(tk == "idtk"): tk = lex() else: print("ERROR : name of input variable expected"+": line: "+str(line)) sys.exit() else: print("ERROR : keyword 'input' expected"+": line: "+str(line)) sys.exit() def actualpars(): global tk if(tk == "rightbrackettk"): tk = lex() actualparlist() if(tk == "leftbrackettk"): tk = lex() else: print("ERROR: ')' expected after actual parameters"+": line: "+str(line)) sys.exit() else: print("ERROR: '(' expected before actual parameters "+": line: "+str(line)) sys.exit() def actualparlist(): global tk actualparitem() while(tk == "commatk"): tk = lex() actualparitem() def actualparitem(): global tk if(tk == "intk"): tk = lex() expression() elif(tk == "inouttk"): tk = lex() if(tk == "idtk"): tk = lex() else: print("ERROR: name of actual parameter expected "+": line: "+str(line)) else: print("ERROR: 'in' or 'inout' keyword expected "+": line: "+str(line)) def condition(): global tk boolterm() while(tk == "ortk"): tk = lex() boolterm() def boolterm(): global tk boolfactor() while( tk == "andtk"): tk = lex() boolfactor() def boolfactor(): global tk if (tk == "nottk"): tk = lex() if( tk == "rightsqbrackettk"): tk = lex() condition() if(tk == "leftsqbrackettk"): tk = lex() else: print( "ERROR : ']' expected after condition "+": line: "+str(line)) sys.exit() else: print("ERROR : '[' expected after 'not' keyword "+": line: "+str(line)) sys.exit() elif(tk == "rightsqbrackettk"): tk = lex() condition() if( tk == "leftsqbrackettk"): tk = lex() else: print( "ERROR : ']' expected after condition"+": line: "+str(line)) sys.exit() elif(tk == "truetk"): tk = lex() elif( tk == "falsetk"): tk = lex() else: expression() relationaloper() expression() def expression(): optionalsign() term() while(tk == "plustk" or tk == "minustk"): addoper() term() def term(): factor() while(tk == "multk" or tk == "divtk"): muloper() factor() def factor(): global tk if(tk == "constanttk"): tk = lex() elif(tk == "rightbrackettk"): tk = lex() expression() if(tk == "leftbrackettk"): tk =lex() else: print("ERROR : ')' expected after expression"+": line: "+str(line)) sys.exit() elif(tk == "idtk"): tk = lex() idtail() def idtail(): if(tk == "rightbrackettk"): actualpars() def relationaloper(): global tk if(tk == "equaltk" or tk == "lessequaltk" or tk == "moreequaltk" or tk == "lesstk" or tk == "moretk" or tk == "morelesstk"): tk = lex() else: print("ERROR: relational operator expected "+": line: "+str(line)) sys.exit() def addoper(): global tk if(tk == "plustk" or tk == "minustk"): tk = lex() else: print("ERROR: '+' or '-' expected "+": line: "+str(line)) sys.exit() def muloper(): global tk if(tk == "multk" or tk == "divtk"): tk = lex() else: print("ERROR: '*' or '/' expected"+": line: "+str(line)) sys.exit() def optionalsign(): global tk if(tk == "plustk" or tk == "minustk"): tk = lex() addoper() tk = lex() program()
def patterntonumber(pattern): if pattern == "": return 0 symbol = pattern[-1] prefix = pattern [:-1] return 4 * patterntonumber(prefix) + symboltonumber(symbol) def symboltonumber(symbol): if symbol == 'A': return 0 if symbol == 'C': return 1 if symbol == 'G': return 2 if symbol == 'T': return 3 test = "ACGCGGCTCTGAAA" k = 2 patternfrequencies =[0] * 4 ** k for i in range(len(test)-k+1): pattern = test[i:i+k] x = patterntonumber(pattern) patternfrequencies[x] = patternfrequencies [x] + 1 z = "" for i in patternfrequencies: z += str(i) + " " print (z)
#Program Title: Quiz grades ''' PROGRAM REQUIRMENTS Write a Python program to compute the average quiz grade for a group of five students. Your program should include a list of five names. Using a for loop, it should successively prompt the user for the quiz grade for each of the five students. Each prompt should include the name of the student whose quiz grade is to be input. It should compute and display the average of those five grades and the highest grade. You should decide on the names of the five students. ''' total = 0 def find_avg(aList): #created a function to determine the avg of a list of numbers t = sum(aList) total = t/len(aList) return total students = ["Johnathan Joestar","Joseph Joestar","Jotaro Kujo","Josuke Higashikata","Giorno Giovanna"] #created list of 5 students grades = [] for student in students: #loop through the list of students and prompt for a grade input grade = int(input("Enter the quiz grade for " + student + ":")) grades.append(grade)#add the entered grade to the list of grades x = 0 while x < len(students): print(students[x], grades[x]) #print all students and grades x += 1 print("The highest quiz score is:", max(grades)) #print highest grade avg_grade = find_avg(grades) print("The average quiz score is", avg_grade) #print average grade
#Program Title: Flooring Calculator ''' PROGRAM REQUIRMENTS a Python program that accepts at least three values as input, performs some computation and displays at least two values as the result. The program must include an if statement that performs different computations based on the value of one of the inputs. Include comments in your program that describe what the program does. ''' import math tile_size = input("Please choose a floor type - laminate or ceramic: ") if (tile_size == "laminate"): size = 0.25 cost = 1.78 elif(tile_size == "ceramic"): size = 0.5625 cost = 1.19 else: print("That is an incorrect flooring type") room_w = eval(input("Please enter the width of the room (ft): ")) room_l = eval(input("Please enter the length of the room (ft): ")) floor = float(room_w * room_l) total = round(float(floor/size), 2) f_cost = round(cost * total, 2) print("You will need: ", math.ceil(total), "tiles of ", tile_size) print (total) print("It will cost $", f_cost)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-01-02 09:47:42 # @Author : Cheung Rui (1484659706@qq.com) # @Link : https://www.cnblogs.com/mangmangbiluo/ # @Version : $Id$ """ 74. Search a 2D Matrix Medium 616 77 Favorite Share Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. Example 1: Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 Output: true Example 2: Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 Output: false """ class Solution: def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix: return False cowlen, rowlen = len(matrix), len(matrix[0]) left, right = 0, cowlen*rowlen -1 smallnum, bignum = matrix[0][0], matrix[cowlen-1][rowlen-1] while(left<=right): mid = (left + right)//2 cow, row = divmod(mid, rowlen) midnum = matrix[cow][row] if midnum == target: return True elif midnum < target: left, smallnum = mid+1, midnum else: right, bignum = mid-1, bignum return False
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-04-11 18:37:27 # @Author : Cheung Rui (1484659706@qq.com) # @Link : https://www.cnblogs.com/mangmangbiluo/ # @Version : $Id$ """ Given a binary tree, flatten it to a linked list in-place. For example, given the following tree: 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 """ """ 就是将二叉树按照深度优先的顺序进行遍历,变成一个每个节点都只有右儿子的树 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ if not root: return None node = root nodelist = [] if node.right: nodelist.append(node.right) if node.left: nodelist.append(node.left) while nodelist: n = nodelist[-1] nodelist.pop() if n.right: nodelist.append(n.right) if n.left: nodelist.append(n.left) node.left = None node.right = n node = n
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-12-31 17:43:13 # @Author : Cheung Rui (1484659706@qq.com) # @Link : https://www.cnblogs.com/mangmangbiluo/ # @Version : $Id$ """ 73. Set Matrix Zeroes Medium 777 153 Favorite Share Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. Example 1: Input: [ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ] Example 2: Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ] """ class Solution: def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ m, n = len(matrix), len(matrix[0]) for i in range(m): for j in range(n): if matrix[i][j] == 0: matrix[i][j] = None for i in range(m): for j in range(n): if matrix[i][j] == None: matrix[i][j] = 0 for k in range(m): if matrix[k][j] != None: matrix[k][j] = 0 for k in range(n): if matrix[i][k] != None: matrix[i][k] = 0
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-12-26 21:34:23 # @Author : Cheung Rui (1484659706@qq.com) # @Link : https://www.cnblogs.com/mangmangbiluo/ # @Version : $Id$ """ 71. Simplify Path Medium 319 964 Favorite Share Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" path = "/a/../../b/../c//.//", => "/c" path = "/a//b////c/d//././/..", => "/a/b/c" In a UNIX-style file system, a period ('.') refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period ("..") moves up a directory, so it cancels out whatever the last directory was. For more information, look here: https://en.wikipedia.org/wiki/Path_(computing)#Unix_style Corner Cases: Did you consider the case where path = "/../"? In this case, you should return "/". Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". In this case, you should ignore redundant slashes and return "/home/foo". """ """ 有路径就进栈,有..就出栈,.就跳过 """ class Solution: def pushDir(self, pathlist, dirname): """ 将dirname加入路径列表中 """ if dirname == "" or dirname==".": pass elif dirname == "..": if pathlist: pathlist.pop() else: pathlist.append(dirname) def simplifyPath(self, path): """ :type path: str :rtype: str """ pathlist = [] dirname = "" for i in path: if i != "/": dirname += i else: self.pushDir(pathlist, dirname) dirname = "" self.pushDir(pathlist, dirname) return "/"+"/".join(pathlist)
import math radius = float (input("Enter circle radius: ")) pi = 3.14 circumference = 2 * pi * radius area = pi * (radius ** 2) print(" Circumference = %.1f" %circumference) print(" Area = %.1f" %area)
""" Day 8 Recursion demonstration """ """ @param x An int. We want the sum from 1 to x @return The sum from 1 to x An iterative implentation of the sum from 1 to x """ def sum_iterative(x): sum = 0 # define an accumulator while x >= 0:# Iterate backwards from x to 0 sum += x # Add x to sum x -= 1 # Subtract 1 from x return sum # Return the final sum """ @ param x An int. We want the sum from 1 to x @return The sum of 1 to x A recursive implementation of the sum from 1 to x """ def sum_recursion(x): if x == 0: #BASE CASE return 0 elif x > 0: #RECURSIVE CASE return x + sum_recursion(x - 1) else: return 0 """ @param n is the number to run factorial on @return returns the factorial of n iterative way to find n! """ def factorial_iterative(n): output = 1 while n > 0: output *= n n -= 1 return output """ @param n is the number to find the factorial of @return returns n! recursive method to find n! """ def factorial_recursive(n): if n == 0: return 1 elif n > 0: return n * factorial_recursive(n - 1) else: return 0 """ @ param n the number to find the fibonacci term of @ return the n th term of the fibonacci sequence iterative way to find the nth term of the fibonacci sequence """ def fib_iterative(n): x = 1 y = 1 while n > 2: z = y y += x x = z n -= 1 return y """ @ param n the number to find the fibonacci term of @ return the n th term of the fibonacci sequence recursive way to find the nth term of the fibonacci sequence """ def fib_recursive(n): if n == 1 or n == 2: return 1 elif n > 2: return fib_recursive(n - 1) + fib_recursive(n - 2) else: return 0 """ """ def main(): print "Welcome to recursion!" print sum_iterative(5) print sum_recursion(6) print factorial_iterative(5) print factorial_recursive(6) print fib_iterative(5) print fib_recursive(6) if __name__ == "__main__": main()
import turtle def main(): wn = turtle.Screen() # Make the screen pop up Chris = turtle.Turtle() # Make the turtle in the screen and name it "Chris" Chris.color("Green") # Change Chris' color to blue Chris.shape("turtle") # Change Chris into a turtle counter = 1 while counter <= 5: Chris.forward(51) Chris.right(50) counter += 1 wn.exitonclick() if __name__ == "__main__": main()
def main(): str = "" for x in range(int(raw_input(""))): str += "&" print str if __name__ == "__main__": main()
class Vector: def __init__(self, *args): self.dimensions = [] for value in args: if type(value) == int: self.dimensions.append(value) if type(value) == list: for element in value: self.dimensions.append(element) def __str__(self): return "Vector: " + str(self.dimensions) def add_vectors(vector1, vector2): output = [] for i in range(len(vector1.dimensions)): output.append(vector1.dimensions[i] + vector2.dimensions[i]) return output def mult_vectors(vector1, vector2): product = 0 for i in range(len(vector1.dimensions)): product += (vector1.dimensions[i] * vector2.dimensions[i]) return product def sub_vectors(vector1, vector2): output = [] for i in range(len(vector1.dimensions)): output.append(vector1.dimensions[i] - vector2.dimensions[i]) return output class Matrix: def __init__(self, *args): self.matrix = [] for value in args: self.matrix.append(value) def __str__(self): for x in range(len(self.matrix)): print str(self.matrix[x]) def mult_matrix(m1, m2): def main(): matrix1 = Matrix([1, 2, 3], [1, 2, 3], [1, 2, 3]) print matrix1 if __name__ == "__main__": main()
class Car: """ Instantiates a new instance of the Car class """ def __init__(self, color, square_area, engine_size, brand): self.color = color self.square_area = square_area self.engine_size = engine_size self.brand = brand """ Returns a string detailing the car's attributes """ def __str__(self): result = "" result += "Car:\n" result += "The color of the car is " + self.color + "\n" result += "The square area of the car is " + str(self.square_area) + "\n" result += "The engine size of the car is " + str(self.engine_size) + "\n" result += "The brand of the car is " + self.brand + "\n" return result """ @self The reference Car object @param new_color The color the we want to change to Changes the current value of self.color to new_color """ def change_color(self, new_color): self.color = new_color """ @self The referenced Car object print "VROOM!" self.engine_size times """ def rev_engine(self): for x in range(self.engine_size): print "VROOM!" """ @self The referenced Car object prints "We're driving!!!!!!"! """ def drive(self): print "We're driving!!!!!!!" """ @car1 The first Car object to fight @car2 The second Car object to fight Two cars will fight in mortal combat """ def fight(car1, car2): if car1.square_area > car2.square_area: print "Car 1 defeats Car 2 in a fight!" elif car2.square_area > car1.square_area: print "Car 2 defeats Car 1 in a fight!" else: print "Car 1 and Car 2 come to a mutual understanding and play Scrabble!" def main(): Car_A = Car("Hotpink", 100, 7, "Ford") Car_B = Car("Green", 101, 8, "Honda") Car.fight(Car_A, Car_B) if __name__ == "__main__": main()
""" Filename:Turtle_Three.py Chris is trying to draw a pentagon (5-sided polygon) It looks a little odd, can you edit the code so that each side is the same length? """ import turtle def main(): wn = turtle.Screen() # Make the screen pop up Chris = turtle.Turtle() # Make the turtle in the screen and name it "Chris" Chris.color("Blue") # Change Chris' color to blue Chris.shape("turtle") # Change Chris into a turtle Chris.left(70) Chris.forward(70) Chris.left(70) Chris.forward(70) Chris.left(70) Chris.forward(70) Chris.left(70) Chris.forward(70) Chris.left(70) Chris.forward(70) wn.exitonclick() if __name__ == "__main__": main()
''' Problem link https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given scores. Store them in a list and find the score of the runner-up. Input Format The first line contains n. The second line contains an array A[] of n integers each separated by a space. Constraints 2 <= n <= 10 -100 <= A[i] <= 100 Output Format Print the runner-up score. Sample Input : 5 2 3 6 6 5 Sample Output : 5 Explanation 0 Given list is [2,3,6,6,5] . The maximum score is 6, second maximum is 5. Hence, we print 5 as the runner-up score. ''' if __name__ == '__main__': n = int(raw_input()) arr = map(int, raw_input().split()) # the sorted built-in function of set creates a list of a set variable and then you can apply slicing. print sorted(set(arr))[-2] #Python List comprehension #print max([x for x in arr if x != max(arr)])
from bs4 import BeautifulSoup with open(file="website.html", mode="r") as webpage: content = webpage.read() print(content) soup = BeautifulSoup(content, "html.parser") # To get the webpage title with tag print(soup.title) # To get the webpage title tag print(soup.title.name) # To get webpage title content as a string print(soup.title.string) # To get all the anchor tags all_anchor_tags = soup.find_all(name="a") # this will make a list call all_anchor_tags print(all_anchor_tags) # you can loop through all_anchor_tags list for tag in all_anchor_tags: # to get text of all a tags in all_anchor_tags list print(tag.getText()) # to get a specific html attributes like eg: href print(tag.get("href")) # select html lines based on its attributes heading = soup.find(name="h1", id="name") print(heading) print(heading.getText()) # [Selecting a Class] select html line based on its tag name and class name section_heading = soup.find(name="h3", class_="heading") print(section_heading) print(section_heading.getText()) print(section_heading.get("class")) # using css selector method inside beautiful soup # selector="p a" means anchor tag is inside a paragraph tag link = soup.select(selector="p a") print(link) # selecting based on id selector name = soup.select(selector="#name") print(name)
#!/usr/bin/env python """ Sort an array of 10,000,000 randomly created integers.""" import random import time # Create the array - well, actually a listn n = 10000000 array = [random.randint(0, 1000000000) for i in range(n)] # Sort it and measure time t0 = time.time() sorted_array = sorted(array) t1 = time.time() # Output the time print("%0.2f seconds for sorting %i integers." % (t1-t0, n))
# Mehmet SAMUR aka Yves Xavier # This is the easy way to learn Python Day6 #Break Statement username = "myusername" password = "passw0rd" while True: quest1 = input("username: ") quest2 = input("password: ") if quest1 == username and quest2 == password: print("Success") break else: print("Wrong Username or Password") print("Please try again.) #Continue Statement while True: s = input("Enter a number: ") if s == "cancel": break if len(s) <= 3: continue print("Enter a 3 digit number. ") #another example number = "23430234034340345670234509585609945459954995400000000000009454504500000" for i in number: if i == "0": continue else: print(i) # In(in) keyword answer = input("Are you sure wanna quit? [Y/N] ") if answer in "Y" or "y": print("Good bye.") elif answer in "N" or "n": print("Ok buddy.") #Guessing number Game import random numbergame = random.randint(0, 100) message = "I got a secret number\nCan you guess it?\nPress \"q\" for quit . " print(message) while True: guess = input("Enter guess") if guess == "q": print("Quitting bitch.") break guess = int(guess) if guess == numbergame: print("Congrats. number is true.") break if guess < numbergame: print("Enter higher number.") elif guess > numbergame: else: print("C'mon you can do it.") #this will write letter byYvesXavier letter 'YvesXavier' #for tdoay this is enough. See you on day 7.
#8.1 # y; g; 9; Myst; True; True; True; True; True #8.2 def prefixes(): prefixes = "JKLMNOPQ" suffix = "ack" for letter in prefixes: if(letter== "O" or letter == "Q"): print(letter + "u" + suffix) else: print(letter + suffix) #prefixes() #8.3 def count_char(x,y): count = 0 for i in y: if(i == x): count += 1 return count #8.4 def count_lett(x,y): count = 0 gui = "yes" while gui == "yes": count = y.find(x) print(count) gui = input("continue? yes/no") return count #8.5 x = '''"Eh bien la chose importante à vous dire, citation de Michelet, qui est un grand écrivain, mais mon estime pour l'historien n'a cessé de décroître ; Michelet vous affirme ceci, "Ce qu'il importe de savoir, c'est à quel point les idées d'intérêt furent étrangères au mouvement de 89"''' import string def rem_punct(x): clean = "" for i in x: if i not in string.punctuation: clean += i return clean def ex85(x): counte = 0 countw = 0 x = x.split() for i in x: countw += 1 if (i.find("e") > 0): counte+=1 return "Yout text contains {0} words, of which {1}, ({2}%) contain an e".format(countw, counte, int((counte/countw)*100)) print(ex85(rem_punct(x))) #8.6 def mult_table(y,x): clean = "" for i in range(1,x+1): if(y*i>9 and y*i < 100): clean = clean + " " + str(y*i) elif(y*i>=100): clean = clean + " " + str(y*i) else: clean = clean + " " + str(y*i) return clean def print_table(x): top1 = " " top2 = "-----" clean = "" for i in range(1, x+1): if(i>8): top1 = top1 + str(i) + " " top2 += "-----" else: top1 = top1 + str(i) + " " top2 += "-----" print(top1) print(top2) for i in range(1, x+1): if (i>9): print("{0}:".format(i)+mult_table(i,x)) else: print("{0}: ".format(i) + mult_table(i, x)) print_table(5) #8.7 def reverse(x): clean = "" for i in range(len(x)): clean = clean + x[len(x)-1-i] return clean #8.8 def mirror(x): return x + reverse(x) #8.9 def remove(x,y): clean = "" for i in y: if not(x==i): clean += i return clean #8.10 def palin(x): clean = "" if len(x)%2 == 0: clean = x[:int(len(x)/2)] else: clean = x[:int(len(x)/2)] + x[int(len(x)/2)] x = x[:int(len(x)/2)] + x[int(len(x)/2)] + x[int(len(x)/2):] if x == mirror(clean): return "yes" else: return "no"
# interfaces for data Robert Chapman Jul 26, 2018 # input is defined # output is called # inter layer connecting is done by defining your output as the others input # routing and coupling is provided by interface # Define 2 layers: # layer1, layer2 = Layer(), Layer() # To connect layer 1 to layer 2: # layer2.inner.plugin(layer1) # For bottom of a stack: # endpoint = Interface() # layer1.inner.plugin(endpoint) class Signal(object): def __init__(self, *args): self.disconnect() def emit0(): self.__signal() def emit1(arg): self.__signal(arg) n = len(args) if n == 0: self.emit = emit0 elif n == 1: self.emit = emit1 else: raise Exception("Error: No method for more than 1 argument!") def nothing(*args): pass def disconnect(self): self.__signal = self.nothing def connect(self, action=nothing): self.__signal = action def connectsTo(self): return self.__signal class Interface(object): def __init__(self, name='interface'): self.input = Signal(object) self.output = Signal(object) self.name = name self.input.connect(self.no_input) self.output.connect(self.no_output) self.signals = [self.input, self.output] def report(self): def extract(s): if s.find('<function ') > -1: return s.split()[1] if s.find('<bound method') > -1: return s.split()[2] return s if self.input.connectsTo() == self.input.nothing: inputName = 'nothing' elif self.input.connectsTo() == self.no_input: inputName = 'no_input' else: inputName = extract('{}'.format(self.input.connectsTo())) if self.output.connectsTo() == self.output.nothing: outputName = 'nothing' elif self.output.connectsTo() == self.no_output: outputName = 'no_output' else: outputName = extract('{}'.format(self.output.connectsTo())) print('Interface: {} input: {} output: {}'.format(self.name, inputName, outputName)) def no_input(self, data): print("Error, {}.input not defined".format(self.name)) def no_output(self, data): print("Error, {}.output unplugged".format(self.name)) def unplug(self): self.output.connect(self.no_output) def plugin(self, inner): inner.output.connect(self.input.emit) self.output.connect(inner.input.emit) def loopback(self): def in2out(data): self.output.emit(data) self.input.connect(in2out) def disconnect(self): for signal in self.signals: signal.disconnect() class Layer(Interface): def __init__(self, name='Layer'): Interface.__init__(self, name) self.inner = Interface(name + '.inner') self.signals += [self.inner.input, self.inner.output] def unplug(self): super(Layer, self).unplug() self.inner.unplug() def passthru(self): def downthru(data): self.inner.output.emit(data) self.input.connect(downthru) def upthru(data): self.output.emit(data) self.inner.input.connect(upthru) def plugin(self, inner): self.inner.plugin(inner) from time import sleep class Port(Interface): nodata = bytearray() def __init__(self, address=0, name=None, hub=None): Interface.__init__(self) self.address = address self.data = self.nodata self.name = name self.hub = hub self.__opened = False self.ioError = Signal() self.ioException = Signal() self.closed = Signal() self.opened = Signal() self.signals += [self.ioError, self.ioException, self.closed, self.opened] def is_open(self): return self.__opened def open(self): # if self.is_open(): # print ("Error: Open error: {} is already open".format(self.name)) self.__opened = True self.input.connect(self.send_data) self.opened.emit() def close(self): if self.is_open(): self.__opened = False self.closed.emit() else: print ("Error: Close error: {} is not open".format(self.name)) def send_data(self, data): self.data.append(data) def get_data(self): data = self.data self.data = self.nodata return data def wait(self, milliseconds): sleep(milliseconds/1000.) class Hub(object): __allports = {} update = Signal() def __init__(self, name='Hub'): self.name = name self.__myports = {} def ports(self): # some instance return list(self.__myports.values()) def all_ports(self): # class of all hubs return list(Hub.__allports.values()) def add_port(self, port): if not self.get_port(port.name): Hub.__allports[port.name] = port self.__myports[port.name] = port self.update.emit() def remove_port(self, port): if Hub.__allports.get(port.name): Hub.__allports.pop(port.name) self.__myports.pop(port.name) self.update.emit() def get_port(self, name): return Hub.__allports.get(name) def close(self): for port in self.ports(): self.remove_port(port) port.close() def wait(self, milliseconds): sleep(milliseconds/1000.) if __name__ == "__main__": s = Signal() def lo(): print('lo') s.connect(lo) s.emit() s = Signal(object) def hi(data): print('input: {}'.format(data)) s.connect(hi) s.emit('data') i = Interface('inter') i.report() i.output.connect(hi) i.loopback() i.input.emit('test1') i.report() t = Interface('top') t.report() l = Layer('lay') b = Interface('bot') b.report() t.input.connect(hi) t.plugin(b) b.loopback() t.output.emit('testtbl') t.plugin(l) l.plugin(b) t.report() l.passthru() l.report() t.output.emit('testlayer') t.unplug() l.unplug() b.unplug() t.report() l.report() b.report() class test(object): def didopen(self): print("port '{}' at address '{}' is open".format(self.port.name, self.port.address)) def didclose(self): print("port '{}' closed".format(self.port.name)) def test(self): try: jp = Hub() jp.add_port(Port(12345, 'test port', jp)) self.port = j = jp.get_port(jp.ports()[0].name) j.report() j.opened.connect(self.didopen) j.closed.connect(self.didclose) j.report() j.open() if j.is_open(): print("yes its open") else: print("port not found") if set(jp.all_ports()) - set(jp.ports()): print("ERROR: all ports not the same as ports") jp.remove_port(jp.get_port(j.name)) if len(set(jp.all_ports()).union(set(jp.ports()))) != 0: print("ERROR: all ports not removed. All{}, ports {}".format(jp.all_ports(), jp.ports())) jp.close() finally: pass t = test() t.test()
charList = ['a','b','c'] setLen = len(charList) len = 2**setLen for i in range(len): for j in range(setLen): if i&(1<<j): print(charList[j],end = ' ') print()
def grammes_stiles(a): b=list(zip(*a)) return [list(i) for i in b] def flatten_list(a): """ Returns a one dimension list from the multidimensional list of numbers a """ c=''.join([i for i in str(a)if i not in'[] ']).strip(',') return list(map(int,c.split(','))) def check_balance(a): stack=[] maches={'(':')', '[':']', '{':'}'} for i in a: if i in maches: stack.append(i) elif i in maches.values(): if (not stack) or maches[stack[-1]]!=i: return False stack.pop() return not stack a=[[[2,3],[12,78],[11,2],[1,0]],[[7,2],[3,2],[7,5],[4,2]],[[4,1],[2,1],[78,0],[45,12]],[[12,3],[3,7],[5,6],[12,8]],[[4,5],[6,2],[1,0],[5,6]]] def get_shape(a): """ Returns the shape of the multidimensional array of numbers a """ bathos=0; for i in str(a): if i!='[': break bathos+=1 shape=[] while bathos>0: shape.append(len(a)) a=a[0] bathos-=1 return shape from functools import reduce def get_items(a): """ Returns the number of items of the multidimensional array of numbers a """ return reduce(lambda x,y :x*y, get_shape(a)) def create_list(ind,*b): """(contend of list, 1st list dimension, \ [other list dimensions])--> n dimennsions list \ n must be 1-6" """ a=len(b) #list dimensions d=1 #a pointer that grows to the list dimensions (a) while True: pinakas=[ind]*b[0] # 1 dimension list d+=1 # increase the pointer if d>a: break #control if pointer is larger to dimensions if not continous for i in range(b[0]): # add a second dimension pinakas[i]=[ind]*b[1] d+=1 if d>a: break for i in range(b[0]): for j in range(b[1]): pinakas[i][j]=[ind]*b[2] d+=1 if d>a: break for i in range(b[0]): for j in range(b[1]): for k in range(b[2]): pinakas[i][j][k]=[ind]*b[3] d+=1 if d>a: break for i in range(b[0]): for j in range(b[1]): for k in range(b[2]): for l in range(b[3]): pinakas[i][j][k][l]=[ind]*b[4] d+=1 if d>a: break for i in range(b[0]): for j in range(b[1]): for k in range(b[2]): for l in range(b[3]): for m in range(b[4]): pinakas[i][j][k][l]=[ind]*b[5] d+=1 if d>a: break return pinakas def reshape1(a,*dimesions): dimesions=list(dimesions) if len(dimesions)>1: current = dimesions.pop() else: # finished! return a result=[] index=0 while index<len(a) : result.append(list(a[index:index+current])) index+=current return reshape1(result,*dimesions)
print("Hello, World!") def add(number1, number2): return number1 + number2 somenum = 3 answer = add(2, somenum) print("2 + " + str(somenum) + " = " + str(answer))
class TooMuchDiscount(Exception): def __init__(self): self.text = 'Слишком большая максимальная скидка' def discounted(price, discount, max_discount=20): try: price = abs(float(price)) discount = abs(float(discount)) max_discount = abs(int(max_discount)) if max_discount >= 100: raise TooMuchDiscount if discount >= max_discount: return price else: return price - (price * discount / 100) except ValueError: return 'Исключение ValueError' except TypeError: return 'Исключение TypeError' except TooMuchDiscount as ex: return ex.text def main(): print(discounted(100, 10)) print(discounted(100, 30)) print(discounted(100, 30, 50)) print(discounted(100, 30, 150)) print(discounted(100, [])) print(discounted(100, 30, 'abc')) if __name__ == '__main__': main()
def two_strings(string_one, string_two): if isinstance(string_one, str) and isinstance(string_two, str): if string_one == string_two: return 1 elif string_two == 'learn': return 3 elif len(string_one) > len(string_two): return 2 else: return 0 def test(a, b): res = two_strings(a, b) print('Строка1 = {}, Строка2 = {}, Результат = {}'.format(a, b, res)) if __name__ == '__main__': test(1, 2) test('learn', 2) test('learn', 'learn') test('learn', 'lear') test('lear1', 'learn') test('learn', 'lear1')