text
stringlengths
37
1.41M
# find all divisible numbers of user input and push to array number = int(raw_input("choose a number to see what is divisible: ")) divsibleNum = list(range(2, number+1)) divisorList = [] for elem in divsibleNum: if number % elem == 0: divisorList.append(elem) print (divisorList)
data_box = [2, 4, 5, 1,"Cat", "Asset"] # You can input from user to check. def liner_Search(databox, target): for loop1 in range(len(data_box)): if databox[loop1] == target: return True else: return False print(liner_Search(data_box,"Asset"))
#first_no = input("Enter the first number: ") #second_no = input("Enter the second number: ") #operation = input("Choose the operation (+, -, *, /): ") while True: try: first_no = int(input("Enter the first number: ")) second_no = int(input("Enter the second number: ")) except ValueError: print("Numbers were invalid") continue else: break operation = input("Choose the operation (+, -, *, /): ") if operation == '+': print("The answer is {}".format((int(first_no) + int(second_no)))) elif operation == '-': print("The answer is {}".format((int(first_no) - int(second_no)))) elif operation == '*': print("The answer is {}".format((int(first_no) * int(second_no)))) elif operation == '/': print("The answer is {}".format((int(first_no) / int(second_no)))) else: print("Operation is invalid")
# -*- coding: utf-8 -*- import sys import numpy as np import cv2 ###donne de nos questions class Question: def __init__(self, question,choices, correct): self.question = question self.choices = choices self.correct = correct from collections import namedtuple q = [None] * 10 Question = namedtuple("Question", "question choices correct") q[0] = Question("Le premier reseau informatique est ne",["en 2000","en 1980","au debut des annees 60","aucune de ces reponses n'est correcte"],[3]) q[1] = Question("Quel est le cable utilise dans un reseau 10 Base T",["coaxial fin","paire torsadee","ondes hertziennes"],[2]) q[2] = Question("Dans un LAN Ethernet, le support",["n'est pas partage et les collisions n'existent pas.","est partage, les collisions existent et representent un phénomène anormal","est partage, les collisions existent et représentent un phenomene normal.","aucune de ces reponses n'est correcte"],[3]) q[3] = Question("Un réseau LAN peut relier Bruxelles et Londres :",["oui","non","parfois"],{2}) q[4] = Question("Un réseau LAN dépend d'un opérateur télécom pour fonctionner correctement :",["oui","non","parfois"],[3]) q[5] = Question("A chaque extremite d'un reseau 10 Base 2, il faut placer :",["une prise RJ45","un bouchon","une clé USB"],[2]) q[6] = Question("Avec une topologie physique en étoile, l'élément qui effectue une diffusion du signal s'appelle un :",["routeur","commutateur","concentrateur"],[3]) q[7] = Question("Dans une topologie physique en étoile, quel est l'élément qui permet d'envoyer une trame sur un port particulier :",["hub","commutateur","routeur"],[2]) q[8] = Question("Dans un réseau Ethernet, pendant l'émission d'une trame, un poste :",["reste inactif","continue l'écoute du signal","envoie une trame"],[2]) q[9] = Question("Une adresse IPv4 est composée de :",["6 octets","4 nombres compris entre 0 et 256","4 nombres compris entre 0 et 255"],[3]) def angle_cos(p0, p1, p2): d1, d2 = (p0-p1).astype('float'), (p2-p1).astype('float') return abs( np.dot(d1, d2) / np.sqrt( np.dot(d1, d1)*np.dot(d2, d2) ) ) def find_squares(img): img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) squares = [] for gray in cv2.split(img): for thrs in range(0, 255, 100): if thrs == 0: bin = cv2.Canny(gray, 0, 50, apertureSize=5) bin = cv2.dilate(bin, None) else: retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY) bin, contours, hierarchy = cv2.findContours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: cnt_len = cv2.arcLength(cnt, True) cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True) if len(cnt) == 4 and cv2.contourArea(cnt) > 50 and cv2.isContourConvex(cnt): cnt = cnt.reshape(-1, 2) max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in range(4)]) if max_cos < 0.1: l1 = cnt[0] - cnt[1] #l2 = cnt[1] - cnt[2] if(abs(np.sqrt(np.dot(l1,l1))-13)< 3 ): squares.append(cnt) return squares def find_circles(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 2, 15, param1=500, # plus grand, le meilleur param2=50, minRadius=15, # 15 maxRadius=20) # 20 circles = np.uint16(np.around(circles)) return circles img = cv2.imread('../images/scanner_jpg.jpg') squares = find_squares(img) circles = find_circles(img) print( len(squares)) #print squares # 95 squares total #cv2.drawContours( img, squares, -1, (0, 255, 0), 3 ) #cv2.imshow('squares', img) #k = cv2.waitKey(0) #if k == 27: # cv2.destroyAllWindows() img1 = cv2.imread('../images/scanner_jpg2.jpg') squares1 = find_squares(img1) circles1 = find_circles(img1) print (len(squares1)) #cv2.drawContours( img1, squares1, -1, (0, 255, 0), 3 ) #cv2.imshow('squares1', img1) #k = cv2.waitKey(0) #if k == 27: # cv2.destroyAllWindows() print (circles) print (circles1) def insertSort(a): liste = a for i in range(len(liste)-1): #print a,i for j in range(i+1,len(liste)): if liste[i]>liste[j]: temp = liste[i] liste[i] = liste[j] liste[j] = temp return liste def circles_ordre(circles): liste = [] circles_ordre = circles * 0 print (circles) for i in range(len(circles[0])): liste.append(circles[0][i][0]+circles[0][i][1]) #print liste liste_ordre = insertSort(liste) liste = [] for i in range(len(circles[0])): liste.append(circles[0][i][0]+circles[0][i][1]) print (liste) print (liste_ordre) for i in range(len(circles[0])): for j in range(len(circles[0])): if liste_ordre[i] == liste[j]: circles_ordre[0][i] = circles[0][j] return circles_ordre circles = circles_ordre(circles) circles1 = circles_ordre(circles1) print (circles) print (circles1) #recalage pts1 = np.float32([[circles[0][0][0],circles[0][0][1]],[circles[0][1][0],circles[0][1][1]], [circles[0][2][0],circles[0][2][1]],[circles[0][3][0],circles[0][3][1]]]) pts2 = np.float32([[circles1[0][0][0],circles1[0][0][1]],[circles1[0][1][0],circles1[0][1][1]], [circles1[0][2][0],circles1[0][2][1]],[circles1[0][3][0],circles1[0][3][1]]]) M = cv2.getPerspectiveTransform(pts2,pts1) dst = cv2.warpPerspective(img1,M,(1240,1754)) squares1 = find_squares(dst) print (len(squares1)) #print squares1 squares_choix = squares[0:25] squares_numero = squares[25:] #print len(squares_choix) #print len(squares_numero) #print squares_choix #print squares_numero[0:7] #methode mise en ordre bubble def mise_ordre_squares(squares): squares_ordre =[] for num in range(10): squares_temp = squares[num*7:num*7+7] for passnum in range(len(squares_temp) - 1, 0, -1): # print alist,passnum for i in range(passnum): if squares_temp[i][0][0] > squares_temp[i + 1][0][0]: temp = squares_temp[i] squares_temp[i] = squares_temp[i + 1] squares_temp[i + 1] = temp squares_ordre += squares_temp return squares_ordre squares_numero = mise_ordre_squares(squares_numero) # afficher les carres detecte ''' cv2.drawContours( dst, squares, -1, (0, 255, 0), 3 ) cv2.imwrite( "resultat3.jpg", dst ); cv2.imshow('squares', dst) k = cv2.waitKey(0) if k == 27: cv2.destroyAllWindows() ''' print('###') #print squares_choix[0][0] #print img.shape #print img[squares_choix[0][0][1],squares_choix[0][0][0]] print('resultat') img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) dst = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY) def correlation_coefficient(patch1, patch2): product = np.mean((patch1 - patch1.mean()) * (patch2 - patch2.mean())) stds = patch1.std() * patch2.std() if stds == 0: return 0 else: product /= stds return product ''' #test de les moyennes et correlation for i in range(25): compte = 0 print('case %d'%(i)) print('difference entre la moyenne') print np.mean(img[squares_choix[i][0][1]:squares_choix[i][1][1],squares_choix[i][0][0]:squares_choix[i][2][0]]) - np.mean(dst[squares_choix[i][0][1]:squares_choix[i][1][1],squares_choix[i][0][0]:squares_choix[i][2][0]]) print('correlation_coefficent') cor = correlation_coefficient(img[squares_choix[i][0][1]:squares_choix[i][1][1],squares_choix[i][0][0]:squares_choix[i][2][0]],dst[squares_choix[i][0][1]:squares_choix[i][1][1],squares_choix[i][0][0]:squares_choix[i][2][0]]) print cor #print np.corrcoef(img[squares_choix[i][0][1]:squares_choix[i][1][1],squares_choix[i][0][0]:squares_choix[i][2][0]],dst[squares_choix[i][0][1]:squares_choix[i][1][1],squares_choix[i][0][0]:squares_choix[i][2][0]])[0,1] (m,n) = img[squares_choix[i][0][1]:squares_choix[i][1][1],squares_choix[i][0][0]:squares_choix[i][2][0]].shape for a in range(m): for b in range(n): if(img[a][b] == dst[a][b]): compte += 1 print compte ''' #print('###') #print squares[1] #print squares1[0] difference_moyenne = [] for i in range(25): difference_moyenne.append(np.mean(img[squares_choix[i][0][1]:squares_choix[i][1][1],squares_choix[i][0][0]:squares_choix[i][2][0]]) - np.mean(dst[squares_choix[i][0][1]:squares_choix[i][1][1],squares_choix[i][0][0]:squares_choix[i][2][0]])) print (difference_moyenne) def decoder(difference_moyenne,seuil): for i in range(len(difference_moyenne)): if difference_moyenne[i] > seuil: difference_moyenne[i] = 1 else: difference_moyenne[i] = 0 return difference_moyenne reponse_correcte = [1,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,0,1,0,0] reponse = decoder(difference_moyenne,20) def resultat(reponse,reponse_correcte): compte = 0 for i in range(len(reponse)): if(reponse[i] == reponse_correcte[i] == 1): compte +=1 return compte print ("note final %d/8"%(resultat(reponse,reponse_correcte)))
import pandas as pd import numpy as np import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import math def get_reports_data(creditrecordcsv): ''' The function takes in the credit_record.csv and creates a data frame for: * expanded - for each account id find out the number of times each status occured throughout the history of the account * score - creates a scoring system and returns the Expanded DF with the aggergated score, a score for months, and the number of times each status occured by serverity and . The higher the score the more risk * full_history - for each account gives the full account's history starting at the most recent month of account going backwards i.e. if an account has been active for 3 months the status of the account will the most recent month's status while 2 months ago will be the first month of the account's existence ''' report = pd.read_csv(creditrecordcsv) # number of months of active credit account for each ID months = report.groupby('ID').count().reset_index() # pull only the columns we care about months = months[['ID', 'MONTHS_BALANCE']] # rename the columns months.columns = ['ID', 'MONTHS_ACTIVE'] # Number of times each ID had each status expanded = report.groupby(['ID', 'STATUS']).size().unstack().reset_index() # Merge the expanded data frame with the months data frame expanded = expanded.merge(months, how='left', on='ID') # fill all null values with 0 expanded.fillna(0, inplace=True) # rename the columns in a way that makes sense expanded.columns = ['id', '0-29', '30-59', '60-89', '90-119', '120-149', 'bad_debt', 'paid_off', 'no_debt', 'months_active'] # copy the expanded dataframe to maintain data intregity (for exploring and future data prepping as needed) score = expanded.copy() # multiply each lateness by n where n is the cronological order of the lateness i.e. being 30-59days is 2 and '120-149' is 5 # for paid off multiple by -2 score['30-59'] = score['30-59'] * 2 score['60-89'] = score['60-89'] * 3 score['90-119'] = score['90-119'] * 4 score['120-149'] = score['120-149'] * 5 score['bad_debt'] = score['bad_debt'] * 6 score['paid_off'] = score['paid_off'] * -2 # convert the id to string score['id'] = score['id'].astype(str) # Creates a score for months active score['time_score'] = np.where(score['months_active'] < 18, 0, np.where(score['months_active'] < 47, -10, -20)) # sum the values on the row level score['score'] = score.sum(axis=1) # create a range for the maxium number of months (60) in the data frame # use a for loop to put get the entire account's history to the current month by shifting status by n for n in range(1, 61): report.columns = report.columns.str.lower() report[f'{str(n)}month_ago'] = report.groupby('id')['status'].shift(n) # convert the months_balance column to positive number report['months_balance'] = report['months_balance']*-1 # get the max row for each id full_history = report.groupby('id')[['months_balance']].max().reset_index() # merge the full_history df with the report df (that has current history) so that each id only has 1 row full_history = full_history.merge(report, how='left', on=['months_balance', 'id']) # rename months_balance column to account_months for age full_history.rename(columns={"months_balance": "account_months"}, inplace=True) # return expanded, score, and full history data frames return expanded, score, full_history def pensioner_years_worked(row): ''' This function takes in a row of a dataframe and checks if the row belongs to a pensioner that is permanently retired (days_employed = -365243) If the pensioner is male, then the number of years worked is equal to a career from age 17 to their age or age 60, whichever is smaller If the pensioner is female and is blue collar, then the number of years worked is equal to a career from age 17 to their age or age 50, whichever is smaller If the pensioner is female and is not blue collar, then the number of years worked is equal to a career from age 17 to their age or age 55, whichever is smaller The starting age of 17 is based on the minimum legal working age of 16, but considers the common practice of waiting until graduation from secondary school before working in cities ''' # Sets the years worked to be equal to the starting value recorded in the employed_years column. If the row is not a retired pensioner, this value will be returned and nothing will be changed years_worked = row['employed_years'] # Checks if the record is from a permanently retired pensioner if row['days_employed'] == -365243: # If the pensioner is male: if row['code_gender'] == 'M': # Find the number of years worked assuming they retired at 60, or if they aren't 60 yet, assume they just retired and have worked since they were 17 if row['age'] > 60: years_worked = row['age'] - 17 - (row['age'] - 60) else: years_worked = row['age'] - 17 # If the pensioner is female: elif row['code_gender'] == 'F': # Identify if the pensioner is blue collar and eligible for earlier retirement blue_collar = ['Laborers', 'Drivers', 'Cooking staff', 'Security staff', 'Cleaning staff', 'Low-skill Laborers', 'Waiters/barmen staff'] # If the pensioner is blue collar, find the number of years worked assuming they retired at 50, or if they aren't 50 yet, assume they just retired and have worked since they were 17 if row['occupation_type'] in blue_collar: if row['age'] > 50: years_worked = row['age'] - 17 - (row['age'] - 50) else: years_worked = row['age'] - 17 # If the pensioner is not blue collar, find the number of years worked assuming they retired at 55, or if they aren't 55 yet, assume they just retired and have worked since they were 17 else: if row['age'] > 55: years_worked = row['age'] - 17 - (row['age'] - 55) else: years_worked = row['age'] - 17 return years_worked def pensioner_days_employed(row): days_employed = row['days_employed'] if row['days_employed'] == -365243: days_employed = math.floor(row['employed_years'] * 365.25) return days_employed def get_application_data(applicationrecordcsv): ''' The function takes in the application_record.csv and returns a dataframe after basic cleaning ''' apps = pd.read_csv('application_record.csv') # Converts all column headers to lowercase apps.columns = (apps.columns).str.lower() # Fills null values in occuptation type with 'Other' apps['occupation_type'].fillna('Other', inplace=True) # Convert days employed to years employed apps['employed_years'] = [round(val/(-365)) if val < -365 else val/(-365) if val < 0 else round(val/365) for val in list(apps.days_employed)] # Convert days_birth to age in years apps['age'] = (apps['days_birth']/365 * -1).apply(np.floor) # Convert "Yes" and "No" throughout dataframe to 1s and 0s respectively apps.replace({'Y': 1, 'N': 0}, inplace=True) # Reverses sign on days birth apps['days_birth'] = apps['days_birth'] * -1 # Reverses sign on days employed apps['days_employed'] = apps['days_employed'] * -1 # Changes the employed_years value of retired pensioners from 1001 to an estimate based on their current age, gender, and occupation apps['employed_years'] = apps.apply(lambda row: pensioner_years_worked(row), axis = 1) # If days employed is a stand in value (-365243), convert that to a number of days equal to the estimated number of years worked apps['days_employed'] = apps.apply(lambda row: pensioner_days_employed(row), axis = 1) # Converts id to object type apps['id'] = apps['id'].astype(str) return apps def add_score_target(apps, score): ''' This takes in the apps and score dataframes and returns apps_cred, which contains all applications with credit records with their score attached and apps_none, which are all applications that have no credit record ''' # Reduces the score dataframe to only the id and score columns score = score[['id', 'score']] # Merges on the left, leaving many records with NaN for score apps = apps.merge(score, how='left', on = 'id') # Creates a dataframe where the score is not null (these applications have a credit record) apps_cred = apps[apps.score.notnull()] apps_cred.reset_index(drop=True, inplace=True) # Creates a dataframe where the score is null (these applications do not have a credit record) apps_none = apps[apps.score.isna()] apps_none = apps_none.drop(columns='score') apps_none.reset_index(drop=True, inplace=True) return apps_cred, apps_none def add_apps_dummies(apps): ''' This returns the apps dataframe with dummy variables ''' # Create list of categorical variables to make dummies of dummies_list = ['name_income_type', 'name_education_type', 'name_family_status', 'name_housing_type', 'occupation_type'] # Create dummies dataframe dummies = pd.get_dummies(apps[dummies_list]) # Convert dummy column headers to snake case style dummies.columns = dummies.columns.str.lower() dummies.columns = dummies.columns.str.replace(" ", "_") # Concate with original dataframe apps_dummies = pd.concat([apps, dummies], axis=1) return apps_dummies def encode_dummies(apps): ''' This returns the apps dataframe with dummy variables ''' # Create list of categorical variables to make dummies of dummies_list = ['name_income_type', 'name_education_type', 'name_housing_type', 'occupation_type'] # Create dummies dataframe dummies = pd.get_dummies(apps[dummies_list]) # Convert dummy column headers to snake case style dummies.columns = dummies.columns.str.lower() dummies.columns = dummies.columns.str.replace(" ", "_") # Concate with original dataframe apps_encoded = pd.concat([apps, dummies], axis=1) # Drop original columns ##apps_encoded.drop(columns=dummies_list, inplace=True) # Drop gender, age, and family status #dropped = ['code_gender', 'name_family_status', 'age'] #apps_encoded.drop(columns=dropped, inplace=True) return apps_encoded def split_data(df, pct=0.10): ''' Divides the dataframe into train, validate, and test sets. Parameters - (df, pct=0.10) df = dataframe you wish to split pct = size of the test set, 1/2 of size of the validate set Returns three dataframes (train, validate, test) ''' train_validate, test = train_test_split(df, test_size=pct, random_state = 123) train, validate = train_test_split(train_validate, test_size=pct*2, random_state = 123) return train, validate, test def split_stratify_data(df, stratify_tgt, pct=0.10): ''' Divides the dataframe into train, validate, and test sets, stratifying on stratify. Parameters - (df, pct=0.10) df = dataframe you wish to split pct = size of the test set, 1/2 of size of the validate set Returns three dataframes (train, validate, test) ''' train_validate, test = train_test_split(df, stratify=df[stratify_tgt], test_size=pct, random_state = 123) train, validate = train_test_split(train_validate, stratify=train_validate[stratify_tgt], test_size=pct*2, random_state = 123) return train, validate, test def standard_scaler(train, validate, test): ''' Accepts three dataframes and applies a standard scaler to convert values in each dataframe based on the mean and standard deviation of each dataframe respectfully. Columns containing object data types are dropped, as strings cannot be directly scaled. Parameters (train, validate, test) = three dataframes being scaled Returns (scaler, train_scaled, validate_scaled, test_scaled) ''' # Remove columns with object data types from each dataframe train = train.select_dtypes(exclude=['object']) validate = validate.select_dtypes(exclude=['object']) test = test.select_dtypes(exclude=['object']) # Fit the scaler to the train dataframe scaler = StandardScaler(copy=True, with_mean=True, with_std=True).fit(train) # Transform the scaler onto the train, validate, and test dataframes train_scaled = pd.DataFrame(scaler.transform(train), columns=train.columns.values).set_index([train.index.values]) validate_scaled = pd.DataFrame(scaler.transform(validate), columns=validate.columns.values).set_index([validate.index.values]) test_scaled = pd.DataFrame(scaler.transform(test), columns=test.columns.values).set_index([test.index.values]) return scaler, train_scaled, validate_scaled, test_scaled def scale_inverse(scaler, train_scaled, validate_scaled, test_scaled): ''' Takes in three dataframes and reverts them back to their unscaled values Parameters (scaler, train_scaled, validate_scaled, test_scaled) scaler = the scaler you with to use to transform scaled values to unscaled values with. Presumably the scaler used to transform the values originally. train_scaled, validate_scaled, test_scaled = the dataframes you wish to revert to unscaled values Returns train_unscaled, validated_unscaled, test_unscaled ''' train_unscaled = pd.DataFrame(scaler.inverse_transform(train_scaled), columns=train_scaled.columns.values).set_index([train_scaled.index.values]) validate_unscaled = pd.DataFrame(scaler.inverse_transform(validate_scaled), columns=validate_scaled.columns.values).set_index([validate_scaled.index.values]) test_unscaled = pd.DataFrame(scaler.inverse_transform(test_scaled), columns=test_scaled.columns.values).set_index([test_scaled.index.values]) return train_unscaled, validate_unscaled, test_unscaled def create_scaled_x_y(train, validate, test, target): ''' Accepts three dataframes (train, validate, test) and a target variable. Separates the target variable from the dataframes, scales train, validate, and test and returns all 6 resulting dataframes. ''' y_train = train[target] X_train = train.drop(columns=[target]) y_validate = validate[target] X_validate = validate.drop(columns=[target]) y_test = test[target] X_test = test.drop(columns=[target]) scaler, X_train_scaled, X_validate_scaled, X_test_scaled = standard_scaler(X_train, X_validate, X_test) return X_train_scaled, y_train, X_validate_scaled, y_validate, X_test_scaled, y_test def wrangle_credit(): ''' This function utlizes the above defined functions to create the train, validate, and test data sets for analysis. Note - The create_scaled_x_y function will be used after EDA to avoid confusion ''' # get the credit report data into a data frame expanded, score, full_history = get_reports_data('credit_record.csv') # get the apps data into a data frame apps = get_application_data('application_record.csv') # create the dummy varaibles for the apps data apps = encode_dummies(apps) # add the score to the apps data apps_cred, apps_none = add_score_target(apps, score) # split the apps_cred data (apps + credit report) into train, validate, and test sets and return the results train, validate, test = split_data(apps_cred) return train, validate, test
from login_register import * os.system("clear") system_print("Welcome to the online Library!") while True: print_menu("MAIN MENU:\n1.Login\n2.Register\n3.Quit") while True: choice = int(input("Please give your option: ")) if choice != 1 and choice != 2 and choice != 3: print("\tWrong input!Please choose 1,2 or 3.") else: break # Login if choice == 1: login() # Register elif choice == 2: register() # Quit else: break os.system("clear") print_menu("Bye.")
#by Lucas and Siddhant #loading library from datetime import datetime # Set a variable birthday = "1-May-12". birthday="1-May-12" date_format = "%d-%B-%y" # Parse the date using datetime.datetime.strptime. parsed_date = datetime.strptime(birthday,date_format) # Use strftime to output a date that looks like "5/1/2012". date_str = parsed_date.strftime("%-m/%-d/%Y") print(date_str) #Making a function to do the same def convert_date_format(raw_date,date_format): parsed_date = datetime.strptime(raw_date,date_format) date_str = parsed_date.strftime("%-m/%-d/%Y") return date_str print(convert_date_format(birthday,date_format))
from constant.constant import Constant class Character: """ class used for MacGyver's moves and items pick up logic """ def __init__(self, icon, level): self.icon = icon self.level = level self.item_count = 0 self.item = ['N', 'E', 'S', 'T'] def move(self, x, y, direction): """ method to make the hero move """ if direction == 'right': if self.is_moving_to(x, y, x, y + 1): return True elif direction == 'left': if self.is_moving_to(x, y, x, y - 1): return True elif direction == 'up': if self.is_moving_to(x, y, x - 1, y): return True elif direction == 'down': if self.is_moving_to(x, y, x + 1, y): return True def has_all_items(self): """ check in the player has all the required items """ return self.item_count == 4 def get_item_count(self): """ get item count """ return self.item_count def is_moving_to(self, x_before, y_before, x_new, y_new): """ method used to move the hero is a direction """ if self.level.is_not_wall(x_new, y_new): if self.level.maze_structure()[x_new][y_new] in self.item: self.item_count += 1 self.level.maze_structure()[x_before][y_before] = '0' self.level.maze_structure()[x_new][y_new] = ( Constant.constant['player']) return True else: return False
class Solution: def isPalindrome(self, x: int) -> bool: #apparently, negatives can't be palindromes :/ if x<0: return False #remember the slice syntax: LIST[start:end:position... -1 reverse, 1 forward, 2, skip 1 each round] return int(str(x)[::-1]) == x
# thanks to Nicholas Swift and his blog post explaining the a* code class Cl_Node(): def __init__(self, parent = None, position = None): self.parent = parent self.position = position self.g = 0 self.h = 0 self.f = 0 def __eq__(self, other): return self.position == other.position def astar(grid, start, end): #function that returns a list of tuples defining the path from start to end #create start and end nodes start_node = Cl_Node(None, start) start_node.g = start_node.h = start_node.f = 0 end_node = Cl_Node(None, end) end_node.g = end_node.h = end_node.f = 0 #initialize lists open_list = [] closed_list = [] #add start node to open list open_list.append(start_node) while len(open_list) > 0: current_node = open_list[0] current_index = 0 for index, item in enumerate(open_list): if item.f < current_node.f: current_node = item current_index = index open_list.pop(current_index) closed_list.append(current_node) if current_node == end_node: path = [] current = current_node while current is not None: path.append(current.position) current = current.parent return path [::-1] children = [] #cut the following from the new position array to remove diagonals... # , (-1, -1), (-1, 1), (1, -1), (1, 1) for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0)]: #adjacent squares #get node position node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1]) #check range if node_position[0] > (len(grid) - 1) or node_position[0] < 0 or node_position[1] > (len(grid[len(grid) -1]) -1) or node_position[1] < 0: continue #make sure terrain is passable if grid[node_position[0]][node_position[1]] != 0 and grid[node_position[0]][node_position[1]] != 'T': continue #create new node new_node = Cl_Node(current_node, node_position) #append children.append(new_node) for child in children: #child is on closed list for closed_child in closed_list: if child == closed_child: continue #create values for f,g,h child.g = current_node.g + 1 child.h = ((child.position[0] - end_node.position[0]) ** 2) + ((child.position[1] - end_node.position[1]) ** 2) child.f = child.g + child.h #child is already in open list for open_node in open_list: if child == open_node and child.g > open_node.g: continue #add child to list open_list.append(child)
# Faça uma função que recebe três números por # parâmetro e imprime na tela em ordem crescente. def ImprimeOrdenado(a, b, c): if (a < b) and (a < c): if (b < c): print(a, b, c) else: print(a, c, b) elif (b < a) and (b < c): if (a < c): print(b, a, c) else: print(b, c, a) else: if (a < b): print(c, a, b) else: print(c, b, a) ImprimeOrdenado(1, 2, 3) ImprimeOrdenado(2, 3, 1) ImprimeOrdenado(3, 1, 2)
def FazerBolo(): print("Separar os ingredientes") print("Misturar os ingredientes em um recipiente") print("Deixar no forno por 30 minutos") print("Retirar do forno") print("") def AtravesarRua(): print("Parar na borda da calçada") print("Olhar para direita") print("Olhar para esquerda") print("Senão tiver trânsito, atravesar") print("") def Saudacao(): nome = input("Diga seu nome: ") print("Olá," + nome) print("") FazerBolo() AtravesarRua() AtravesarRua() Saudacao()
# 2. Во втором массиве сохранить индексы чётных элементов первого массива. # Например, если дан массив со значениями 8, 3, 15, 6, 4, 2, второй массив надо # заполнить значениями 0, 3, 4, 5, (индексация начинается с нуля), # т.к. именно в этих позициях первого массива стоят чётные числа. import random SIZE = 10_000 MIN_ITEM = 0 MAX_ITEM = 1_000_000 array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] print(array) arr_index = [] for i in range(SIZE): if array[i] % 2 == 0: arr_index.append(i) print(arr_index)
values = { a:b} a= int(input("enter num:")) b= input("enter name:") x=int(input("enter choice: 1.get name,2.get number,3.display dictionary,4.insert:::")) if x == 1: print values[input("enter num:")] elif x==3: print values
######################################################################## # Define a Convolution Neural Network # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # 2. Change the code to have only a single fully connected layer. # The model will have a single layer that connects the input to the output. import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(3 * 32 * 32, 10) #fully connected def forward(self, x): x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) #x = self.fc1(x) return x
from algorithms.base_algorithm import BaseAlgorithm class FordBellman(BaseAlgorithm): def __init__(self, name): super().__init__(name) def find_path(self, graph, start, end): return self.ford_bellman(graph, start, end) @staticmethod def ford_bellman(graph, start, end): count = len(graph.nodes) all_connections = graph.get_all_connections() dist = [float("Inf")] * count dist[start.index] = 0 paths = [] for i in range(count): paths.append([graph.nodes[end.index].data]) for i in range(count - 1): for u, v, w in all_connections: if dist[u] != float("Inf") and dist[u] + w < dist[v]: dist[v] = dist[u] + w paths[v].append(graph.nodes[u].data) paths[end.index].append(graph.nodes[start.index].data) for u, v, w in all_connections: if dist[u] != float("Inf") and dist[u] + w < dist[v]: print("Graph contains negative weight cycle") return paths[end.index].reverse() return dist[end.index], paths[end.index]
from abc import ABCMeta, abstractmethod, abstractproperty class BaseModel(object): __metaclass__ = ABCMeta @abstractproperty def model(self): """ Return Model :return: obj model """ @abstractmethod def reset(self): """ Reset model with base structure :return: None """ @abstractmethod def load(self, values): """ Load model with passed values :param values: dict k/v to load into model :return: obj model """
""" Task. Given two integers a and b, find their greatest common divisor. Input Format. The two integers a, b are given in the same line separated by space. Constraints. 1<=a,b<=2·109. Output Format. Output GCD(a, b). """ def EuclidGCD(a, b): if b == 0: return a else: a = a%b return EuclidGCD(b, a) in_ = [int(n) for n in input().split()] print(EuclidGCD(in_[0], in_[1]))
#!/usr/bin/env python3 import sys import os from threading import Thread from queue import Queue, LifoQueue from functools import cache from operator import itemgetter from collections import Counter from rectangle import Rectangle # Keep a count of each area a rectangle might have rect_areas = Counter() rect_queue = LifoQueue() area_queue = Queue() @cache def create_rectangle(bottom, left, top, right): "Creating a rectangle is expensive, reuse an existing one if available" return Rectangle(bottom, left, top, right) def read_rectangles(): for line in sys.stdin: cmd, data = line.split(maxsplit=1) if cmd == "CREATE": bottom, left, top, right = [float(n) for n in data.split()] rect = create_rectangle(bottom, left, top, right) rect_queue.put(rect) elif cmd == "MOVE": # Add moved version of the previously read rectangle vertical, horizontal = [float(n) for n in data.split()] rect = rect_queue.get() new_rect = rect.move(vertical, horizontal) rect_queue.put(rect) rect_queue.put(new_rect) elif cmd == "RESIZE": # Add resized version of the previously read rectangle vertical, horizontal = [float(n) for n in data.split()] rect = rect_queue.get() new_rect = rect.resize(vertical, horizontal) rect_queue.put(rect) rect_queue.put(new_rect) def rect_to_area(): while not rect_queue.empty(): rect = rect_queue.get() area = rect.area() area_queue.put(area) rect_queue.task_done() def area_to_counter(): while not area_queue.empty(): rect_areas[area_queue.get(timeout=1)] += 1 if __name__ == '__main__': read_rectangles() for _ in range(os.cpu_count()): Thread(target=rect_to_area, daemon=True).start() rect_queue.join() area_to_counter() print("Number of rectangles computed:", sum(rect_areas.values())) print("Most common rectangle areas:") most_common = sorted(rect_areas.most_common(), key=itemgetter(1), reverse=True) for area, count in most_common: print(" Area %s\t%d rectangles" % (area, count))
# 5. Реализовать класс Stationery (канцелярская принадлежность). # Определить в нем атрибут title (название) и метод draw (отрисовка). # Метод выводит сообщение “Запуск отрисовки.” Создать три дочерних # класса Pen (ручка), Pencil (карандаш), Handle (маркер). # В каждом из классов реализовать переопределение метода draw. # Для каждого из классов методы должен выводить уникальное сообщение. # Создать экземпляры классов и проверить, что выведет описанный # метод для каждого экземпляра. class Stationery: title = '' def draw(self): print('Запуск отрисовки.') class Pen(Stationery): def __init__(self, title): self.title = title def draw(self): print(f'Пишу текст с помощью ручки "{self.title}".') class Pencil(Stationery): def __init__(self, title): self.title = title def draw(self): print(f'Рисую чертеж с помощью карандаша "{self.title}".') class Handle(Stationery): def __init__(self, title): self.title = title def draw(self): print(f'Делаю заметки с помощью маркера "{self.title}".') my_item1 = Pen('Лучшая ручка') my_item2 = Pencil('Великолепный карандаш') my_item3 = Handle('Самый лучший маркер') print(my_item1.title) print(my_item2.title) print(my_item3.title) my_item1.draw() my_item2.draw() my_item3.draw()
# 3. Реализовать программу работы с органическими клетками. # Необходимо создать класс Клетка. В его конструкторе инициализировать # параметр, соответствующий количеству клеток (целое число). В классе # должны быть реализованы методы перегрузки арифметических операторов: # сложение (__add__()), вычитание (__sub__()), умножение (__mul__()), # деление (__truediv__()).Данные методы должны применяться только к # клеткам и выполнять увеличение, уменьшение, умножение и обычное # (не целочисленное) деление клеток, соответственно. В методе деления # должно осуществляться округление значения до целого числа. # Сложение. Объединение двух клеток. При этом число ячеек общей клетки # должно равняться сумме ячеек исходных двух клеток. # Вычитание. Участвуют две клетки. Операцию необходимо выполнять только # если разность количества ячеек двух клеток больше нуля, иначе выводить # соответствующее сообщение. # Умножение. Создается общая клетка из двух. Число ячеек общей клетки # определяется как произведение количества ячеек этих двух клеток. # Деление. Создается общая клетка из двух. Число ячеек общей клетки # определяется как целочисленное деление количества ячеек этих двух клеток. # В классе необходимо реализовать метод make_order(), принимающий # экземпляр класса и количество ячеек в ряду. Данный метод позволяет # организовать ячейки по рядам. # Метод должен возвращать строку вида *****\n*****\n*****..., где # количество ячеек между \n равно переданному аргументу. Если ячеек # на формирование ряда не хватает, то в последний ряд записываются # все оставшиеся. # Например, количество ячеек клетки равняется 12, количество ячеек в # ряду — 5. Тогда метод make_order() вернет строку: *****\n*****\n**. # Или, количество ячеек клетки равняется 15, количество ячеек в ряду — 5. # Тогда метод make_order() вернет строку: *****\n*****\n*****. # Подсказка: подробный список операторов для перегрузки доступен по ссылке. class Kletka: def __init__(self, count = 0): self.count = count def __add__(self, other): return Kletka(self.count + other.count) def __sub__(self, other): if (self.count - other.count) > 0: return Kletka(self.count - other.count) raise Exception("Разность количества ячеек двух клеток должна быть больше нуля!") def __mul__(self, other): return Kletka(self.count * other.count) def __truediv__(self, other): return Kletka(round(self.count / other.count)) @staticmethod def make_order(kletka, number): result = '' for a in range(1, kletka.count + 1): result += '*' if ((a % number) == 0): result += '\n' return result print(Kletka.make_order(Kletka(15), 5))
# 7. Продолжить работу над заданием. В программу должна попадать # строка из слов, разделённых пробелом. Каждое слово состоит # из латинских букв в нижнем регистре. Нужно сделать вывод # исходной строки, но каждое слово должно начинаться с заглавной # буквы. Используйте написанную ранее функцию int_func(). def is_ascii(s): return all(65 <= ord(c) <= 122 for c in s) def is_lower(s): return s.islower() # реализация функции def int_func(s): return s.title() user_value = '' while True: user_value = input('Введите строку из слов, разделённых пробелами: ') values = user_value.split() if len(values) > 1: for v in values: if not is_ascii(v): print(f'Ошибка! Слово "{v}" не состоит из латинских букв!') break elif not is_lower(v): print(f'Ошибка! Слово "{v}" не состоит из букв в нижнем регистре!') break else: break else: print('Ошибка! Строка должна содержать не менее 2-х слов!') # вывод результата print(f"Результат вызова функции int_func('{user_value}'): {int_func(user_value)}")
# 1. Реализовать класс «Дата», функция-конструктор которого должна принимать # дату в виде строки формата «день-месяц-год». В рамках класса реализовать # два метода. Первый, с декоратором @classmethod, должен извлекать число, # месяц, год и преобразовывать их тип к типу «Число». Второй, с декоратором # @staticmethod, должен проводить валидацию числа, месяца и года (например, # месяц — от 1 до 12). Проверить работу полученной структуры на реальных данных. class Date: def __init__(self, date_as_string): self.date_as_string = date_as_string @classmethod def extract_numbers(cls, date): return [int(number) for number in date.date_as_string.split('-')] @staticmethod def Validate(day, month, year): if day not in [1,31]: raise ValueError(f'Ошибка! Некорректное значения дня "{day}".') elif month not in [1,12]: raise ValueError(f'Ошибка! Некорректное значения месяца "{month}".') elif year < 0: raise ValueError(f'Ошибка! Некорректное значения года "{year}".') my_date = Date('31-12-2012') my_date_values = Date.extract_numbers(my_date) print(my_date_values) print(Date.Validate(my_date_values[0], my_date_values[1], my_date_values[2]))
# 6. Реализовать два небольших скрипта: # а) итератор, генерирующий целые числа, начиная с указанного, # б) итератор, повторяющий элементы некоторого списка, определенного заранее. # Подсказка: использовать функцию count() и cycle() модуля itertools. # Обратите внимание, что создаваемый цикл не должен быть бесконечным. # Необходимо предусмотреть условие его завершения. # Например, в первом задании выводим целые числа, начиная с 3, а при достижении # числа 10 завершаем цикл. Во втором также необходимо предусмотреть условие, # при котором повторение элементов списка будет прекращено. from random import randint from my_count_functions import my_count_func from my_cycle_functions import my_cycle_func # случайное значения n = randint(1, 9) # итератор, генерирующий целые числа, начиная с указанного print(f'Вывод результата a): {my_count_func(n)}') # итератор, повторяющий элементы некоторого списка, определенного заранее print(f'Вывод результата б): {my_cycle_func([randint(10, 100) for a in range(n)])}')
# Python wih X starting point Y end Point and D as fix Jump distance. def solution(X, Y, D): # Use Case 1: Jump Distance 0 # Through exeption if Y < X or D <= 0: raise Exception("Invalid arguments") # Use case 2: Y in multiplication of D # Use case 3: Y in Not in multiplecaiton of D if (Y- X) % D == 0: return (Y- X) // D else: return ((Y- X) // D) + 1 # Code COntributed by Nilesh # To Test Try X=10, Y=85 D=30
# -*- coding: utf-8 -*- """ Created on Thu Aug 20 09:59:26 2015 @author: akond """ from swampy.TurtleWorld import * def drawTriangle(turtleParam, length, angle): ''' This module draws a triangle ''' import math legLen = length * math.sin(angle * math.pi / 180) #for i in range(3): rt(turtleParam, angle) fd(turtleParam, length) lt(turtleParam, 90 + angle) fd(turtleParam, 2 * legLen) lt(turtleParam, 90 + angle) fd(turtleParam, length) lt(turtleParam, 180 - angle) ## def drawPie(tParam, segmentCount, lengthParam): angle = 360.0 / segmentCount # Made it floating point computation for issue #5 for count in range(segmentCount): drawTriangle(tParam, lengthParam, angle/2) lt(tParam, angle) lengthVal = 100 segments=10 #Picture # 1 world = TurtleWorld() turtleObj = Turtle() drawPie(turtleObj, segments, lengthVal) #Picture # 2 world = TurtleWorld() turtleObj = Turtle() segments=6 drawPie(turtleObj, segments, lengthVal) #Picture # 3 world = TurtleWorld() turtleObj = Turtle() segments=5 drawPie(turtleObj, segments, lengthVal) #Picture # 4 world = TurtleWorld() turtleObj = Turtle() segments=4 drawPie(turtleObj, segments, lengthVal) #Picture # 5 world = TurtleWorld() turtleObj = Turtle() segments=10 drawPie(turtleObj, segments, lengthVal) #Picture # 6 world = TurtleWorld() turtleObj = Turtle() segments=8 drawPie(turtleObj, segments, lengthVal) #Added by Manish world = TurtleWorld() turtleObj = Turtle() segments=7 drawPie(turtleObj, segments, lengthVal) #drawTriangle(turtleObj, lengthVal, angleVal) wait_for_user()
#Autores: Esteban Andres Flores Gutierrez y Camila Fernanda Guzman Lara import base def ConvertirAbase(bf): fin= 'Fin de la funcion '+str('ConvertirAbase') basef=bf bi= input('Base inicial: ') if basef==bi or bi < 2 or bi > 10: print 'Ingrese base correcta.' else: numero= input('Ingrese numero: ') if base.esNumero(numero, bi)== False: print 'Ingrese numero y base correcta.' else: ni=base.decimal(numero,bi) nf=base.cambio(ni,basef) print nf q=raw_input('Otra conversion? (si/no): ') if q.lower()== 'si': return ConvertirAbase(basef) elif q.lower()== 'no': print '\n' print fin return 0 else: print 'Si desea otra conversion, responda con si/no. De lo contrario, se finalizara la funcion.' def Mayor(mayor=0, var=0, var2=0): gigante= mayor basemayor= var numayor=var2 dig= input('Ingrese numero: ') if dig == int(0): print 'Decimal: ' + str(gigante) + ' ; ' + 'Base: ' +str(var)+' ; ' 'Numero: ' +str(var2) print '\n' print 'Fin de la funcion'+str('Mayor') return 0 else: numero= dig/10 bas= dig%10 if bas < 2: print "Ingrese base correcta" elif base.esNumero(numero,bas) == False: print "Numero incorrecto" else: final= base.decimal(numero,bas) print "Decimal: "+str(final) if final > gigante: gigante = final basemayor= bas numayor = numero else: basemayor= var numayor=var2 return Mayor(gigante, basemayor, numayor) print "****************************************************" print "***** Ejemplo de la funcion ConvertirAbase(2) ******" print "****************************************************" ConvertirAbase(2) print "************************************************" print '\n' print "************************************************" print '\n' print "****************************************************" print "***** Ejemplo de la funcion ConvertirAbase(6) ******" print "****************************************************" ConvertirAbase(6) print "************************************************" print '\n' print "************************************************" print '\n' print "*************************************************" print "********** Ejemplo de la funcion Mayor **********" print "*************************************************" Mayor() print "************************************************" print '\n' print "************************************************" print '\n' print 'F i n \t d e l \t p r o g r a m a'
# %% import matplotlib.pyplot as plt import numpy as np print("Hello python") x = np.linspace(0, 2*np.pi, 10000) y = np.sin(x) print(np.pi) plt.plot(x, y) plt.show()
############################################################################## # # # A game by Louis Sugy for Ludum Dare #39 # # Theme: Running out of power # # # # CC BY-NC-SA # # # ############################################################################## import pygame from screen import Screen from menu import MainMenu from level import Level class Game: def __init__(self): pygame.init() self.screen = Screen("Broken Shuttle by Louis Sugy", 800, 600, 60) self.clock = pygame.time.Clock() def start(self): main_menu = MainMenu(self.screen) main_menu.start() def end(self): pygame.quit() game = Game() try: game.start() finally: game.end()
UNDERCOVER_OPTIONS = ''' You decide to go undercover on Planet Earth as a human. Where do you decide to go first 1) Harvard University 2) Visit the circus 3) Go to the mall 4) Visit a peanut butter factory... logically ;) ''' VISIT_CIRUS = ''' You see a sentient peanut butter jar performing circus trucks. What do you do? 1) 2) 3) ''' HARVARD_OPTION = ''' You end up in a CS50 lecture and end up being in the algorithms demo. You understand that CS50 is better than any peanut butter. You film the lecture and send it to your overlords, who then use CS create a new power source ''' def undercover_narrative(): undercover_option = int(input(UNDERCOVER_OPTIONS)) if undercover_option == 1: print(HARVARD_OPTION)
''' message = input("Tell me something, and I will repeat it back to you: ") print(message) current_number = 1 while current_number <= 5: print(current_number) current_number += 1 ''' unconfimed_users = ["alice","brian","candance"] confimed_users = [] while unconfimed_users: current_user = unconfimed_users.pop() print("Verifying user: " + current_user.title()) confimed_users.append(current_user) print("\nThe following users have been confirmed: ") for confimed_user in confimed_users: print(confimed_user.title())
""" let n = 18 Ask user to guess a number. If he guess greater than 18 than tell to reduce his guess If he guess smaller than 18 than tell to grow up his guess If he entered 18 then he wins game Max no of guesses are 9 If he can't guess 18 either in 9 guesses then he lose the game Print no of guesses left at each term """ n = 18 guess_num = 1 while guess_num < 10: guess = int(input("Guess a number :- ")) if guess == 18: print("Wow!! You guess the number only in", guess_num, "guesses") break elif guess <= 10: print("Enter a big number") print("No of guesses left =", 9 - guess_num) guess_num = guess_num + 1 continue elif guess < 18: print("You are very close!!\nEnter a little big number") print("No of guesses left =", 9 - guess_num) guess_num = guess_num + 1 continue elif guess < 25: print("You are very close!!\nEnter a little short number") print("No of guesses left =", 9 - guess_num) guess_num = guess_num + 1 continue else: print("Enter a short number") print("No of guesses left =", 9 - guess_num) guess_num = guess_num + 1 if guess_num == 10: print("Alas!! You have spent all your turns!!\nGAME OVER")
""" Take two numbers a & b as input. Then swap their values & print. """ print("Enter number a = ", end="") a = input() print("Enter number b = ", end="") b = input() a, b = b, a print("After swapping") print("a = " + str(a)) print("b = " + str(b))
alfabe = "abcdefghijklmnopqrstuvwxyz" text = input("Metninizi girin:") result = "" for i in text: #Kullanıcı saçma karakterler girebilir. try: sayi = alfabe.index(i) result+=alfabe[(sayi+13)%len(alfabe)] except: result+=str(i) print(result)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ que = deque() if not p and not q: return True elif p and q and p.val == q.val: que.extend([p.left, q.left, p.right, q.right]) while len(que) >= 2: if que[0] and que[1]: if que[0].val != que[1].val: return False else: que.extend([que[0].left, que[1].left, que[0].right, que[1].right]) elif (que[0] and not que[1]) or (que[1] and not que[0]): return False que.popleft() que.popleft() return True else: return False
#!/usr/bin/python class Node: def __init__(self, key=None, val=None, count=0): self.key = key self.val = val self.left = None self.right = None self.count = count class BST: def __init__(self): self.root = None def size(self): return self._size(self.root) def _size(self, x): if x is None: return 0 return x.count def rank(self, key): return self._rank(key, self.root) def _rank(self, key, x): if x is None: return 0 if key < x.key: return self._rank(key, x.left) elif key > x.key: return 1 + self._size(x.left) + self._rank(key, x.right) else: return self._size(x.left) def put(self, key, val): self.root = self._put(self.root, key, val) def _put(self, x, key, val): if x is None: return Node(key, val, 1) if key < x.key: x.left = self._put(x.left, key, val) elif key > x.key: x.right = self._put(x.right, key, val) else: x.val = val x.count = 1 + self._size(x.left) + self._size(x.right) return x def get(self, key): x = self.root while x is not None: if key < x.key: x = x.left elif key > x.key: x = x.right else: return x.val return None def iterate(self): q = [] self._inorder(self.root, q) return q def _inorder(self, x, q): if x is None: return self._inorder(x.left, q) q.append(x.key) self._inorder(x.right, q) def floor(self, key): x = self._floor(self.root, key) if x is None: return None return x.key def _floor(self, x, key): if x is None: return None if x.key == key: return x if x.key > key: return self._floor(x.left, key) t = self._floor(x.right, key) if t is not None: return t else: return x def max_key(self): x = self.root if x is None: return None while x.right is not None: x = x.right return x.key def min_key(self): x = self.root if x is None: return None while x.left is not None: x = x.left return x.key
class Parent1(object): def __init__(self): super().__init__() print("is Parent1") print("goes Parent1") class Parent2(object): def __init__(self): super().__init__() print("is Parent2") print("goes Parent2") class Child1(Parent1): def __init__(self): print("is Child1") super().__init__() #Parent1.__init__(self) print("goes Child1") class Child2(Parent1): def __init__(self): print("is Child2") super().__init__() #Parent1.__init__(self) print("goes Child2") class Child3(Parent2): def __init__(self): print("is Child3") super().__init__() # Parent2.__init__(self) print("goes Child3") class Grandson(Child1,Child2,Child3): def __init__(self): print("is Grandson") Child1.__init__(self) Child2.__init__(self) Child3.__init__(self) print("goes Grandson") if __name__=="__main__": Grandson()
class Node(object): def __init__(self, value=None, next=None, previous=None): self.value, self.next, self.previous = value, next, previous class CircularDoubleLinkedNode(object): def __init__(self, maxsize=None): self.maxsize = maxsize self.root = Node() self.root.next = self.root self.root.previous = self.root self.length = 0 def __len__(self): return self.length def headnode(self): return self.root.next def tailnode(self): return self.root.previous def append(self, value): if self.maxsize is not None and self.value >= self.maxsize: raise Exception('Full') node = Node(value) tailnode = self.tailnode() tailnode.next = node node.next = self.root node.previous = tailnode self.length += 1 self.root.previous = node def appendleft(self, value): if self.maxsize is not None and self.value >= self.maxsize: raise Exception('Full') node = Node(value) headnode = self.headnode() self.root.next = node node.next = headnode headnode.previous = node node.previous = self.root self.length += 1 def pop(self): if self.root.next is self.root: return tailnode = self.tailnode() prevnode = tailnode.previous prevnode.next = self.root self.root.previous = prevnode value = tailnode.value del tailnode self.length -= 1 return value def popleft(self): if self.root.next is self.root: return headnode = self.headnode() self.root.next = headnode.next headnode.next.previous = self.root value = headnode.value del headnode self.length -= 1 return value def __iter__(self): for node in self._iter_node(): yield node.value def _iter_node(self): curnode = self.root.next while curnode is not self.root: yield curnode curnode = curnode.next def remove(self, node): if self.root.next is self.root: raise Exception('remove empty CircularDoubleLinkedNode') prevnode = node.previous nextnode = node.next prevnode.next = nextnode nextnode.previous = prevnode del node self.length -= 1 def reverse_node(self): curnode = self.root.previous while curnode is not self.root: yield curnode curnode = curnode.previous class Queue(object): def __init__(self): self._items = CircularDoubleLinkedNode() def __len__(self): return len(self._items) def __iter__(self): for item in self._items: yield item def push(self, value): self._items.append(value) def pop(self): return self._items.popleft() def is_empty(self): return len(self._items) == 0 def test(): q = Queue() for i in range(5): q.push(i) assert list(q) == [i for i in range(5)] assert len(q) == 5 for i in range(5): assert q.pop() == i assert len(q) == 0 if __name__ == "__main__": test()
def long_repeat(line): """ length the longest substring that consists of the same char """ n='' a='' for i in line: if i!=n: n=i a=a+','+i else : a=a+i b=a.strip(',').split(',') sum=0 for i in b: if sum<len(i): sum=len(i) # your code here return sum if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert long_repeat('sdsffffse') == 4, "First" assert long_repeat('ddvvrwwwrggg') == 3, "Second" assert long_repeat('abababaab') == 2, "Third" assert long_repeat('') == 0, "Empty" print('"Run" is good. How is "Check"?')
from collections import Counter def checkio(text: str) -> str: a = list(filter(nonum, text)) b = [] for i in a: b.append(i.lower()) x = sorted(Counter(b).most_common(), key=lambda x: x[1], reverse=True) def p(n): if n[1] < x[0][1]: return False else: return True return sorted(list(filter(p, x)), key=lambda x: x[0])[0][0] def nonum(n): if n.isdigit(): return False if ord(n) < 65 or 90 < ord(n) < 97 or ord(n) > 122: return False else: return True if __name__ == '__main__': print("Example:") print(checkio("Hello World!")) # These "asserts" using only for self-checking and not necessary for auto-testing assert checkio("Hello World!") == "l", "Hello test" assert checkio("How do you do?") == "o", "O is most wanted" assert checkio("One") == "e", "All letter only once." assert checkio("Oops!") == "o", "Don't forget about lower case." assert checkio("AAaooo!!!!") == "a", "Only letters." assert checkio("abe") == "a", "The First." print("Start the long test") assert checkio("a" * 9000 + "b" * 1000) == "a", "Long." print("The local tests are done.")
def health_calculator(age, apples_ate, cigs_smoked): answer = (100-age) + (apples_ate * 2.5) - (cigs_smoked * 3) print(answer) my_data = [26, 1, 0] # Unpacking an argument list health_calculator(*my_data)
# 3.4 = Pillow, 2.7 = PIL (PIL is 3.4 compatible, use it) from PIL import Image # Open image img = Image.open("sampleImage1.jpg") # Print image size, format print(img.size) print(img.format) # Crop image area = (100, 100, 200, 200) # (left, top, right, bottom) cropped_img = img.crop(area) # Display image cropped_img.show() # opens with default image viewer, creates temp file name # Combine images together img1 = Image.open("sampleImage2.jpg") img2 = cropped_img area1 = (100, 100, 200, 200) img1.paste(img2, area1) img1.show()
import timeit # Timing performances print("List performance: ", end="") l = timeit.timeit(stmt='10**6 in a', setup='a = range(10**6)', number=100000) print(l, end="") print("\nSet performance: ", end="") s = timeit.timeit(stmt='10**6 in a', setup='a = set(range(10**6))', number=100000) print(s, '\n') # Printing out which took less time if s == l: print("Set and List performance are equal") elif s > l: print("List performance better than Set performance") else: print("Set performance better than List performance") # LIST vs. SET # A list keeps order, dict and set don't: when you care about order, therefore, you must use list (if your choice of containers is limited to these three, of course;-). # dict associates with each key a value, while list and set just contain values: very different use cases, obviously. # set requires items to be hashable, list doesn't: if you have non-hashable items, therefore, you cannot use set and must instead use list. # set forbids duplicates, list does not: also a crucial distinction. (A "multiset", which maps duplicates into a different count for items present more than once, can be found in collections.Counter -- you could build one as a dict, if for some weird reason you couldn't import collections, or, in pre-2.7 Python as a collections.defaultdict(int), using the items as keys and the associated value as the count). # Checking for membership of a value in a set (or dict, for keys) is blazingly fast (taking about a constant, short time), while in a list it takes time proportional to the list's length in the average and worst cases. So, if you have hashable items, don't care either way about order or duplicates, and want speedy membership checking, set is better than list. # When you want to store some values which you'll be iterating over, Python's list constructs are slightly faster. However, if you'll be storing (unique) values in order to check for their existence, then sets are significantly faster. # You may want to consider Tuples as they're similar to lists but can’t be modified. They take up slightly less memory and are faster to access. They aren’t as flexible but are more efficient than lists. Their normal use is to serve as dictionary keys.
# The difference between import module and from module import foo is mainly subjective. Pick the one you like best and be consistent in your use of it. Here are some points to help you decide. import module # Pros: # Less maintenance of your import statements. Don't need to add any additional imports to start using another item from the module # Cons: # Typing module.foo in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing mo.foo) from module import foo # Pros: # Less typing to use foo # More control over which items of a module can be accessed # Cons: # To use a new item from the module you have to update your import statement # You lose context about foo. For example, it's less clear what ceil() does compared to math.ceil() # Either method is acceptable, but don't use from module import *. # For any reasonable large set of code, if you import * you will likely be cementing it into the module, unable to be removed. This is because it is difficult to determine what items used in the code are coming from 'module', making it easy to get to the point where you think you don't use the import any more but it's extremely difficult to be sure. # -------------------------- # What's the difference between "import foo" and "from foo import *"? #1) import sys # This brings the name “sys” into your module. # (Technically, it binds the name “sys” to the object that is the sys module.) # It does not give you direct access to any of the names inside sys itself (such as exit for example). To access those you need to prefix them with sys, as in sys.exit() #2) from sys import * # This does NOT bring the name “sys” into your module, instead it brings all of the names inside sys (like exit for example) into your module. Now you can access those names without a prefix, like this: exit() # So why not do that instead of import sys? # The reason is that the second form will overwrite any names you have already declared — like exit say. exit = 42 from sys import * # hides my exit variable. # OR more likely, the other way round from sys import * exit = 42 # now hides the sys.exit function so I can't use it. #Of course some of these are obvious but there can be a lot of names in a module, and some modules have the same name in them, for example: from os import * from urllib import * open(foo) # which open gets called, os.open or urllib.open or open? #Can you see how it gets confusing?
# Printing binary and hex values print("binary:", bin(8)) print("hex: ", hex(10)) # AND a = 50 # 110010 b = 25 # 011001 c = a & b print('\n', "AND: ", bin(c),' ',c, sep='') # OR d = a | b print('\n',"OR: ", bin(d),' ',d, sep='') # Shift x = 240 # 11110000 y = x >> 2 print('\n',"Shift: ", bin(y),' ',y, sep='')
import unittest from Testing import main class TestMain(unittest.TestCase): def setUp(self): print('about to test a function') def test_do_stuff(self): """You can add docstrings within test functions""" test_param = 10 result = main.do_stuff(test_param) self.assertEqual(result, 15) # Ran test in 0.002s, OK def test_do_stuff2(self): test_param = 10 result = main.do_stuff(test_param) self.assertEqual(result, 10) # AssertionError: 15 != 10 def test_do_stuff3(self): test_param = 'asdf' result = main.do_stuff(test_param) self.assertEqual(result, ValueError) # AssertionError: ValueError("invalid literal for int() with base 10: 'asdf'") != <class 'ValueError'> def test_do_stuff4(self): test_param = 'asdf' result = main.do_stuff(test_param) self.assertIsInstance(result, ValueError) # Ran test in 0.001s, OK def test_do_stuff5(self): test_param = None result = main.do_stuff(test_param) self.assertEqual(result, ValueError) # TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' def test_do_stuff6(self): test_param = None result = main.do_stuff(test_param) self.assertEqual(result, 'please enter number') # Ran test in 0.001s, OK def test_do_stuff7(self): test_param = '' result = main.do_stuff(test_param) self.assertEqual(result, 'please enter number') # Ran test in 0.001s, OK def test_do_stuff8(self): test_param = 0 result = main.do_stuff(test_param) self.assertEqual(result, 'please enter number') # Ran test in 0.001s, OK def tearDown(self): print('cleaning up') if __name__ == '__main__': unittest.main()
numbers = [number for number in range(1,21)] print(numbers) numbers2 = [number for number in range(1,10000001)] number_min = min(numbers2) number_max = max(numbers2) number_sum = sum(numbers2) print(number_min,number_max,number_sum) numbers3 = [] for number in range(1,21,2): numbers3.append(number) for number in numbers3: print(number)
def make_shirt(size, font='I love Python'): print("This T-shirt'size is " + size + " and the font is " + font) make_shirt('BIG') make_shirt(size='middle') make_shirt('small', font='ABCD')
class ListInfo: """定义一个列表的操作类""" def __init__(self, list_info): self.list = list_info def add_key(self, info): # 添加的key必须是字符串或数字 if isinstance(info, (str, int)): self.list.append(info) return self.list else: return "str or int" def get_key(self, num, value): if num > len(self.list): return "Wrong" else: self.list[num] = value return self.list def update_list(self, list_new): return self.list.extend(list_new) def del_key(self): if len(self.list) > 0: delkey = self.list.pop(-1) return delkey else: return "NO NUMBER"
import math class Point: def __init__(self, x, y): self.x = x self.y = y def get_x(self): return self.x def get_y(self): return self.y class Line: def __init__(self, p1, p2): self.x = p1.get_x() - p2.get_x() self.y = p1.get_y() - p2.get_y() self.len = math.sqrt(self.x ** 2 + self.y** 2) def get_len(self): return self.len # 其他类中的方法可以先行在类中使用 p1 = Point(2, 3) p2 = Point(5, 7) line = Line(p1, p2) print(line.get_len())
import random import math from c1_1 import * """ 输入一个三位数与程序随机数比较大小 1 如果大于程序随机数,则分别输出这个三位数的个位、十位、百位 2 如果等于程序随机数,则提示中奖,记100分 3 如果小于程序随机数,则将120个字符输入到文本文件中 (规则是每一条字符串的长度为12,单独占一行,并且前四个是字母,后8个是数字 """ # 输入函数 while True: num = input("请输入一个三位数:") random_number = random.randint(100, 999) # 检测输入是否是纯数字 if num.isdigit() and 100 <= int(num) <= 999: if int(num) < random_number: comparison_small(num) break elif int(num) > random_number: result = comparison_big(random_number) break else: print('请按规定输入')
import math def comparison_small(num): """小于比较""" print("这是一个小于") def comparison_big(num): """大于比较""" num = int(num) num_one = num//100 num_two = num%100//10 num_three = num%100%10 print("百位是{}".format(num_one)) print("十位是{}".format(num_two)) print("个位是{}".format(num_three)) # return num_one
alien_color = 'red' if alien_color == "green": print("You get 5 points") elif alien_color == "red": print("You get 10 points") else: print("You get 15 points")
name_invented = ['xuweicheng', 'zhangbo', 'zhuyifan', 'daipaiyu'] for i in name_invented: print("Congralution! You are invented in this party, " + i.title()) print("It's shame that " + name_invented[0].title() + " can't come with us") del name_invented[0] name_invented.insert(0,'wangluodan') print(name_invented) name_invented.insert(1,'lizhiyao') name_invented.append('liuhaiyang') for i in range(5): print("invented " + name_invented[i]) num1 = name_invented.pop(0) print("Sorry, you are not in the list of invented " + num1) num2 = name_invented.pop(0) print("Sorry, you are not in the list of invented " + num2) num3 = name_invented.pop(0) print("Sorry, you are not in the list of invented " + num3) num4 = name_invented.pop(0) print("Sorry, you are not in the list of invented " + num4) for i in name_invented: print("Remember to come on time " + i.title()) del name_invented[0] del name_invented[0] print(name_invented)
import argparse import os import sys parser = argparse.ArgumentParser(description="Create code project templates for C++, HTML and Python") parser.add_argument("-t", "--template", help="Defines the template that you want to make", required=True) parser.add_argument("-asrc", "--addsrc", action="store_true", help="Choose whether or not to add a SRC folder for your project") parser.add_argument("-cpphdir", "--cppheaderdirectory",action="store_true", help="Choose if you want to make a directory for header files (Only in C++ template)") parser.add_argument("-ajs", "--addjavascript", action="store_true", help="Choose if you want an main.js file in your HTML template") parser.add_argument("-hfile", "--headerfilecpp", action="store_true", help="Choose if you want to create a header file for your main source file") parser.add_argument("-chjs", "--cssjshtml", action="store_true", help="Choose if you want a CSS-HTML-JS folder structure for your HTML template") args = parser.parse_args() def enterCLI(templateType): while True: cmd = input("\n{} $: ".format(templateType)).split(" ") if (cmd[0] == "cls" or cmd[0] == "clear"): os.system("cls") if sys.platform == "win32" else os.system("clear") elif (cmd[0] == "sysplatform"): print(sys.platform) if ("C++" in templateType): if (cmd[0] == "new" and cmd[1] == "header-source"): if (input("Create a new source file with a header? ({}) y/n: ".format(cmd[2]).lower()) == "y"): if (os.path.exists(os.getcwd() + "/src")): os.system("touch src/{}".format(cmd[2])) else: os.system("touch {}".format(cmd[2])) if (os.path.exists(os.getcwd() + "/headers")): os.system("touch headers/{}".format(str(cmd[2])[0:len(cmd[2]) - 4] + ".h")) else: os.system("touch {}".format(str(cmd[2])[:2] + ".h")) print("Added new source file and header file. ({})".format(cmd[2])) else: print("Not created. ") continue if ("Python" in templateType): if (cmd[0] == "new" and cmd[1] == "pyfile"): if (input("Create a new python file? y/n: ").lower() == "y"): if (os.path.exists(os.getcwd() + "/src")): os.system("touch src/{}".format(str(cmd[2]))) else: os.system("touch {}".format(str(cmd[2]))) else: print("Not created. ") continue def createCPPTemplate(isheader, toGenerateSrcFolder): print("Creating C++ template for directory " + os.getcwd() + ".\n\nGenerated SRC folder: " + str(toGenerateSrcFolder)) print("To make header file: " + str(args.headerfilecpp)) print("To make directory for header files: " + str(isheader)) yn = input("Do these configurations look good to you? y/n: ").lower() if (yn == "y"): try: if (toGenerateSrcFolder): os.mkdir("src") os.system("touch src/main.cpp") else: os.system("touch main.cpp") if (isheader): os.system("mkdir headers") if (isheader and args.headerfilecpp): os.system("touch headers/main.h") elif (args.headerfilecpp): os.system("touch main.h") print("template created...\n") enter = input("Would you like to enter your template CLI? y/n: ") enter = enter.lower() enterCLI("C++ template ") if enter == "y" else exit(0) except Exception as e: print("Failed to create template for c++. Error occured: \n") print(e) elif (yn == "n"): print("template not created") input() else: print("error: you didn't enter y or n. Aborted") exit(0) def createPythonTemplate(toGenerateSrcFolder): print("Creating Python template for directory " + os.getcwd() + ".\n\nGenerated SRC folder: " + str(toGenerateSrcFolder)) yn = input("Do these configurations look good to you? y/n: ").lower() if (yn == "y"): try: if (toGenerateSrcFolder): os.mkdir("src") os.system("touch src/main.py") else: os.system("touch main.py") print("template created...\n") enter = input("Would you like to enter your template CLI? y/n: ") enter = enter.lower() enterCLI("Python template ") if enter else exit(0) except Exception as e: print("Failed to create template for python. Error occured: \n") print(e) elif (yn == "n"): print("template not created") input() else: print("error: you didn't enter y or n. Aborted") exit(0) def createHTMLTemplate(withJS, chjs_struct): print("Creating HTML template for directory " + os.getcwd() + ".") print("Generated JS file (main.js): " + str(withJS)) print("HTML-CSS-JS folder structure: " + str(chjs_struct)) yn = input("Do these configurations look good to you? y/n: ").lower() if (yn == "y"): try: if (chjs_struct): os.mkdir("HTML") os.mkdir("CSS") os.mkdir("JS") os.system("touch HTML/index.html & touch CSS/index.css") else: os.system("index.html") os.system("index.css") if (withJS): if (os.path.exists(os.getcwd() + "/JS")): os.system("touch JS/main.js") else: os.system("touch main.js") except Exception as e: print("Failed to create template for HTML. Error occured: \n") print(e) elif (yn == "n"): print("template not created") input() else: print("error: you didn't enter y or n. Aborted") exit(0) if (args.template): args.template = args.template.lower() if (args.template == "html"): createHTMLTemplate(args.addjavascript, args.cssjshtml) elif (args.template == "c++" or args.template == "cpp"): createCPPTemplate(args.cppheaderdirectory, args.addsrc) elif (args.template == "py" or args.template == "python" or args.template == "python3"): createPythonTemplate(args.addsrc)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2016-03-14 20:16:01 # @Author : Damon Chen ([email protected]) # @Link : www.zhenchen.me # @Version : $Id$ # @Description: import os class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ for i in range(len(nums) - 1): j = i + 1 if nums[i] == 0: while j < len(nums) and nums[j] == 0: j += 1 if j == len(nums): break nums[i] = nums[j] nums[j] = 0 return nums if __name__ == '__main__': sol = Solution() print(sol.moveZeroes([1,2,3,0,4,5,0,0,0,7,8]))
x = "there are %d types of people." % 10 # variable with string inside # Defining decimal variable %d at end of string binary = "binary" do_not = "don't" y = "Those who know %s and those who %s." % (binary, do_not) # variable with strings inside # defining multiple string variables %s print x # print varible x print y # print variable y print "I said: %r." % x # %r raw data for debugging # calling variable x with %r defining variable at end of line # variables that use other variables print "I also said: '%s'." % y # calling for string variable %s difining variable at end of line # using string variable that has multiple variables in string hilarious = False # variable with boolean value True or False joke_evaluation = "Isn't that joke so funny?! %r" # variable with string. %r in string not defined yet print joke_evaluation % hilarious # calling variable joke_evaluation # calling for variable hilarious # %r is defind after joke_evaluation # %r stands for repr or a string containing a printable- # representaion of an object w = "This is the left side of..." e = "a string with a right side" print w + e # prints without space print w, e # prints with space
print "How old are you?", age = raw_input() # comma prevents new line # variable asking for data raw_input() # You can put any kind of data in raw_input() print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "so, you're %r old, %r tall and %r heavy." % ( age, height, weight) # print string with variables inside- # Calling variables at the end of string
""" Given a array/list , return a randomly shuffle array/list this is implementation of "Fisher–Yates shuffle Algorithm",time complexity of this algorithm is O(n) assumption here is, function rand() that generates random number in O(1) time. Examples: Given [1,2,3,4,5,6,7], [5, 2, 3, 4, 1] Given [1,2,3,4,5,6,7], [1,2,3,4,5,6,7] Given [1,2,3,4,5,6,7], [1, 2, 3, 5, 4] """ import random def randomize_array(arr): for i in range(len(arr)-1,0,-1): # To generate a random nummber within it's index j = random.randint(0,i) # Swap arr[i] with the element at random index arr[i],arr[j] = arr[j],arr[i] return arr
""" 4. Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ... Количество элементов (n) вводится с клавиатуры. Пример: Введите количество элементов: 3 Количество элементов - 3, их сумма - 0.75 ЗДЕСЬ ДОЛЖНА БЫТЬ РЕАЛИЗАЦИЯ ЧЕРЕЗ ЦИКЛ """ try: N = int(input('Введите число елементов в последовательности: ')) S = 1 i = 1 El = 1 while i < N: El /= -2 S = S + El i += 1 print(f'Кол-во элементов: {N}, их сумма: {S}') except ValueError: print('Вы ввели не число, повторите.')
import sys sys.stdin = open("args1.txt") def answer(): f, s = list(map(int, input().split())) ans = 0 return " ".join( str(a) for a in sorted(ans)) def main(): ncases = int(input()) for i in range(ncases): print("Case #{0}: {1}".format(i + 1, answer())) if __name__ == "__main__": main()
class Solution: def canPartition(self, nums: List[int]) -> bool: total = sum(nums) if total % 2: return False target = total // 2 # * Sort the array -> NlogN # * Create a current sum set for all possible (deduped) sums # * Check if the target is in the total # * if the sums all > target, then return False -> < N^2 # * Example: [1,5,11,5] -> [1,5,5,11], target: 11 # nums.sort() # ? Why don't we need to sort it? partial_sums = set([0]) # * Zero for keeping single elements. for num in nums: all_is_greater = True new_sums = partial_sums.copy() for psum in partial_sums: new_sum = psum + num if new_sum == target: return True elif new_sum < target: all_is_greater = False new_sums.add(new_sum) # *> End for if all_is_greater: return False partial_sums = new_sums return False
class Solution: def uniquePaths(self, m: int, n: int) -> int: ## Start from the finish line ## Only move to left and up ## Every position is the sum of its right and down grid = [[0]*(n+1) for _ in range(m+1)] for row in reversed(range(m)): for col in reversed(range(n)): # print(row, col) if row == m-1 and col == n-1: grid[row][col] = 1 # * Finish line. else: grid[row][col] = grid[row+1][col] + grid[row][col+1] return grid[0][0]
# -*- coding: utf-8 -*- # @Time : 2017/10/5 15:43 # @Author : Yulong Liu # @File : p0005_M_LongestPalindromicSubstring.py """ 题号:5 难度:medium 链接:https://leetcode.com/problems/longest-palindromic-substring/description/ 描述:找出一个长度不大于1000的字符串中的最长回文子串(非子序列) """ class Solution(object): def longestPalindrome(self, s): """ 思路:dp :type s: str :rtype: str """ if not s: return '' size = len(s) start = 0 max_length = 1 F = [[False for x in range(size)] for y in range(size)] # 初始化边界数据 for i in range(size): F[i][i] = True if i+1 < size and s[i] == s[i+1]: F[i][i+1] = True start = i max_length = 2 # 依次判断每个长度的子串(由于长度1和2已结初始化了,这里直接从3开始判断) for length in range(3, size+1): for i in range(size-length+1): j = i + length - 1 if F[i+1][j-1] and s[i] == s[j]: F[i][j] = F[i+1][j-1] if length > max_length: start = i max_length = length return s[start:start+max_length] def longestPalindrome2(self, s): """ 从网上抄的代码,效率超高 :type s: str :rtype: str """ ls = len(s) maxs = '' i = 0 while 2 * (ls - i) - 1 > len(maxs): pl = pr = i # move the current index (i) and the right pointer (pr), if the consecutive letters are the same while pr < ls - 1 and s[pr] == s[pr + 1]: i += 1 pr += 1 # move left and right pointers, so that the substring between them is longer than maxs dif = len(maxs) - (pr - pl) if dif > 0: dif += dif % 2 pl, pr = pl - dif / 2, pr + dif / 2 # check whether the substring is palindrome. # If yes, try to further extend it, and then replace maxs with the new substring if s[pl:pr + 1] == s[pr:(pl - 1 if pl > 0 else None):-1]: while pl > 0 and pr < ls - 1 and s[pl - 1] == s[pr + 1]: pl -= 1 pr += 1 maxs = s[pl:pr + 1] i += 1 return maxs if __name__ == '__main__': print(Solution().longestPalindrome('babad'))
x = 1 total = 0 for x in range(1,10): total = total + x x = x + 1 print("x=",total)
#!/usr/bin/env python ''' Leetcode: Search in Rotated Sorted Array Leetcode: Search in Rotated Sorted Array II http://leetcode.com/2010/04/searching-element-in-rotated-array.html ''' from __future__ import division import random ''' Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. ''' # modified binary search, O(logn) # Search in L[i:j] def search_rotated_arr(L, val): l = 0; r = len(L)-1 while l <= r: mid = (l + r + 1)//2 if L[mid] == val: return mid if L[l] <= L[mid]: # the lower half is sorted if L[l] <= val <= L[mid]: r = mid-1 else: l = mid+1 else: # the upper half is sorted if L[mid] <= val <= L[r]: l = mid+1 else: r = mid-1 return -1 def find_rotated_pivot(L): l = 0; r = len(L)-1 while L[l] > L[r]: mid = (l + r + 1)//2 if L[mid] > L[r]: l = mid+1 else: r = mid return l ''' What if duplicates are allowed? Would this affect the run-time complexity? How and why? Write a function to determine if a given target is in the array. ''' def search_rotated_arr2(L, val, i, j): #print L[i:j] if i == j-1: return L[i] == val elif i >= j-1: return False else: mid = (i+j)//2 if L[mid] == val: return True lower = upper = False if (L[i] >= L[mid]) or (val < L[mid]): lower = search_rotated_arr2(L, val, i, mid) if (L[mid] >= L[j-1]) or (L[mid] < val): upper = search_rotated_arr2(L, val, mid, j) return lower or upper if __name__ == '__main__': print search_rotated_arr([4,5,6,7,0,1,2], 6, 0, 7) print search_rotated_arr([4,5,6,7,0,1,2], 0, 0, 7) print search_rotated_arr([4,5,6,7,0,1,2], 3, 0, 7) print print search_rotated_arr2([4,5,7,0,1,2,4,4], 7, 0, 8) print search_rotated_arr2([4,5,6,7,0,0,1,2], 0, 0, 8) print search_rotated_arr2([4,4,4,4,5,2], 3, 0, 6)
#!/usr/bin/env python ''' Leetcode: Search for a Range Given a sorted array of integers, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4]. ''' from __future__ import division import random # O(log n) in time. # Search in L[i:j] def binary_range_search(L, val, i, j): if L[i] == L[j-1] == val: return range(i,j) if i == j-1 and L[i] != val: return [] if i > j-1: return [] # L[i:mid], L[mid:j] mid = (i+j)//2 lower = []; upper = [] if val <= L[mid]: lower = binary_range_search(L, val, i, mid) if val >= L[mid]: upper = binary_range_search(L, val, mid, j) return lower + upper def search_range(L, val): return binary_range_search(L, val, 0, len(L)) if __name__ == '__main__': print search_range([1,2,3,3,3,3,3,3,3,4,5,6,6,6,6,6,7], 3) print search_range([1,2,3,3,4,5,5,6,7,8,9], 3) print search_range([1,2,3], 3) print search_range([3], 3) print search_range([3,3,4,5], 3)
#!/usr/bin/env python from __future__ import division class Node(object): def __init__(self, value, next=None, prev=None): self.prev = prev self.next = next self.value = value def __str__(self): if self.next is None: return str(self.value) else: return '%d (%s)' % (self.value, str(self.next)) def __repr__(self): s = 'LinkedListNode Object (value='+str(self.value)+')' return s
#!/usr/bin/env python ''' Leetcode: Longest Palindromic Substring Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. http://leetcode.com/2011/11/longest-palindromic-substring-part-i.html http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html ''' from __future__ import division # Using pair of indices for same lements # ~O(n^2) def longest_palin_substr1(s): print s, '-->', elems = set(list(s)) pos = {} for i, elem in enumerate(list(s)): pos.setdefault(elem,[]).append(i) #print pos # Get pairs of locations with same element pairs = set() for elem in pos: elem_pos = pos[elem] for i in range(len(elem_pos)): for j in range(i+1, len(elem_pos)): pairs.add((elem_pos[i],elem_pos[j])) # Prioritize distant pairs sorted_pairs = sorted(pairs, key=lambda x:x[1]-x[0], reverse=True) #print sorted_pairs for start, end in sorted_pairs: i, j = start, end while i < j: if not (i,j) in pairs: break i += 1 j -= 1 if i >= j: # find a match! return s[start:end+1] return '' # Reverse S and become S'. Find the longest common substring between S and S', which must also be the longest palindromic substring. # For example, S="abacdfgdcaba", S'="abacdgfdcaba". # The longest common substring between S and S' is "abacd". Clearly, this is not a valid palindrome. def longest_palin_substr2(s): n = len(s) if n == 0: return '' rev_s = s[::-1] # longest common string with same indices (i <--> n-1-i) # DP? longest_common_string(s, rev_s) # DP: P(i,j) = true if S[i:j+1] is palindrome # P(i,j) = P(i+1,j-1) and S[i] == S[j] # ~O(n^2) in time, ~O(n^2) in space def longest_palin_substr3(s): n = len(s) if n == 0: return '' P = {} for i in range(n): P[(i,i)] = True # k = j-i between 0 and n-1 for k in range(n-1): for i in range(n): j = i+k if j >= n: continue if i+1 <= j-1: P[(i,j)] = P[(i+1,j-1)] and s[i] == s[j] else: P[(i,j)] = s[i] == s[j] start, end = max([k for k in P if P[k]], key=lambda x:x[1]-x[0]) return s[start:end+1] # Find center of a substring palindrome and expand it # ~O(n^2) in time and ~O(1) in space def longest_palin_substr4(s): n = len(s) if n == 0: return '' max_pali = '' # Center can be on a letter or between letters for i in range(n): for j in [i,i+1]: # Center at s[i:j+1] while i >= 0 and j <= n-1: if s[i] != s[j]: break i -= 1 j += 1 cur_pali = s[i+1:j] if len(cur_pali) > len(max_pali): max_pali = cur_pali return max_pali # Manacher's Algorithm # http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html # http://www.felix021.com/blog/read.php?2040 # ~O(n) def longest_palin_substr5(s): # reformat the string s = list(s) # so that all the palindrome substrings are of odd length for i in range(len(s)+1): s.insert(i*2,'#') print s p = defaultdict(int) # left/right length of palindrome centered at s[i] max_center = 0 # current maximum palindrom's center max_upper = 0 # maximum palindrom's upper boundary, max_center+P[max_center] for i in range(1,len(s)): # i & j are symmetric points to max_center_id j = 2*max_center - i p[i] = min(p[j], max_upper-i) if max_upper > i else 1 while i-p[i] >= 0 and i+p[i] <= len(s)-1 and s[i+p[i]] == s[i-p[i]]: p[i]+=1 if p[i]+i > max_upper: max_upper = p[i]+i max_center = i print 's:', ','.join(s) print 'p:', ','.join(map(str, [p[i] for i in range(len(s))])) return max(p.values())-1 # Using suffix tree # ~O(nlogn) if __name__ == '__main__': __func__ = longest_palin_substr4 print __func__('cabcbaabac') print __func__('abbaaa') print __func__('abacdfgdcaba') print __func__('aaaaaaa') print __func__('')
#!/usr/bin/env python ''' Leetcode: Gas Station There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. Note: The solution is guaranteed to be unique. ''' from __future__ import division import random # We can use a Queue to store the current tour. We first enqueue first petrol pump to the queue, we keep enqueueing petrol pumps till we either complete the tour, or current amount of petrol becomes negative. If the amount becomes negative, then we keep dequeueing petrol pumps till the current amount becomes positive or queue becomes empty. def gas_station(gas, cost): n = len(gas) start = 0; next = 1 Q = [] cur_gas = gas[start] - cost[start] while start != next or cur_gas < 0: while start != next and cur_gas < 0: # pop, changing starting point cur_gas -= gas[start] - cost[start] start = (start+1)%n if start == 0: # go back to the first trial return -1 cur_gas += gas[next] - cost[next] next = (next+1)%n return start ''' What if we want to keep the leftover gas as much as possible? ''' # G(i,j) = the maximum leftover gas a car goes from i-th station to j-th. # the car can use gas at i-th but not at j-th # only valid when G(i,j) >= 0 # G(i,j) = max{G(i,mid)+G(k,mid) for i < mid < j, # gas[i] - (cost[i]+...+cost[j])} # We use G(i,i) for a circular route. # ~ O(n^3) def gas_station2(gas, cost): n = len(gas) G = {} for i in range(n): G[i,(i+1)%n] = gas[i] - cost[i] print G for k in range(2,n+1): for i in range(n): j = (i+k) % n G[i,j] = -float('inf') sum_cost = cost[i] # with stop for mid in range(i+1,i+k): mid = mid % n if G[i,mid] >= 0: G[i,j] = max(G[i,j], G[i,mid]+G[mid,j]) sum_cost += cost[mid] # no stop if gas[i]-sum_cost > 0: G[i,j] = max(G[i,j], gas[i]-sum_cost) circles = dict((i, G[i,j]) for i,j in G if j == i) print circles return max(circles.values()) >= 0 ''' What if we want to get the trip with the minimum times of stops? ''' # G(i,j,s) = maximum leftover gas from i-th to j-th station with s stops in-between; 0 <= s <= j-i-1 # G(i,j,0) = gas[i] - sum(cost[i..j-1]) # G(i,j,s) = max{G(i,mid,s1) + G(mid,j,s2) for # 0 <= s1 <= mid-i-1, # 0 <= s2 <= j-mid-1, # s1+s2+1 == s} # Final results: argmin_s G(i,j,s) >= 0. # ~O(n^4) def gas_station3(gas, cost): n = len(gas) G = {} for i in range(n): G[i,(i+1)%n,0] = gas[i] - cost[i] for k in range(2, n+1): for i in range(n): j = i+k G[i,j%n,0] = gas[i] - sum([cost[x%n] for x in range(i,j)]) for s in range(1, k): G[i,j%n,s] = -float('inf') for mid in range(i+1,i+k): for s1 in range(0, mid-i): s2 = s-s1-1 if s2 < 0 or s2 > j-mid-1: continue print '(i,j,s)=(%d,%d,%d)'%(i,j,s), s1, s2 G[i,j%n,s] = max(G[i,j%n,s], \ G[i,mid%n,s1]+G[mid%n,j%n,s2]) #''' for x,y,z in G: if z == s: print x,y,z, ':', G[x,y,z] #''' for k,v in G.items(): print k,v min_step = n-1 for i in range(n): args = [x for x in range(0,n) if G[i,i,x] > 0] if args: min_s = min(args) min_step = min(min_step, min_s) print i,'-->',i, 'steps:',min_s, 'leftover gas:', G[i,i,min_s] return min_step # Greedy algorithm, starting at if __name__ == '__main__': gas = [10,5,10,5,10] cost = [2,2,2,5,2] print gas_station3(gas, cost)
#!/usr/bin/env python ''' Leetcode: Copy List with Random Pointer A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. ''' from __future__ import division import random import LinkedList class Node(LinkedList.Node): def __init__(self, value, next=None, prev=None, randp=None): super(Node, self).__init__(value, next, prev) self.randp = randp def __str__(self): if self.randp is None: s = '[%d]' % self.value else: s = '[%d,%d]' % (self.value, self.randp.value) if self.next: s += '->(%s)' % str(self.next) return s # Brute-force # create the list first and then set up the pointer def copylist(head): new_head = Node(head.value) # Copy the list prev_n = new_head node = head.next while node: n = Node(node.value) prev_n.next = n prev_n = n node = node.next # Assign pointer node = head new_node = new_head while node: if node.randp: # locate the pointer h = head newh = new_head while h != node.randp: h = h.next newh = newh.next new_node.randp = newh node = node.next new_node = new_node.next print 'Orig:', head print 'Copy:', new_head if __name__ == '__main__': n6 = Node(6) n5 = Node(5, n6) n4 = Node(4, n5) n3 = Node(3, n4) n2 = Node(2, n3) n1 = Node(1, n2) n1.randp = n4 n2.randp = n4 n4.randp = n6 n5.randp = n3 copylist(n1)
#!/usr/bin/env python ''' Leetcode: Recover Binary Search Tree Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? ''' from __future__ import division import random from BinaryTree import Node, BST def find_outliers(root, outliers): if root.left: if root.left.value <= root.value: find_outliers(root.left, outliers) else: outliers.append(root.left) if root.right: if root.right.value >= root.value: return find_outliers(root.right, outliers) else: outliers.append(root.right) # time ~ O(n), space ~ O(1) def recover_BST(root): print root outliers = [] find_outliers(root, outliers) x, y = outliers print x, y # swith them x.value, y.value = y.value, x.value print root if __name__ == '__main__': recover_BST(BST)
#!/usr/bin/env python ''' Leetcode: Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. ''' from __future__ import division import random '''A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.''' def sort_colors(L): from collections import Counter counter = Counter(L) for i,x in enumerate(counter.elements()): L[i] = x return L ''' Follow up: Could you come up with an one-pass algorithm using only constant space? ''' def sort_colors2(L): n = len(L) zero = 0; two = n-1 # Write 1 at the beginning; 2 at the end. cur = 0 while cur <= two: print cur, L, zero, two if L[cur] == 0: if cur > zero: L[zero], L[cur] = L[cur], L[zero] zero += 1 else: # TRICKY PART. # cur == zero and L[cur] == L[zero] == 0 cur += 1 zero += 1 elif L[cur] == 2: if cur < two: L[two], L[cur] = L[cur], L[two] two -= 1 else: break else: cur += 1 print L, '\n' return L def sort_colors3(A): n = len(A) k = 0; zero = 0; two = n-1 while k <= two: if A[k] == 0 and zero < k: A[k], A[zero] = A[zero], A[k] while A[zero] == 0: zero += 1 elif A[k] == 2 and k < two: A[k], A[two] = A[two], A[k] while A[two] == 2: two -= 1 else: k += 1 print k, zero, two, A print A if __name__ == '__main__': sort_colors2([2,0,1,0,2,1,2,2,1,1]) sort_colors2([2,1,2,1,2,0]) sort_colors2([0,0,1,2,2,2,0,0,0])
#!/usr/bin/env python ''' Leetcode: Binary Tree Maximum Path Sum Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For example: Given the below binary tree, 1 / \ 2 3 Return 6. 2-1-3 ''' from __future__ import division import random from BinaryTree import Node, SampleTreeRoot # L(node) = max sum path in node's left sub-tree # R(node) = max sum path in node's right sub-tree # L(node) = node.val + max{L(node.left), R(node.left)} # R(node) = node.val + max{L(node.right), R(node.right)} # max{L(node)+R(node) for any node in the tree} def subtree_maxsum_path(node, is_left=True, Lpath={}, Rpath={}): if is_left: # left sub-tree if not node.left: Lpath[node.id] = 0 return 0 else: Lpath[node.id] = node.value + max( subtree_maxsum_path(node.left, True, Lpath, Rpath), subtree_maxsum_path(node.left, False, Lpath, Rpath) ) return Lpath[node.id] else: # right sub-tree if not node.right: Rpath[node.id] = 0 return 0 else: Rpath[node.id] = node.value + max( subtree_maxsum_path(node.right, True, Lpath, Rpath), subtree_maxsum_path(node.right, False, Lpath, Rpath) ) return Rpath[node.id] def maxsum_path(root): Lpath = {} Rpath = {} subtree_maxsum_path(root, True, Lpath, Rpath) subtree_maxsum_path(root, False, Lpath, Rpath) print 'Left-path:', Lpath print 'Right-path:', Rpath path2sum = dict((i, Lpath[i]+Rpath[i]) for i in Lpath.keys()) i = max(path2sum, key=path2sum.get) print 'The path going through node', i, 'with max sum', path2sum[i] return path2sum[i] if __name__ == '__main__': print maxsum_path(SampleTreeRoot)
#!/usr/bin/env python from __future__ import division import random from BinaryTree import Node, root, root_with_id ''' Leetcode: Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. ''' def path_sum(root, val): if not root: return False if not root.left and not root.right: return val == root.value return path_sum(root.left, val-root.value) or path_sum(root.right, val-root.value) ''' Leetcode: Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 6 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] ''' def path_finder(root, val, path, paths): if not root: return False if not root.left and not root.right: if root.value == val: path.append(root.value) paths.append(path) return True else: return False left = path_finder(root.left, val-root.value, path+[root.value], paths) right = path_finder(root.right, val-root.value, path+[root.value], paths) # make sure it can be executed! return left or right def path_sum2(root, val): paths = [] path_finder(root, val, [], paths) print 'sum:', val print 'paths:', paths if __name__ == '__main__': path_sum2(root_with_id, 4) path_sum2(root_with_id, -4) path_sum2(root, 22) path_sum2(root, 26)
#!/usr/bin/env python ''' Leetcode: Flatten Binary Tree to Linked List Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal. ''' from __future__ import division import random from BinaryTree import Node, root ### In-order traversal without using recursion or stack, in place ### (Morris traversal) # 1. cur = root # 2. if cur has no left-child # 2.1 print cur.value # 2.2 cur --> cur.right # 3. else: # 3.1 cur --> the right most child of the left subtree # 3.2 cur --> cur.left def morris_traversal(root): cur = root while cur: if cur.left is not None: rightmost_in_left = cur.left while rightmost_in_left.right: rightmost_in_left = rightmost_in_left.right rightmost_in_left.right = cur cur_left = cur.left cur.left = None cur = cur_left else: # visit right child # no left child, it is the turn to visit the root! print cur.value, cur = cur.right # For each node: # 1. cur = root # 2. visit cur # 3. if cur has no left-child: # 3.1 cur = cur.right # 4. else: # 4.1 move cur's right-child to the rightmost child of its left subtree # 4.2 cur = cur.left def inplace_preorder_traversal(root): cur = root while cur: print cur.value, if cur.left: if cur.right: rightmost_in_left = cur.left while rightmost_in_left.right: rightmost_in_left = rightmost_in_left.right rightmost_in_left.right = cur.right cur.right = None cur = cur.left else: cur = cur.right def flatten(root): cur = root # pre-order in-place traversal while cur: #print cur.value, if cur.left: if cur.right: rightmost_in_left = cur.left while rightmost_in_left.right: rightmost_in_left = rightmost_in_left.right rightmost_in_left.right = cur.right cur.right = None cur = cur.left else: cur = cur.right print root # move all left child to be right child cur = root while cur: if cur.left: cur.right = cur.left cur.left = None cur = cur.right print root if __name__ == '__main__': print root flatten(root)
#!/usr/bin/env python ''' Leetcode: Word Search Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, Given board = [ ["ABCE"], ["SFCS"], ["ADEE"] ] word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false. ''' from __future__ import division import random # start from i,j def word_search_from_cell(M, word, i, j): if len(word) == 0: return True if i is not None and j is not None: cands = ((i+1,j), (i-1,j), (i,j+1), (i,j-1)) else: cands = ((x,y) for x in range(len(M)) for y in range(len(M[0]))) # (x,y) are adjacent cell to (i,j) for x,y in cands: if 0 <=x< len(M) and 0<=y<len(M[0]) and M[x][y] == word[0]: M[x][y] = '-' if word_search_from_cell(M, word[1:], x, y): return True M[x][y] = word[0] return False def word_search(M, word): M2 = [list(row[0]) for row in M] print M2 return word_search_from_cell(M2,word,None,None) if __name__ == '__main__': M = [ ["ABCE"], ["SFCS"], ["ADEE"] ] print word_search(M, "ABCCED") print word_search(M, "SEE") print word_search(M, "ABCB")
#!/usr/bin/env python from __future__ import division import random ''' Leetcode: Single Number Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? ''' def func(): pass ''' Leetcode: Single Number II Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? ''' def func(): pass if __name__ == '__main__': func()
from game import Game from layout import Layout choice = str(input("Do you want to play? (Y/N)")) player1 = Game.play(choice) print("You choosed {}".format(player1)) Layout.layout() print("") index = int(input("Enter position:")) Layout.index(index, player1) Layout.layout()
# coding: utf-8 import urllib2 import math # question 1 def lit_fichier(): # le principe est le m�me que pour le chargement d'un fichier # le programme lit directement les informations depuis Internet f = urllib2.urlopen( "http://www.xavierdupre.fr/enseignement" "/examen_python/restaurant_paris.txt" ) s = f.read() f.close() lines = s.split("\n") # on d�coupe en lignes # on d�coupe en colonnes lines = [_.strip("\n\r ").split("\t") for _ in lines if len(_) > 0] lines = [_ for _ in lines if len(_) == 3] # on supprime les lignes vides # on convertit les coordonn�es en r�el lines = [(a[3:], float(b), float(c)) for a, b, c in lines] return lines # question 2 def compte_restaurant(mat): # simple comptage, voir le chapitre 3... compte = {} for cp, x, y in mat: if cp not in compte: compte[cp] = 0 compte[cp] += 1 return compte # question 3 def barycentre(mat): # un barycentre est un point (X,Y) # o� X et Y sont respectivement la moyenne des X et des Y barycentre = {} # boucle sur la matrice for cp, x, y in mat: if cp not in barycentre: barycentre[cp] = [0, 0.0, 0.0] a, b, c = barycentre[cp] barycentre[cp] = [a + 1, b + x, c + y] # boucle sur les barycentres for cp in barycentre: a, b, c = barycentre[cp] barycentre[cp] = [b / a, c / a] # le co�t de cette fonction est en O (n log k) # o� k est le nombre de barycentre # de nombreux �l�ves ont deux boucles imbriqu�es, # d'abord sur la matrice, ensuite sur les barycentres # ce qui donne un co�t en O (nk), beaucoup plus grand return barycentre # question 4 def distance(x1, y1, x2, y2): return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 # question 5 def plus_proche_restaurant(x, y, arr, mat): m, mx, my = None, None, None for cp, a, b in mat: if cp != arr and (m is None or distance(a, b, x, y) < m): mx, my = a, b m = distance(a, b, x, y) return mx, my # question 6 def densite_approchee(mat): g = barycentre(mat) compte = compte_restaurant(mat) res = {} for cp in g: out = plus_proche_restaurant(g[cp][0], g[cp][1], cp, mat) r = distance(g[cp][0], g[cp][1], out[0], out[1]) aire = math.pi * r**2 res[cp] = compte[cp] / aire return res if __name__ == "__main__": if False: # mettre � vrai pour remplacer la fonction plus_proche_restaurant # ajout par rapport � l'�nonc� # en r�ponse � la derni�re question # plut�t que de prendre le premier point � hors de l'arrondissement # on consid�re celui correspondant � un quantile (5%) # ce qui �vite les quelques restaurants dont les donn�es # sont erron�es def plus_proche_restaurant_avec_amelioration(x, y, arr, mat): all = [] for cp, a, b in mat: if cp != arr: m = distance(a, b, x, y) all.append((m, a, b)) all.sort() a, b = all[len(all) / 20][1:] return a, b # ajout par rapport � l'�nonc� plus_proche_restaurant = plus_proche_restaurant_avec_amelioration mat = lit_fichier() com = densite_approchee(mat) ret = [(v, k) for k, v in com.iteritems()] ret.sort() for a, b in ret: print("%d\t%s" % (a, b)) # ajout par rapport � l'�nonc� # permet de dessiner les restaurants, une couleur par arrondissement # on observe que certains points sont aberrants, ce qui r�duit d'autant # l'estimation du rayon d'un arrondissement (il suffit qu'un restaurant # �tiquet�s dans le 15�me soit situ� pr�s du barycentre du 14�me.) import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) colors = [ "red", "blue", "yellow", "orange", "black", "green", "purple", "brown", "gray", "magenta", "cyan", "pink", "burlywood", "chartreuse", "#ee0055", ] for cp in barycentre(mat): lx = [m[1] for m in mat if m[0] == cp] ly = [m[2] for m in mat if m[0] == cp] c = colors[int(cp) % len(colors)] # if cp not in ["02", "20"] : continue ax.scatter(lx, ly, s=5.0, c=c, edgecolors="none") plt.show()
# coding: utf-8 from functools import reduce def recherche(li, c): """ Retourne l'index d'un élément ou -1 si non trouvé. :param li: liste :param c: élément à trouver :return: position .. exref:: :tag: Base :title: recherche avec index Lorsqu'on cherche un élément dans un tableau, on cherche plus souvent sa position que le fait que le tableau contient cet élément. .. runpython:: :showcode: def recherche (li, c) : for i,v in enumerate (li) : if v == c: return i return -1 li = [45, 32, 43, 56] print (recherche(li, 43)) # affiche 2 En python, il existe un fonction simple qui permet de faire ça : :: print(li.index(43)) # affiche 2 Lorsque l'élément n'y est pas, on retourne souvent la position ``-1`` qui ne peut être prise par aucun élément : :: if c in li: return li.index(c) else: return -1 Même si ce bout de code parcourt deux fois le tableau (une fois déterminer sa présence, une seconde fois pour sa position), ce code est souvent plus rapide que la première version et la probabilité d'y faire une erreur plus faible. """ if c in li: return li.index(c) else: return -1 def minindex(li): """ Retourne l'index du minimum et le minimum. :param li: liste :return: tuple (minimum, position) .. exref:: :tag: Base :title: minimum avec position La fonction `min <https://docs.python.org/3/library/functions.html#min>`_ retourne le minium d'un tableau mais pas sa position. Le premier réflexe est alors de recoder le parcours de la liste tout en conservant la position du minimum. .. runpython:: :showcode: li = [0, 434, 43, 6436, 5] m = 0 for i in range (0, len(li)): if li[m] < li[i]: m = i print(m) Mais il existe une astuce pour obtenir la position sans avoir à le reprogrammer. .. runpython:: :showcode: li = [0, 434, 43, 6436, 5] k = [(v,i) for i, v in enumerate(li)] m = min(k) print(m) La fonction ``min`` choisit l'élément minimum d'un tableau dont les éléments sont des couples (élément du premier tableau, sa position). Le minimum est choisi en comparant les éléments, et la position départegera les exaequo. """ return min((v, i) for i, v in enumerate(li)) def recherche_dichotomique(li, c): """ Effectue une recherche dichotomique. :param li: tableau :param c: élément à chercher :return: position .. exref:: :tag: Base :title: recherche dichotomique La `recherche dichotomique <http://fr.wikipedia.org/wiki/Dichotomie>`_ est plus rapide qu'une recherche classique mais elle suppose que celle-ci s'effectue dans un ensemble trié. L'idée est de couper en deux l'intervalle de recherche à chaque itération. Comme l'ensemble est trié, en comparant l'élément cherché à l'élément central, on peut éliminer une partie de l'ensemble : la moitié inférieure ou supérieure. .. runpython:: :showcode: def recherche_dichotomique(li, c) : a, b = 0, len (li)-1 while a <= b : m = (a + b)//2 if c == li[m]: return m elif c < li[m]: b = m-1 else : a = m+1 return -1 print(recherche_dichotomique([0, 2, 5, 7, 8], 7)) """ a, b = 0, len(li) - 1 while a <= b: m = (a + b) // 2 if c == li[m]: return m elif c < li[m]: b = m - 1 # partie supérieure éliminée else: a = m + 1 # partie inférieure éliminée return -1 # élément non trouvé def text2mat(s, sep_row="\n", sep_col="\t"): """ Convertit une chaîne de caractères en une matrice ( = liste de listes), réciproque de la fonction @see fn mat2text. :param s: texte à convertir :param sep_row: séparation de ligne :param sep_col: séparateur de colonnes :return: liste de liste .. exref:: :tag: Base :title: conversion d'une chaîne de caractère en matrice Les quelques lignes qui suivent permettent de décomposer une chaîne de caractères en matrice. Chaque ligne et chaque colonne sont séparées par des séparateurs différents. Ce procédé intervient souvent lorsqu'on récupère des informations depuis un fichier texte lui-même provenant d'un tableur. .. runpython:: :showcode: s = "case11;case12;case13|case21;case22;case23" # décomposition en matrice ligne = s.split ("|") # lignes mat = [ l.split (";") for l in ligne ] # colonnes print(mat) Comme cette opération est très fréquente lorsqu'on travaille avec les données, on ne l'implémente plus soi-même. On préfère utiliser un module comme `pandas <http://pandas.pydata.org/>`_ qui est plus robuste et considère plus de cas. Pour écrire, utilise la méthode `to_csv <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html>`_, pour lire, la fonction `read_csv <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html>`_. On peut également directement enregistrer au format Excel `read_excel <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.excel.read_excel.html>`_ et écrire dans ce même format `to_excel <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html>`_. """ ligne = s.split(sep_row) # lignes mat = [el.split(sep_col) for el in ligne] # colonnes return mat def mat2text(mat, sep_row="\n", sep_col="\t"): """ Convertit une matrice en une chaîne de caractères, réciproque de la fonction @see fn text2mat. :param mat: matrice à convertir (liste de listes) :param sep_row: séparation de ligne :param sep_col: séparateur de colonnes :return: liste de liste .. exref:: :tag: Base :title: conversion d'une matrice en chaîne de caractères .. runpython:: :showcode: mat = [['case11', 'case12', 'case13'], ['case21', 'case22', 'case23']] ligne = [ ";".join (l) for l in mat ] # colonnes s = "|".join (ligne) # lignes print(s) """ ligne = [";".join(li) for li in mat] # colonnes s = "|".join(ligne) # lignes return s def somme(li): """ Calcule la somme des éléments d'un tableau. :param li: tableau :return: somme .. exref:: :tag: Base :title: calcul d'une somme Le calcul d'une somme fait toujours intervenir une boucle car le langage :epkg:`Python` ne peut faire des additions qu'avec deux nombres. Le schéma est toujours le même : initialisation et boucle. .. runpython:: :showcode: li = [0, 434, 43, 6456] s = 0 # initialisation for l in li : # boucle s += l # addition print(s) Ce code est équivalent à la fonction `sum <https://docs.python.org/3/library/functions.html#sum>`_. Dans ce cas où la somme intègre le résultat d'une fonction (au sens mathématique) et non les éléments d'une liste, il faudrait écrire : .. runpython:: :showcode: def fonction(x): return x li = [0, 434, 43, 6456] s = 0 for l in li: s += fonction (l) print(s) Et ces deux lignes pourraient être résumées en une seule grâce à l'une de ces instructions : .. runpython:: :showcode: def fonction(x): return x li = [0, 434, 43, 6456] s1 = sum([fonction(l) for l in li]) s2 = sum(fonction(l) for l in li) s3 = sum(map(fonction, li)) print(s1, s2, s3) L'avantage des deux dernières instructions est qu'elles évitent la création d'une liste intermédiaire, c'est un point à prendre en compte si la liste sur laquelle opère la somme est volumineuse. """ return sum(li) def triindex(li): """ Trie une liste, retourne la liste triée et les positions initiales. :param li: tableau :return: liste triée .. exref:: :tag: Base :title: tri, garder les positions initiales Le tri est une opération fréquente. On n'a pas toujours le temps de programmer le tri le plus efficace comme un tri `quicksort <http://fr.wikipedia.org/wiki/Tri_rapide>`_ et un tri plus simple suffit la plupart du temps. Le tri suivant consiste à recherche le plus petit élément puis à échanger sa place avec le premier élément du tableau du tableau. On recommence la même procédure à partir de la seconde position, puis la troisième et ainsi de suite jusqu'à la fin du tableau. .. runpython:: :showcode: li = [5, 6, 4, 3, 8, 2] for i in range (0, len (li)) : # recherche du minimum entre i et len (li) exclu pos = i for j in range (i+1, len (li)) : if li [j] < li [pos] : pos = j # échange ech = li [pos] li [pos] = li [i] li [i] = ech print(li) La fonction `sorted <https://docs.python.org/3/library/functions.html#sorted>`_ trie également une liste mais selon un algorithme plus efficace que celui-ci (voir `Timsort <http://en.wikipedia.org/wiki/Timsort>`_). On est parfois amené à reprogrammer un tri parce qu'on veut conserver la position des éléments dans le tableau non trié. Cela arrive quand on souhaite trier un tableau et appliquer la même transformation à un second tableau. Il est toujours préférable de ne pas reprogrammer un tri (moins d'erreur). Il suffit d'applicer la même idée que pour la fonction @see fn minindex. .. runpython:: :showcode: tab = ["zero", "un", "deux"] # tableau à trier pos = sorted( (t,i) for i,t in enumerate(tab) ) # tableau de couples print (pos) # affiche [('deux', 2), ('un', 1), ('zero', 0)] Si cette écriture est trop succincte, on peut la décomposer en : .. runpython:: :showcode: tab = ["zero", "un", "deux"] tab_position = [(t,i) for i,t in enumerate(tab)] tab_position.sort() print(tab_position) """ return sorted((t, i) for i, t in enumerate(li)) def compte(li): """ Compte le nombre d'occurrences de chaque élément d'une liste. :param li: tableau :return: dictionnaire .. exref:: :tag: Base :title: comptage :label: l-ex-comptage On souhaite ici compter le nombre d'occurrences de chaque élément d'un tableau. Par exemple, on pourrait connaître par ce moyen la popularité d'un mot dans un discours politique ou l'étendue du vocabulaire utilisé. L'exemple suivant compte les mots d'une liste de mots. .. runpython:: :showcode: li = ["un", "deux", "un", "trois"] d = { } for l in li: if l not in d: d[l] = 1 else: d[l] += 1 print(d) # affiche {'un': 2, 'trois': 1, 'deux': 1} La structure la plus appropriée ici est un dictionnaire puisqu'on cherche à associer une valeur à un élément d'une liste qui peut être de tout type. Si la liste contient des éléments de type modifiable comme une liste, il faudrait convertir ceux-ci en un type immuable comme une chaîne de caractères. L'exemple suivant illustre ce cas en comptant les occurrences des lignes d'une matrice. .. runpython:: :showcode: mat = [ [1,1,1], [2,2,2], [1,1,1]] d = {} for l in mat: k = str(l) # k = tuple (l) lorsque cela est possible if k not in d: d[k] = 1 else: d[k] += 1 print(d) # affiche {'[1, 1, 1]': 2, '[2, 2, 2]': 1} Les listes ne peuvent pas être les clés du dictionnaire : `Why Lists Can't Be Dictionary Keys <https://wiki.python.org/moin/DictionaryKeys>`_. On peut également vouloir non pas compter le nombre d'occurrence mais mémoriser les positions des éléments tous identiques. On doit utiliser un dictionnaire de listes : .. runpython:: :showcode: li = ["un", "deux", "un", "trois"] d = { } for i, v in enumerate(li): if v not in d: d[v] = [i] else: d[v].append(i) print(d) # affiche {'un': [0, 2], 'trois': [3], 'deux': [1]} S'il suffit juste de compter, l'écriture la plus simple est : .. runpython:: :showcode: r = {} li = ["un", "deux", "un", "trois"] for x in li: r[x] = r.get(x,0) + 1 print(r) """ r = {} for x in li: r[x] = r.get(x, 0) + 1 return r def mat2vect(mat): """ Convertit une matrice en un tableau à une seule dimension, réciproque de la fonction @see fn vect2mat. :param mat: matrice :return: liste .. exref:: :tag: Base :title: conversion d'une matrice en un vecteur Dans un langage comme le *C++*, il arrive fréquemment qu'une matrice ne soit pas représentée par une liste de listes mais par une seule liste car cette représentation est plus efficace. Il faut donc convertir un indice en deux indices ligne et colonne. Il faut bien sûr que le nombre de colonnes sur chaque ligne soit constant. Le premier programme convertit une liste de listes en une seule liste. .. runpython:: :showcode: mat = [[0,1,2],[3,4,5]] lin = [ i * len (mat [i]) + j \\ for i in range (0, len (mat)) \\ for j in range (0, len (mat [i])) ] print(lin) Vous pouvez aussi utiliser des fonctions telles que `reduce <https://docs.python.org/3/library/functools.html?highlight=reduce#module-functools>`_. .. runpython:: :showcode: from functools import reduce mat = [[0,1,2], [3,4,5]] lin = reduce(lambda x,y: x+y, mat) print(lin) """ return reduce(lambda x, y: x + y, mat) def vect2mat(vect, ncol): """ Convertit un tableau à une dimension en une matrice, réciproque de la fonction @see fn mat2vect. :param vect: vecteur :param ncol: nombre de colonnes :return: matrice .. exref:: :tag: Base :title: conversion d'un vecteur en une matrice Dans un langage comme le *C++*, il arrive fréquemment qu'une matrice ne soit pas représentée par une liste de listes mais par une seule liste car cette représentation est plus efficace. Il faut donc convertir un indice en deux indices ligne et colonne. Il faut bien sûr que le nombre de colonnes sur chaque ligne soit constant. Le premier programme convertit une liste de listes en une seule liste. .. runpython:: :showcode: ncol = 2 vect = [0, 1, 2, 3, 4, 5] mat = [vect[i*ncol: (i+1)*ncol] for i in range(0,len(vect)//ncol)] print(mat) """ return [vect[i * ncol : (i + 1) * ncol] for i in range(0, len(vect) // ncol)] def integrale(fonction, a, b, n): """ Calcule l'intégrale d'une fonction avec la `méthode de Rienmann <https://fr.wikipedia.org/wiki/Somme_de_Riemann>`_. :param fonction: fonction :param a: borne inférieure de l'intervalle :param b: borne supérieure de l'intervalle :param n: nombre de division de l'intervalle :return: valeur .. exref:: :tag: Base :title: fonction comme paramètre :label: paragraphe_fonction_variable Une fonction peut aussi recevoir en paramètre une autre fonction. L'exemple suivant inclut la fonction ``calcul_n_valeur`` qui prend comme paramètres ``l`` et ``f``. Cette fonction calcule pour toutes les valeurs ``x`` de la liste ``l`` la valeur ``f(x)``. ``fonction_carre`` ou ``fonction_cube`` sont passées en paramètres à la fonction ``calcul_n_valeur`` qui les exécute. .. runpython:: :showcode: def fonction_carre(x): return x*x def fonction_cube(x): return x*x*x def calcul_n_valeur(l,f): res = [f(i) for i in l] return res l = [0,1,2,3] print(l) # affiche [0, 1, 2, 3] l1 = calcul_n_valeur(l, fonction_carre) print(l1) # affiche [0, 1, 4, 9] l2 = calcul_n_valeur(l, fonction_cube) print(l2) # affiche [0, 1, 8, 27] """ h = (b - a) / n return sum(fonction(a + h / 2 + h * i) for i in range(0, n)) * h def construit_matrice_carree(n): """ Cette fonction construit une matrice carrée remplie de zéro sous la forme d'une liste de listes. :param n: dimension de la matrice carrée """ return [[0 for i in range(n)] for j in range(n)] def enumerate_permutations_recursive(ensemble): """ Enumère les permutations d'un ensemble de façon récursive. :param ensemble: ensemble à permuter :return: itérateur sur les permutations """ if len(ensemble) == 1: yield ensemble else: for i in range(0, len(ensemble)): # pylint: disable=C0200 ensemble[0], ensemble[i] = ensemble[i], ensemble[0] per = enumerate_permutations_recursive(ensemble[1:]) for p in per: yield [ensemble[0]] + p ensemble[0], ensemble[i] = ensemble[i], ensemble[0] def enumerate_permutations(ensemble): """ Enumère les permutations d'un ensemble de façon non récursive. :param ensemble: ensemble à permuter :return: itérateur sur les permutations """ if len(ensemble) == 1: yield ensemble else: position = list(range(len(ensemble))) while position[0] < len(ensemble): memo = [] for i, p in enumerate(position): ensemble[i], ensemble[p] = ensemble[p], ensemble[i] memo.append((i, p)) yield ensemble.copy() for i, p in reversed(memo): ensemble[i], ensemble[p] = ensemble[p], ensemble[i] last = len(position) - 1 position[last] += 1 while last > 0 and position[last] >= len(position): position[last - 1] += 1 position[last] = last last -= 1
# coding: utf-8 # �nonc� 1, exercice 1, recherche dichotomique # question 1 def recherche_dichotomique(element, liste_triee): """ premier code: http://www.xavierdupre.fr/blog/2013-12-01_nojs.html """ a = 0 b = len(liste_triee) - 1 m = (a + b) // 2 while a < b: if liste_triee[m] == element: return m elif liste_triee[m] > element: b = m - 1 else: a = m + 1 m = (a + b) // 2 return a li = [0, 2, 4, 6, 8, 100, 1000] print(recherche_dichotomique(100, li)) # affiche 5 # question 2 def deux_recherches(element, liste_impair, liste_pair): if element % 2 == 0: return recherche_dichotomique(element, liste_pair), -1 else: return -1, recherche_dichotomique(element, liste_impair) lp = [0, 2, 4, 6, 8, 100, 1000] li = [1, 3, 5] print(deux_recherches(100, li, lp)) # affiche (5, -1) # question 3 """ liste coup�e liste non coup�e (2n) recherche simple 1 + n 2n recherche dichotomique 1 + ln n ln(2n) = 1 + ln(n) co�t �quivalent """ # question 4 def recherche_dichotomique(element, liste_triee): a = 0 b = len(liste_triee) - 1 m = (a + b) // 2 while a < b: if liste_triee[m] == element: return m elif liste_triee[m] > element: b = m - 1 else: a = m + 1 m = (a + b) // 2 if liste_triee[a] != element: return -1 # ligne ajout�e else: return m # ligne ajout�e li = [0, 2, 4, 6, 8, 100, 1000] for i in li: print(i, recherche_dichotomique(i, li)) # v�rifier qu'on retrouve tous les �l�ments existant print(recherche_dichotomique(1, li)) # affiche -1 # question 5 def deux_recherches(element, liste_impair, liste_pair): i = recherche_dichotomique(element, liste_impair) if i == -1: return recherche_dichotomique(element, liste_pair) else: return i # question 6 """ Les logarithmes sont en base 2. co�t fonction question 2 : 1001 ( 1 + ln(n) ) = C1 co�t fonction question 5 : 1000 ln(n) + 2 ln(n) = C2 C2 - C1 = ln(n) - 1001 > 0 La fonction 5 est plus rapide dans ce cas. """
import os import zipfile from typing import List from urllib.request import urlopen def decompress_zip(filename, dest: str, verbose: bool = False) -> List[str]: """ Unzips a zip file. :param filename: file to process :param dest: destination :param verbose: verbosity :return: return the list of decompressed files """ try: fp = zipfile.ZipFile(filename, "r") except zipfile.BadZipFile as e: # pragma: no cover raise RuntimeError(f"Unable to unzip {filename!r}") from e files = [] for info in fp.infolist(): if not os.path.exists(info.filename): data = fp.read(info.filename) tos = os.path.join(dest, info.filename) if not os.path.exists(tos): finalfolder = os.path.split(tos)[0] if not os.path.exists(finalfolder): if verbose: print(f"creating folder {finalfolder!r}") os.makedirs(finalfolder) if not info.filename.endswith("/"): with open(tos, "wb") as u: u.write(data) files.append(tos) if verbose: print(f"unzipped {info.filename!r} to {tos!r}") elif not tos.endswith("/"): files.append(tos) elif not info.filename.endswith("/"): files.append(info.filename) return files def download_and_unzip( url: str, dest: str = ".", timeout: int = 10, verbose: bool = False ) -> List[str]: """ Downloads a file and unzip it. :param url: url :param dest: destination folder :param timeout: timeout :param verbose: display progress :return: list of unzipped files """ filename = url.split("/")[-1] dest_zip = os.path.join(dest, filename) if not os.path.exists(dest_zip): if verbose: print(f"downloads into {dest_zip!r} from {url!r}") with urlopen(url, timeout=timeout) as u: content = u.read() with open(dest_zip, "wb") as f: f.write(content) elif verbose: print(f"already downloaded {dest_zip!r}") return decompress_zip(dest_zip, dest, verbose=verbose)
import math import unittest class TestFunctions(unittest.TestCase): # 1st Task def calculateMpg(miles_int, gallons_int): return miles_int / gallons_int miles_string = input("Enter the amount of miles you went.") gallons_string = input("Enter the number of gallons you consumed.") miles_int= int(miles_string) gallons_int= int(gallons_string) Mpg = calculatingMpg(miles_int , gallons_int) # "The above program will calculate the Mpg of a car. #2nd Task from math import pi def calculateAreaofCircle(radius_int): return pi*math.pow(radius_int, 2) radius_string = input("Please enter the value of radius.") radius_int = int(radius_string) AoC= calculateAreaofCircle(radius_int) #The above program will calculate the area of a Circle. # 3rd Task def convertFahrenheitToCelcius(fahrenheit_int): return (fahrenheit_int - 32) / 1.8 fahrenheit_string = input("Please enter the value of Fahrenheit.") fahrenheit_int = int(fahrenheit_string) cFTC=convertFahrenheitToCelcius() #The above prograam will convert Fahrenheit to Celcius. #4th task def calculateDistanceBetweenPoints(x, y, x1, y1) return math.sqrt(((x1-x)*(x1-x)) + ((y1-y)*(y1-y)) ) x_string= input("Please enter the x value.") y_string= input("Please enter the y value.") x1_string= input("Please enter the x1 value.") y1_string= input("Please enter the y1 value.") x=int(x_string) y=int(y_string) x1=int(x1_string) y1=int(y1_string) cDBP= calculateDistanceBetweenPoints() #The above function will calculate the distance between two points using Phytagoras formulate. print("If a car went {0} miles by using {1} amount of " "gas. The car can go {2} miles per gallon.".format(miles_int , gallons_int, Mpg)) print("Area of a circle with the radius {0}, is {1}.".format(radius_int, AoC)) print("{0} fahrenheits is equal to {1} celcius.".format(fahrenheit_int, cFTC)) print("The amount of distance between the points ({0},{1}) and ({2}, {3}), is {4}.".format(x,y,x1,y1,cDBP)) #The testing is done below. unittest.calculateMpg() unittest.calculateAreaofCircle() unittest.convertFahrenheitToCelcius() unittest.calculateDistanceBetweenPoints()
import time # dict mit sprechenden Stundenbezeichnungen STUNDEN = { 0: "zwölf", 1: "eins", 2: "zwei", 3: "drei", 4: "vier", 5: "fünf", 6: "sechs", 7: "sieben", 8: "acht", 9: "neun", 10: "zehn", 11: "elf", 12: "zwölf", 13: "eins", 14: "zwei", 15: "drei", 16: "vier", 17: "fünf", 18: "sechs", 19: "sieben", 20: "acht", 21: "neun", 22: "zehn", 23: "elf", 24: "zwölf" } # Zeit in Sekunden zwischen den Aktualisierungen ZEIT_AKTUALISIERUNG = 1 def hole_zeit(): """ Funktion hole_zeit holt die lokale Systemzeit EINGABE --- AUSGABE (int) zeit.tm_hour: Stunde (int) zeit.tm_min: Minute """ zeit = time.localtime() return zeit.tm_hour, zeit.tm_min def zeit_zu_text(std, min): """ Funktion zeit_zu_text wandelt die Zahlenwerte für Stunde und Minute in einen sprechenden Text um. EINGABE (int) std: Stunde (int) min: Minute AUSGABE (str) uhrzeit_text: Uhrzeit in sprechender Form """ # Zahlenbereich prüfen if not 0 <= std < 24: raise ValueError(f"ungültiger Stundenwert: {std}") if not 0 <= min < 60: raise ValueError(f"ungültiger Minutenwert: {min}") # Stundentexte festlegen if min < 25: std_text = STUNDEN[std] else: std_text = STUNDEN[std + 1] if min < 2: vor_nach_text = "" if std == 1: # s am Ende abschneiden --> "ein Uhr" statt "eins Uhr" std_text = std_text[0:-1] std_text += " Uhr" # Minutentexte festlegen elif min < 5: vor_nach_text = "kurz nach" elif min < 10: vor_nach_text = "fünf nach" elif min < 15: vor_nach_text = "zehn nach" elif min < 20: vor_nach_text = "viertel nach" elif min < 25: vor_nach_text = "zwanzig nach" elif min < 27: vor_nach_text = "fünf vor halb" elif min < 30: vor_nach_text = "kurz vor halb" elif min < 32: vor_nach_text = "halb" elif min < 35: vor_nach_text = "kurz nach" elif min < 40: vor_nach_text = "fünf nach halb" elif min < 45: vor_nach_text = "zwanzig vor" elif min < 50: vor_nach_text = "viertel vor" elif min < 55: vor_nach_text = "zehn vor" elif min < 58: vor_nach_text = "fünf vor" elif min >= 58: vor_nach_text = "kurz vor" # String für Textausgabe zusammensetzen uhrzeit_text = f"Es ist {vor_nach_text} {std_text}.".replace(" ", " ") return uhrzeit_text letzte_ausgabe = "" while True: std, min = hole_zeit() ausgabe = zeit_zu_text(std, min) # nur bei Änderungen ausgeben if not letzte_ausgabe == ausgabe: letzte_ausgabe = ausgabe print(ausgabe) # warten time.sleep(ZEIT_AKTUALISIERUNG) # TODO: Taste zum Beenden definieren # TODO: Terminal leeren vor Aktualisierung
dict = {} # empty dictionary dict[0] = 0 dict[1] = 3 dict[2] = 3 dict[3] = 5 dict[4] = 4 dict[5] = 4 dict[6] = 3 dict[7] = 5 dict[8] = 5 dict[9] = 4 dict[10] = 3 dict[11] = 6 dict[12] = 6 dict[13] = 8 dict[14] = 8 dict[15] = 7 dict[16] = 7 dict[17] = 9 dict[18] = 8 dict[19] = 8 dict[20] = 6 dict[30] = 6 dict[40] = 5 dict[50] = 5 dict[60] = 5 dict[70] = 7 dict[80] = 6 dict[90] = 6 dict[100] = 7 dict[1000] = 11 words = {} # empty dictionary of words words[0] = 0 words[1] = 'One' words[2] = 'Two' words[3] = 'Three' words[4] = 'Four' words[5] = 'Five' words[6] = 'Six' words[7] = 'Seven' words[8] = 'Eight' words[9] = 'Nine' words[10] = 'Ten' words[11] = 'Eleven' words[12] = 'Twelve' words[13] = 'Thirteen' words[14] = 'Fourteen' words[15] = 'Fifteen' words[16] = 'Sixteen' words[17] = 'Seventeen' words[18] = 'Eighteen' words[19] = 'Nineteen' words[20] = 'Twenty' words[30] = 'Thirty' words[40] = 'Fourty' words[50] = 'Fifty' words[60] = 'Sixtey' words[70] = 'Seventy' words[80] = 'Eighty' words[90] = 'Ninety' words[100] = 'Hundred' words[1000] = 'Thousand' sum = 0 # sumation for single digit numbers for i in range(1, 11): sum += dict[i] print (words[i], '', 'Sum=', sum) # summation for numbers less than 20 for i in range(11, 21): sum += dict[i] print (words[i], '', 'Sum=', sum) # for sumation upto hundred terms for i in range(21, 100): j = i sum += dict[j - j % 10] sum += dict[j % 10] print (words[j - j % 10], words[j % 10], '', 'Sum=', sum) sum += dict[1] + dict[100] print (words[100], '', 'Sum=', sum) # for numbers from 101 to 999 for i in range(101, 1000): # print("sum = "+str(sum)+" i = "+str(i)) sum += dict[int(i / 100)] + dict[100] try: if dict[i % 100] == 0: print ( words[int(i / 100)], ' ', words[100], '', 'Sum=', sum, ) pass else: sum += len('and') sum += dict[i % 100] print ( words[int(i / 100)], ' ', words[100], 'and', ' ', words[i % 100], '', 'Sum=', sum, ) except Exception: # print("Teen Number Detected in 100s ") # print(dict[i%100]) sum += len('and') sum += dict[i % 100 - i % 10] + dict[i % 10] print ( words[int(i / 100)], ' ', words[100], 'and', str(words[i % 100 - i % 10]), ' ', str(words[i % 10]), '', 'Sum=', sum, ) pass sum += dict[1000] print (words[1000], '', 'Sum=', sum) print 'Total = %d' % sum input('That was Awesome :)')
#!/usr/bin/env python3 ################################### # WHAT IS IN THIS EXAMPLE? # # This example shows using the bot framework to build non-bot functionality. # Here, the currently logged in user will send a message to the channel and # then loop through rotating the message by moving the first character to # the end, and editing the original message with the rotated message. This # creates a scrolling or marquee effect. ################################### import asyncio import logging import sys import pykeybasebot.types.chat1 as chat1 from pykeybasebot import Bot logging.basicConfig(level=logging.DEBUG) if "win32" in sys.platform: # Windows specific event-loop policy asyncio.set_event_loop_policy( asyncio.WindowsProactorEventLoopPolicy() # type: ignore ) def rotate(message): """ Returns a string with the first character of 'message' moved to the end """ return f"{message[1:]}{message[0]}" async def scrolling_message(message, before="", after=""): channel = chat1.ChatChannel( name="yourcompany.marketing", topic_name="lunchtalk", members_type="team" ) def noop_handler(*args, **kwargs): pass bot = Bot( # you don't need to pass in a username or paperkey if you're already logged in handler=noop_handler ) result = await bot.chat.send(channel, f"{before}{message}{after}") msg_id = result.message_id while True: message = rotate(message) await bot.chat.edit(channel, msg_id, f"{before}{message}{after}") await asyncio.sleep(0.5) asyncio.run( scrolling_message("There's pizza in the break room!", before="--[ `", after="` ]--") )
class Clock(object): def __init__(self,hours=0,minutes=0,seconds=0): self.__hours = hours self.__minutes = minutes self.__seconds = seconds def set(self,hours,minues,seconds=0): self.__hours = hours self.__minutes = minutes self.__seconds = seconds def tick(self): """ Time will be advanced by one second """ if self.__seconds == 59 : self.__seconds = 0 if (self.__minutes == 59) : self.__minutes = 0 self.__hours == 0 if self.__hours == 23 else self.__hours + 1 else: self.__minutes += 1 else: self.__seconds += 1 def display(self): print ("%d:%d:%d" % (self.__hours,self.__minutes,self.__seconds)) def __str__(self): return "%2d:%2d:%2d" %(self.__hours,self.__minutes,self.__seconds)
from Logica import Logica print ("""Ingrese la figura de la cual va a calcular su volumen: 1) Esfera 2) Cilindro 3) Cono de con formula 4) Cono mediante cálculo con cilindros 5) Cubo""") opc = int(input()) log = Logica(opc) print ("El volumen es "+str(log.mostrar_volumen())+" u^3")
from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label class TextBlock(BoxLayout): def __init__(self,container, **kwargs): super(TextBlock, self).__init__(**kwargs) self.width = container.width self.height = container.height self.size_hint_max_y = 200 self.orientation = 'vertical' self.text_welcome = "Welcome to Pyttleships !" self.text_first_stage = "Place all of your ships on the board to the left.\nThis board will keep track of enemy shots and your remaining ships.\nAfter you place all your ships click on board to the right to take shot." self.text_second_stage = "After you finish placing your ships, enemy will do the same." self.text_third_stage = "Now, that enemy has placed his ships, its time to take turns at shots to see who will sink all the enemy ships.\nClick on the left board to take a shot." self.text_instructions = "Left click - take a shot/place ship\nZ - rotate ship during placement\n" self.text_stage = self.text_first_stage self.placeLabels() def placeLabels(self): label_welcome = Label(font_size=20, halign='center', text=self.text_welcome, pos_hint = {'top':1.0}) label_stage = Label(font_size=15, halign='center', text=self.text_stage) label_instruction = Label(font_size=15, halign='left', text=self.text_instructions) self.add_widget(label_welcome) self.add_widget(label_stage) self.add_widget(label_instruction)
dict1 = dict() def staircase(n): if n in dict1: return dict1[n] if n == 1: return 1 elif n == 2: return 2 elif n == 3: return 4 else: a = staircase(n-1) dict1[n-1] = a b = staircase(n-2) dict1[n-2] = b c = staircase(n-3) dict1[n-3] = c return a + b + c pass
T = int(input()) for _ in range(T): n = int(input()) str1 = input() if(str1 == "".join(reversed(str1))): print("Yes") else: print("No")
a = input("Enter the string:\t") list1 = [] for i in a.split(" "): list1.append("".join(reversed(i))) print(" ".join(list1))
# This is simply to learn about the MD5 Hash """ MD5 is hash function accepts sequence of bytes and returns 128 bit hash value, usually used to check data integrity but has a lot of security issues. This basically has 3 functions. 1. Encode(): converts the string into bytes to be acceptable by the hash function. 2. digest(): This returns the encoded data in byte format 3. hexdigest(): This returns the encoded data in hexadecimal format """ import hashlib #Now, we will take the string that is to be encodes. str = input() #We will byte encode the string entered using encode, so that it can be hashed. str = str.encode() #Now, we will pass on the encoded data to the hashlib function so that it can be converted. result = hashlib.md5(str) #To get the equivalent hexadecimal value, we get. print("The hexadecimal equivalent of hash is:\t ",result.hexdigest()) print("The decimal equivalent of the hash:\t",result.digest())
class TrieNode(object): #Trie Node class. def __init__(self,char=None): #This represents all the nodes of the trieNode. self.children = [None]*26 #isEndOfWord is true if node represents end of the word, self.character = char self.isEndOfWord = False class Trie(object): def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self,ch): return ord(ch)-ord('a') def insert(self,key): ''' 1. While adding a key to the trie, two cases might arise. i) The new key added to the trie is not a part of the trie ii) The new key added to the trie is already a part of the prefix node. ''' builderNode = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) #If character is not already present. if not builderNode.children[index]: builderNode.children[index] = self.getNode() builderNode = builderNode.children[index] builderNode.isEndOfWord = True def search(self,key): #Our task here is to check if the key is present in the trie. length = len(key) builderNode = self.root for level in range(length): index = self._charToIndex(key[level]) if not builderNode.children[index]: return False builderNode = builderNode.children[index] return builderNode.isEndOfWord #Helper function to tell if the rooot has no children. def isEmpty(self,trieNode): for i in trieNode.children: if i is not None: return False return True def remove(self,trieNode,key,depth=0): if(trieNode is None): return None if(depth == len(key)): if(trieNode.isEndOfWord): trieNode.isEmpty = False if(self.isEmpty(trieNode)): trieNode = None return trieNode index = ord(key[depth]) - ord('a') trieNode.children[index] = self.remove(trieNode.children[index],key,depth+1) if(self.isEmpty(trieNode) and trieNode.isEndOfWord == False): trieNode = None return trieNode def main(): trie = Trie() keys = ['raghav','geeks','radhika','rahul','gambling','geeky','ra'] for key in keys: trie.insert(key) print("Present in trie {}".format(trie.search("raghav"))) print("Present in trie {}".format(trie.search("rahulai"))) print("Present in trie {}".format(trie.search("rahul"))) print("Present in trie {}".format(trie.search("radhika"))) trie.remove(trie.root,"radhika") trie.remove(trie.root,"rahul") print("Present in trie {}".format(trie.search("radhika"))) print("Present in trie {}".format(trie.search("rahul"))) if __name__ == "__main__": main()
import sys from collections import defaultdict def printSolution(shortest_distance,start): ans = sorted(shortest_distance.items()) for i in ans: if i[0] == start: continue elif i[1] >= 100000000000: print(-1,end=" ") else: print(i[1],end=" ") print() def dijkstras(graph,start,nodes): shortest_distance = {} unseenNode = graph for i in range(1,nodes+1): shortest_distance[i] = sys.maxsize shortest_distance[start] = 0 # print(shortest_distance) while unseenNode: minNode = None for i in unseenNode: # print(i,shortest_distance) if minNode is None: minNode = i elif(shortest_distance[i] < shortest_distance[minNode]): minNode = i for node,distance in unseenNode[minNode].items(): for dis in distance: if shortest_distance[minNode]+dis < shortest_distance[node]: shortest_distance[node] = shortest_distance[minNode]+dis unseenNode.pop(minNode) printSolution(shortest_distance,start) pass t = int(input()) for _ in range(0,t): nodes,edges = map(int,input().split()) graph = defaultdict(dict) for i in range(0,edges): start,end,weight = map(int,input().split()) try: graph[start][end].append(weight) graph[end][start].append(weight) except: graph[start][end] = [weight] graph[end][start] = [weight] # print(graph) start = int(input()) dijkstras(graph,start,nodes) #In this we cater to multiple roads within a city aas well!
def deep_reverse(arr,res): ''' Base case: Here, as soon as the list is over, we return, ''' if(len(arr) == 0): return else: ''' 1. We take the element from the end of the list i). If it is a list, we recursively call the same function on this element(list) and then append to the result array. ii) If not a list, all we have to do is append the current element and call recursion on the remaining list. 2. After this, we just have to return the result. ''' temp = arr[len(arr)-1] #If the element is of type list, do this. if(type(temp) is list): res1 = [] deep_reverse(temp,res1) res.append(res1) #else, just append to the res array. else: res.append(temp) #Now, we call recursion again. deep_reverse(arr[0:len(arr)-1],res) return res #Test on these. print(deep_reverse([1,2,3,4,5],[])) print(deep_reverse([1, [2, 3, [4, [5, 6]]]],[])) #Ouput [5,4,3,2,1] [[[[6, 5], 4], 3, 2], 1]
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root We will simply use the Binary search algorithm to find the square root, and we will be done in O(log(n)) """ if number < 0: return "Square root of negative numbers is not possible" low = 0.0 high = float(number+1) while((high-low) > 0.000001): mid = (high+low)/2 if mid*mid < number: low = mid else: high = mid return int(high) #Test case 1 n = 16 print("Square root of {} is: {}".format(n,sqrt(n))) #Test case 2 n = 27 print("Square root of {} is: {}".format(n,sqrt(n))) #Test case 3(EDGE CASE) n = 0 print("Square root of {} is: {}".format(n,sqrt(n))) #Test case 4 (Edge case) n = -25 print("Square root of {} is: {}".format(n,sqrt(n))) #Outputs for the above Test cases. # Square root of 16 is: 4 # Square root of 27 is: 5 # Square root of 0 is: 0
str1 = input("Enter the string:\t") #In-place means that you should update the original string rather than creating a new one n = len(str1) str1 = list(str1) for i in range(n//2): temp = str1[i] str1[i] = str1[n-i-1] str1[n-i-1] = temp print("".join(str1))
import sys def get_min_max(ints): if (len(ints) == 0): print("Array is empty!") return -1 maximum = -sys.maxsize minimum = sys.maxsize for i in ints: if i > maximum: maximum = i if i < minimum: minimum = i print("Maximum minimum pair is: ",(minimum,maximum)) return (minimum,maximum) ## Example Test Case of Ten Integers import random #Test case 1 l = [i for i in range(0, 10)] # a list containing 0 - 9 random.shuffle(l) print ("Pass" if ((0, 9) == get_min_max(l)) else "Fail") #Test case 2 (Edge case) l = [1,1,1,1,1,1,1,1,1,1,1,1,] print ("Pass" if ((1,1) == get_min_max(l)) else "Fail") #Test case 3 (Empty array)(Edge) l = [] print ("Pass" if (-1 == get_min_max(l)) else "Fail") #Test case 4 l = [2,5,1,4,8,9,56,76,43,56,7,8,9,6,4] print ("Pass" if ((1,76) == get_min_max(l)) else "Fail") #Test case 5 (Including negative numbers) l = [-2,-4,100,-10000,34,-23,2,100,21] print ("Pass" if ((-10000,100) == get_min_max(l)) else "Fail") # Output # Maximum minimum pair is: (0, 9) # Pass # Maximum minimum pair is: (1, 1) # Pass # Array is empty! # Pass # Maximum minimum pair is: (1, 76) # Pass # Maximum minimum pair is: (-10000, 100) # Pass