text
stringlengths
37
1.41M
# In this program, we will use three datasets to answer some questions. import pandas as pd import numpy as np pd.options.mode.chained_assignment = None # Energyy file. def energy(): # Loading the first file and omitting some rows from the top and bottom. energy = pd.read_excel('energy.xls', skiprows = 17) energy.drop(energy.index[227:], inplace = True) energy.drop(energy.columns[0:2], axis = 1, inplace = True) energy.columns = ['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable'] # Turning missing values in the form of '...' into np.NaN. for i in range(energy.shape[0]): if type(energy.iloc[i]['Energy Supply']) == type('a'): energy.at[i, 'Energy Supply'] = np.NaN for i in range(energy.shape[0]): if type(energy.iloc[i]['Energy Supply per Capita']) == type('a'): energy.at[i, 'Energy Supply per Capita'] = np.NaN # Adusting column dtypes for later avoiding errors. Further, converting Energy Supply to # gigajoules (there are 1,000,000 gigajoules in a petajoule) energy['Energy Supply'] = pd.to_numeric(energy['Energy Supply']) energy['Energy Supply'] = energy['Energy Supply']*1000000 energy['Energy Supply per Capita'] = pd.to_numeric(energy['Energy Supply per Capita']) # Editing the names of some countries. name_changes_energy = {"Republic of Korea": "South Korea", "United States of America": "United States", "United Kingdom of Great Britain and Northern Ireland": "United Kingdom", "China, Hong Kong Special Administrative Region": "Hong Kong"} for i in range(energy.shape[0]): for j in name_changes_energy.keys(): if energy['Country'].iloc[i] == j: energy['Country'].iloc[i] = name_changes_energy[j] # First, finding the names for some countries which have unwanted names including # numbers and/or parenthesis; and then, editing them. name_changes_indicators = ['(', ')', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] name_changes = [] for i in range(energy.shape[0]): for j in name_changes_indicators: if j in energy['Country'].iloc[i]: if energy['Country'].iloc[i] not in name_changes: name_changes.append(energy['Country'].iloc[i]) name_changes_energy_2 = {} for i in name_changes: name_changes_energy_2[i] = None # print(name_changes_energy_2) this is for finding the names so that we can # manually create a dictionary in the next step to revise the names. name_changes_energy_2 = {'Australia1': 'Australia', 'Bolivia (Plurinational State of)': 'Bolivia', 'China, Hong Kong Special Administrative Region3': 'Hong kong', 'China, Macao Special Administrative Region4': 'China, Macao Special Administrative Region', 'China2': 'China', 'Denmark5': 'Denmark', 'Falkland Islands (Malvinas)': 'Falkland Islands', 'France6': 'France', 'Greenland7': 'Greenland', 'Indonesia8': 'Indonesia', 'Iran (Islamic Republic of)': 'Iran', 'Italy9': 'Italy', 'Japan10': 'Japan', 'Kuwait11': 'Kuwait', 'Micronesia (Federated States of)': 'Micronesia', 'Netherlands12': 'Netherlands', 'Portugal13': 'Portugal', 'Saudi Arabia14': 'Saudi Arabia', 'Serbia15': 'Serbia', 'Sint Maarten (Dutch part)': 'Sint Maarten', 'Spain16': 'Spain', 'Switzerland17': 'Switzerland', 'Ukraine18': 'Ukraine', 'United Kingdom of Great Britain and Northern Ireland19': 'United Kingdom', 'United States of America20': 'United States', 'Venezuela (Bolivarian Republic of)': 'Venezuela'} for i in range(energy.shape[0]): for j in name_changes_energy_2.keys(): if energy['Country'].iloc[i] == j: energy['Country'].iloc[i] = name_changes_energy_2[j] # print(energy.info()) # print(energy.iloc[[0, -1]]) return energy # GDP file. def GDP(): GDP = pd.read_csv('gdp.csv', skiprows = 4) # Editing the names of some countries. name_changes_GDP = {"Korea, Rep.": "South Korea", "Iran, Islamic Rep.": "Iran", "Hong Kong SAR, China": "Hong Kong"} for i in range(GDP.shape[0]): for j in name_changes_GDP.keys(): if GDP['Country Name'].iloc[i] == j: GDP['Country Name'].iloc[i] = name_changes_GDP[j] # Changing the name of 'Country Name' column GDP.rename(columns = {'Country Name' : 'Country'}, inplace = True) # Keeping only the last 10 years, 2005-2016. cols_GDP = ['Country'] years = range(2006, 2016) for i in years: cols_GDP.append(str(i)) GDP = GDP[cols_GDP] # print(GDP.info()) # print(GDP.iloc[[0, -1]]) return GDP # ScimEn file. def ScimEn(): ScimEn = pd.read_excel('science.xlsx') # print(ScimEn.info()) # print(ScimEn.iloc[[-1, 0]]) return ScimEn # Merging the three datasets into one comprehensive dataset. def total_data(): energy_table = energy() GDP_table = GDP() ScimEn_table = ScimEn() # Merging the three datasets into one, using the country names. part_1 = pd.merge(energy_table, GDP_table, how = 'inner', left_on = 'Country', right_on = 'Country') All_data = pd.merge(part_1, ScimEn_table, how = 'inner', left_on = 'Country', right_on = 'Country') # Getting only the records for the top 15 ranked countries. Result_data = All_data[All_data['Rank'] <= 15] # Setting Country names as index. Result_data.set_index('Country', inplace = True) # Reordering columns. cols = ['Rank', 'Documents', 'Citable documents', 'Citations', 'Self-citations', 'Citations per document', 'H index', 'Energy Supply', 'Energy Supply per Capita', '% Renewable', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015'] Result_data = Result_data[cols] return Result_data # The previous function joins three datasets then reduces this to just the top 15 entries. # In the below function, we find out how many entries we lost through this merge. def data_loss(): energy_table = energy() GDP_table = GDP() ScimEn_table = ScimEn() # Inner merges. part_1 = pd.merge(energy_table, GDP_table, how = 'inner', left_on = 'Country', right_on = 'Country') All_data = pd.merge(part_1, ScimEn_table, how = 'inner', left_on = 'Country', right_on = 'Country') # Outer merges. part_1_o = pd.merge(energy_table, GDP_table, how = 'outer', left_on = 'Country', right_on = 'Country') All_data_o = pd.merge(part_1_o, ScimEn_table, how = 'outer', left_on = 'Country', right_on = 'Country') # print(len(All_data_o) - len(All_data)) return (All_data_o.shape[0]) - (All_data.shape[0]) # Finding out the average GDP over the last 10 years for each country. def avg_GDP(): Top15 = total_data() yrs = range(2006, 2016) cols_10 = [] for i in yrs: cols_10.append(str(i)) Top15['average_GDP'] = Top15.apply(lambda row: np.mean(row[cols_10]), axis = 1) s = Top15['average_GDP'] avgGDP = s.sort_values(ascending = False) return avgGDP # Finding out how much has the GDP changed over the 10 year span for the country with the 6th largest average GDP. def GDP_change(): Top15 = total_data() first_GDP = Top15.loc['United Kingdom']['2006'] last_GDP = Top15.loc['United Kingdom']['2015'] result = last_GDP - first_GDP return result # Finding out the mean Energy Supply per Capita. def mean_ESC(): Top15 = total_data() return np.mean(Top15['Energy Supply per Capita']) # Finding out the country that has the maximum % Renewable and its percentage? def max_RNW(): Top15 = total_data() max_percentage = np.max(Top15['% Renewable']) country_name = list(Top15.where(Top15['% Renewable'] == np.max(Top15['% Renewable'])).dropna().index)[0] result = (country_name, max_percentage) return result # Creating a new column that is the ratio of Self-Citations to Total Citations; and then, finding out # the maximum value for this new column, and the country that has the highest ratio. def max_cit_ratio(): Top15 = total_data() Top15['self_citation_ratio'] = Top15['Self-citations']/Top15['Citations'] max_self_citation = np.max(Top15['self_citation_ratio']) country_name = list(Top15.where(Top15['self_citation_ratio'] == np.max(Top15['self_citation_ratio'])).dropna().index)[0] result = (country_name, max_self_citation) return result # Creating a column that estimates the population using Energy Supply and Energy Supply per capita; and then, # finding out the third most populous country according to this estimate. def third_country(): Top15 = total_data() Top15['estimated_population'] = Top15['Energy Supply']/Top15['Energy Supply per Capita'] third_population = Top15['estimated_population'].sort_values(ascending = False).iloc[2] country_name = list(Top15.where(Top15['estimated_population'] == third_population).dropna().index)[0] return country_name # Creating a column that estimates the number of citable documents per person; and then, finding out the # correlation between the number of citable documents per capita and the energy supply per capita; # using Pearson's R. def correlation(): Top15 = total_data() Top15['estimated_population'] = Top15['Energy Supply']/Top15['Energy Supply per Capita'] Top15['estimated_citation_per_person'] = Top15['Citable documents']/Top15['estimated_population'] cols = ['Energy Supply per Capita', 'estimated_citation_per_person'] Top15n = Top15[cols] Top15n['estimated_citation_per_person'] = pd.to_numeric(Top15n['estimated_citation_per_person']) Top15n['Energy Supply per Capita'] = pd.to_numeric(Top15n['Energy Supply per Capita']) df = Top15n.corr() result = df.loc['estimated_citation_per_person']['Energy Supply per Capita'] return result # Creating a new column with a 1 if the country's % Renewable value is at or above the median for # all countries in the top 15, and a 0 if the country's % Renewable value is below the median; and then, # returning a series whose index is the country name sorted in ascending order of rank. def RNW_median(): Top15 = total_data() Top15['median_criteria'] = Top15.apply(lambda x: 1 if x['% Renewable'] >= np.median(Top15['% Renewable']) else 0, axis = 1) HighRenew = Top15['median_criteria'].sort_values() return HighRenew # Using a dictionary to group the countries by continent; and then creating a dateframe that # displays the sample size (the number of countries in each continent bin), and the sum, mean, # and the std using the estimated populations of countries in each group. def groupings(): Top15 = total_data() Top15['estimated_population'] = Top15['Energy Supply']/Top15['Energy Supply per Capita'] Top15n = Top15.reset_index() def convertor(x): data = x['Country'] ContinentDict = {'China':'Asia', 'United States':'North America', 'Japan':'Asia', 'United Kingdom':'Europe', 'Russian Federation':'Europe', 'Canada':'North America', 'Germany':'Europe', 'India':'Asia', 'France':'Europe', 'South Korea':'Asia', 'Italy':'Europe', 'Spain':'Europe', 'Iran':'Asia', 'Australia':'Australia', 'Brazil':'South America'} for i in ContinentDict.keys(): if data == i: return ContinentDict[i] Top15n['Continent'] = Top15n.apply(convertor, axis = 1) cols = ['Continent', 'estimated_population'] Top15n = Top15n[cols] Top15n['estimated_population'] = pd.to_numeric(Top15n['estimated_population']) Result = pd.DataFrame(index = ['Asia', 'Australia', 'Europe', 'North America', 'South America']) Result['size'] = Top15n.groupby('Continent').count() Result['sum'] = Top15n.groupby('Continent').sum() Result['mean'] = Top15n.groupby('Continent').mean() Result['std'] = Top15n.groupby('Continent').std() return Result # Cutting % Renewable into 5 bins; and then, grouping the Top15 by the Continent, as well as these new % Renewable bins. # Then, finding out how many countries are in each of these groups. def groupings_2(): Top15 = total_data() Top15n = Top15.reset_index() def convertor(x): data = x['Country'] ContinentDict = {'China':'Asia', 'United States':'North America', 'Japan':'Asia', 'United Kingdom':'Europe', 'Russian Federation':'Europe', 'Canada':'North America', 'Germany':'Europe', 'India':'Asia', 'France':'Europe', 'South Korea':'Asia', 'Italy':'Europe', 'Spain':'Europe', 'Iran':'Asia', 'Australia':'Australia', 'Brazil':'South America'} for i in ContinentDict.keys(): if data == i: return ContinentDict[i] Top15n['Continent'] = Top15n.apply(convertor, axis = 1) Top15n['Rnw_gp'] = pd.cut(Top15n['% Renewable'], 5) result = Top15n.groupby(['Continent', 'Rnw_gp']).size() return result # Converting the Population Estimate series to a string with thousands separator (using commas). def convertor_str(): Top15 = total_data() Top15['estimated_population'] = Top15['Energy Supply']/Top15['Energy Supply per Capita'] PopEst = Top15['estimated_population'] for i in range(PopEst.shape[0]): PopEst.iloc[i] = '{:,}'.format(PopEst.iloc[i]) return PopEst f1 = total_data() print(f1) print('This was a function results.\n\n') f2 = data_loss() print(f2) print('This was a function results.\n\n') f3 = avg_GDP() print(f3) print('This was a function results.\n\n') f4 = GDP_change() print(f4) print('This was a function results.\n\n') f5 = mean_ESC() print(f5) print('This was a function results.\n\n') f6 = max_RNW() print(f6) print('This was a function results.\n\n') f7 = max_cit_ratio() print(f7) print('This was a function results.\n\n') f8 = third_country() print(f8) print('This was a function results.\n\n') f9 = correlation() print(f9) print('This was a function results.\n\n') f10 = RNW_median() print(f10) print('This was a function results.\n\n') f11 = groupings() print(f11) print('This was a function results.\n\n') f12 = groupings_2() print(f12) print('This was a function results.\n\n') f13 = convertor_str() print(f13) print('This was a function results.\n\n') print('\nThanks for reviewing') # Thanks for reviewing
import os disk=input("Введите путь, который вы хотите отскранировать: ") folder=[] for i in os.walk(disk): folder.append(i) files=[] sum=0 for address, dirs, files in folder: for file in files: sum+=os.path.getsize(address+'\\'+file) print(sum,'- Б') print(sum/1024,'- КБ') print(sum/1024/1024,'- МБ') print(sum/1024/1024/1024,'- ГБ') print(sum/1024/1024/1024/1024,'- ТБ') # import os # # disk=input("Введите диск, который вы хотите отскранировать: ") # # print(os.listdir(disk)) # os.chdir(disk) # print(os.getcwd()) # # def get_folder_size(path,size=0): # print(os.listdir(path)) # # os.chdir(path) # for i in os.listdir(path): # # cur_path=os.path.abspath(i) # print(cur_path) # if os.path.isfile(cur_path): # size+=os.path.getsize(cur_path) # print(size) # else: # previous_path = path # os.chdir(path) # size+=get_folder_size(cur_path) # # return size # # # # # # # # get_folder_size(os.path.realpath(disk))
# names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"] # usernames = [] # # # write your for loop here # for name in names: # usernames.append(name.replace(' ', '_').lower()) # # print(usernames) # names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"] # # for name in names: # name = name.lower().replace(" ", "_") # # print(names) # usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"] # # # write your for loop here # for index in range(len(usernames)): # usernames[index] = usernames[index].lower().replace(' ', '_') # # print(usernames) # tokens = ['<greeting>', 'Hello World!', '</greeting>'] # count = 0 # # # write your for loop here # for index in range(len(tokens)): # if tokens[index].startswith('<') and tokens[index].endswith('>'): # count += 1 # # print(count) # items = ['first string', 'second string'] # html_str = "<ul>\n" # "\ n" is the character that marks the end of the line, it does # # the characters that are after it in html_str are on the next line # # # write your code here # for item in items: # html_str += "<li>{}</li>\n".format(item) # html_str += "</ul>" # # print(html_str) # colors = ['Red', 'Blue', 'Green', 'Purple'] # lower_colors = [] # # for color in colors: # lower_colors.append(color.lower()) # # print(lower_colors) # # number to find the factorial of # number = 6 # # # start with our product equal to one # product = 1 # # # track the current number being multiplied # current = 1 # # # write your while loop here # # while current <= number: # product *= current # current+=1 # # # # multiply the product so far by the current number # # # # increment current with each iteration until it reaches number # # # # print the factorial of number # print(product) # # number to find the factorial of # number = 6 # # # start with our product equal to one # product = 1 # # # track the current number being multiplied # current = 1 # # # write your while loop here # # for num in range(2, number + 1): # product *= num # # # multiply the product so far by the current number # # # # increment current with each iteration until it reaches number # # # # print the factorial of number # print(product) # start_num = 2 # provide some start number # end_num = 100 # provide some end number that you stop when you hit # count_by = 2 # provide some number to count by # # # # write a while loop that uses break_num as the ongoing number to # # check against end_num # break_num = start_num # while break_num < end_num: # break_num += count_by # print(break_num) # # print(break_num) # start_num = 1 # provide some start number # end_num = 100 # provide some end number that you stop when you hit # count_by = 2 # provide some number to count by # # # write a condition to check that end_num is larger than start_num before looping # # write a while loop that uses break_num as the ongoing number to # # check against end_num # # if start_num > end_num: # print("Oops! Looks like your start value is greater than the end value. Please try again.") # else: # result = start_num # while result < end_num: # result += count_by # # # print(result) # limit = 40 # # # write your while loop here # num = 0 # while (num + 1) ** 2 < limit: # num += 1 # nearest_square = num ** 2 # # print(nearest_square) # num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, # 149, 59, 84, 69, 113, 166] # # count_odd = 0 # list_sum = 0 # i = 0 # len_num_list = len(num_list) # # while (count_odd < 5) and (i < len_num_list): # if num_list[i] % 2 != 0: # list_sum += num_list[i] # count_odd += 1 # i += 1 # # print("The numbers of odd numbers added are: {}".format(count_odd)) # print("The sum of the odd numbers added is: {}".format(list_sum)) # HINT: modify the headlines list to verify your loop works with different inputs # headlines = ["Local Bear Eaten by Man", # "Legislature Announces New Laws", # "Peasant Discovers Violence Inherent in System", # "Cat Rescues Fireman Stuck in Tree", # "Brave Knight Runs Away", # "Papperbok Review: Totally Triffic"] # # news_ticker = "" # # write your loop here # for line in headlines: # # if len(news_ticker) > 140: # news_ticker = news_ticker[0:140] # break # else: # news_ticker += line+" " # # print(news_ticker) # # print(news_ticker) # # ## Your code should check if each number in the list is a prime number # check_prime = [26, 39, 51, 53, 57, 79, 85] # # ## write your code here # ## HINT: You can use the modulo operator to find a factor # # for num in check_prime: # for i in range(2, num): # if (num % 2) == 0: # print("{} is NOT a prime number, because {} is a factor of {}".format(num, i, num)) # break # if i == num - 1: # print("{} IS a prime number".format(num))
name= "America" print(name) favFoods= ["banku","konkonte","waakye","beans","tuozaafi"] print(favFoods) print(favFoods[-1]) print(favFoods[0:4]) print("My favourite foods are "+ favFoods[0] + " " + favFoods[1] + " ") string1= "We are" string2= " here to study" string3=" cloud computing" print(string1 + string2 + string3) print(favFoods[0].title()) ages=[1,2,3,4, "abi"] print(ages[0]) print(str(ages[0])+str(ages[1])) print(ages[0],ages[4]) favFoods[2]="amala" print(favFoods) ages[-1]=5 print(ages) favFoods.append("eba") favFoods.append("pepper soup") print(favFoods) favFoods.insert(1,"rice") print(favFoods) print([1]) # list attendeeList=["Anita","Linda","Akua","Rita"] print(attendeeList) #To use delete, pop and remove to take an item out from the list attendeeList.remove("Linda") print(attendeeList) # delete method attendeeList=["Anita","Linda","Akua","Rita"] del attendeeList[0] print(attendeeList) # pop method. Takes out the last item in the list attendeeList=["Anita","Linda","Akua","Rita"] attendeeList.pop() print(attendeeList) # If an item is popped out, it can be assigned a variable and print it out later attendeeList=["Anita","Linda","Akua","Rita"] notattendeeList=attendeeList.pop() print(notattendeeList)
import random from Score import Score class Player: def __init__(self, name, order): self.name = name self.order = order """There are two type of turns, open and closed You start closed, once you score 1000 in a turn You become open, meaning you can score less that 1000 points""" self.open_turn = False self.remaining_dice = 6 self.points = 0 self.roll_number = 0 self.dice_dict = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0} self.round_points = 0 def change_turn_style(self, style): """There are two types of turns in the game: open and closed. It stars closed. After scoring 750 in one round, it becomes open.""" self.open_turn = True return self.open_turn def roll(self): remaining_dice = self.remaining_dice """Generates a random number from 1 - 6 based on the number of dice left and puts them in a sorted list.""" dice_roll = sorted([random.randint(1,6) for i in range(1, remaining_dice+1)]) self.roll_number +=1 return dice_roll, self.roll_number @staticmethod def DiceDisplayer(dice_roll): for i in range(len(dice_roll)): print(f"Dice {i+1}: {dice_roll[i]}") def update_dice_count(self, kept_dice): self.remaining_dice = self.remaining_dice - len(kept_dice) def hold(self, dice_roll): while True: #start loop for AreYouSure function while True: #setting up for invalid inputs Player.DiceDisplayer(dice_roll) try: kept_dice = input(""" Which dice would you like to keep? Enter the dice number (not the value), separated by commas. Press enter to keep everything. > """).split(',') except IndexError: print("That is not an available die.") #create an error in case people enter something stupid, use RE else: break if kept_dice == ['']: #keeps all the dice if nothing is entered above kept_dice = [i for i in range(len(dice_roll))] """Using the kept_dice to create a list of all the dice values that are saved without overwriting the original roll, in case they change their mind.""" kept_dice = list(map(int, kept_dice)) dice_bank = [dice_roll[i-1] for i in kept_dice] print(f"You've chosen {sorted(dice_bank)}") msg = "Is this correct (y/n)? " if self.AreYouSure(msg) == True: break dice_roll = list(map(int, dice_bank)) #overwrites oringal roll with save dice self.update_dice_count(kept_dice) self.DiceCounter(dice_roll) return self.dice_dict def KeepPoints(self): """Saves the points from the round to the player and clears the round points.""" self.points += self.round_points print(f"You've scored {self.round_points} this turn.") self.round_points = 0 print(f"You now have {self.points} total.") return self.points, self.round_points def DiceCounter(self, dice_roll): """Converts a list of dice into a dictionary that counts all the dice vales, which can be read by our scorer""" self.ResetDice() for i in dice_roll: if i in self.dice_dict: self.dice_dict[i] +=1 return self.dice_dict def AreYouSure(self, msg): """Player gets to chooose yes or no.""" while True: roll_again = input(msg) if roll_again == "n": return False elif roll_again == "y": return True else: print("Please enter y or n ") def ResetDice(self): self.dice_dict = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0} return self.dice_dict def Turn(self): """The general sequence for a player's turn. The turn end when the player either: chooses to stop rolling, has a roll with no points, or reaches three rolls without a bonus. The points from the round are added to the player.""" while self.roll_number <3: dice_roll, self.roll_number = self.roll() """We need to check if the intial roll is zilched. if so, there is no point asking if they want to save any dice, because their turn is over.""" dice = self.DiceCounter(dice_roll) score = Score(dice) score.MasterScorer() if score.zilched == True: self.round_points = 0 break dice = self.hold(dice_roll) score = Score(dice) score.MasterScorer() print(f"You scored {score.roll_points}! Great job!") self.round_points += score.roll_points self.ResetDice() msg = "Would you like to roll again (y/n)? " if self.remaining_dice == 0: self.roll_number = 0 self.remaining_dice = 6 print({self.roll_number}, {self.remaining_dice}) elif self.roll_number == 3: #You are only allowed three rolls break else: if self.AreYouSure(msg) == False: break self.KeepPoints() player1 = Player("player1", 1) dice_roll = player1.Turn() """ player1.hold(r1_t1) r1_r2 = player1.roll2() player1.hold(r1_r2) r1_r3 = player1.roll3() """
import unittest def insertion_sort(list): for i in range(2, len(list)): index = i while index > 0 and list[index - 1] > list[index]: list[index - 1], list[index] = list[index], list[index - 1] index -=1 return list class UnitTest(unittest.TestCase): def test(self): self.assertEqual([1, 2, 3, 4, 5, 6], insertion_sort([4, 6, 1, 3, 5, 2])) self.assertEqual([1, 2, 3, 4, 5, 6], insertion_sort([1, 3, 4, 2, 5, 6])) self.assertEqual([1, 2, 3, 4, 5, 6], insertion_sort([1, 4, 2, 3, 6, 5])) if __name__ == '__main__': unittest.main()
# Задание 6 # Напишите функцию, которая считает количество # цифр в числе. Число передаётся в качестве параметра. Из # функции нужно вернуть полученное количество цифр. # Например, если передали 3456, количество цифр будет 4. def number_of_digits (num:int): count=0 while num>0: num//=10 count=count+1 return count number=int(input("Enter the number: ")) print(number_of_digits(number))
# 2. Що таке map(), filter(), lambda x: x ** 2 # # map() - это функция, которая принимает два аргумента: функцию и аргумент составного типа данных, # например, список. map применяет к каждому элементу списка переданную функцию. # Например, вы прочитали из файла список чисел, изначально все эти числа имеют строковый тип данных, # чтобы работать с ними - нужно превратить их в целое число: old_list = ['1', '2', '3', '4', '5', '6', '7'] new_list = list(map(int, old_list)) print(new_list) # filter() - это функция, которая предлагает элегантный вариант фильтрации элементов последовательности. # Принимает в качестве аргументов функцию и последовательность, которую необходимо отфильтровать mixed = ['мак', 'просо', 'мак', 'мак', 'просо', 'мак', 'просо', 'просо', 'просо', 'мак'] zolushka = list(filter(lambda x: x == 'мак', mixed)) print(zolushka) # lambda оператор или lambda функция в Python это способ создать анонимную функцию, то есть функцию без имени. # Такие функции можно назвать одноразовыми, они используются только при создании # В данном примере lambda функция возводит в квадрат значение, переданое ей в качестве аргумента и выводит результат z=lambda x: x ** 2 print(z(5))
def GetAnswerWithUnderscores(answer, letters_guessed): result = '' for char in answer: if char in letters_guessed: result += char else: result += '_' return result answer = GetAnswerWithUnderscores('welcome', 'mel') print('GetAnswerWithUnderscores #1: expected _el__me, got', answer) answer = GetAnswerWithUnderscores('quick', 'rstlne') print('GetAnswerWithUnderscores #2: expected _____, got', answer) def GetWordSeparatedBySpaces(word): result = "" for index in range(len(word)): if index == (len(word)-1): result += word[index] else: result += word[index] + " " return result answer = GetWordSeparatedBySpaces('plane') print('GetWordSeparatedBySpaces #1: expected p l a n e, got', answer) answer = GetWordSeparatedBySpaces('to') # Don't worry about the hasattr function, the if statement, or what they # do: it's not required for this Hangman assignment. if hasattr(answer, 'strip') and answer.strip() == answer: text = 'PASS' else: text = 'FAIL' print('GetWordSeparatedBySpaces #2: expected no spaces at the beginning or end,', text) def IsWinner(answer, letters_guessed): c = 0 for char in answer: for index in range(len(letters_guessed)): if char == letters_guessed[index]: c += 1 if c == len(answer): return True return False answer = IsWinner('plane', 'anelp') print('IsWinner #1: expected True, got', answer) answer = IsWinner('plane', 'plan') print('IsWinner #2: expected False, got', answer) def IsLegalGuess(current_guess, letters_guessed): if current_guess.lower() not in 'abcdefghijklmnopqrstuvwxyz': print('Input is not a valid string i.e english alphabets') return False else: if len(current_guess) == 1: if current_guess not in letters_guessed.lower(): return True else: print('Input already exists') return False else: print('Input is not a single character') return False answer = IsLegalGuess('g', '') print('IsLegalGuess #1: expected True, got', answer) answer = IsLegalGuess('g', 'rstle') print('IsLegalGuess #1: expected True, got', answer) answer = IsLegalGuess('bb', 'cat') print('IsLegalGuess #1: expected False, got', answer) answer = IsLegalGuess('p', 'yzpr') print('IsLegalGuess #1: expected False, got', answer) def GetLegalGuess(letters_guessed): input_guessed = input('Input your guess') while not IsLegalGuess(input_guessed, letters_guessed): input_guessed = input('Input your guess') return input_guessed print(GetLegalGuess('abc')) def IsGuessRevealing(answer, legal_letter_guess): if legal_letter_guess in answer: return True else: return False answer = IsGuessRevealing('welcome', 'c') print('IsGuessRevealing #1: expected True, got', answer) answer = IsGuessRevealing('quick', 'z') print('IsGuessRevealing #1: expected False, got', answer)
class object: def __init__(self,Name,Health,Speed,Power): self.Name = Name self.Health = Health self.Speed = Speed self.Power = Power self.Luck = 0 def update_luck(self,num): self.Luck = num def add_luck(self,num): self.Luck += num def show_stats(self): new_words = "" dictonary = { "Name":self.Name, "Health":self.Health, "Speed":self.Speed, "Power":self.Power, "Luck":self.Luck } for i,v in dictonary.items(): new_words+= f"\n {i}: {v}" return new_words class player(object): def __init__(self,Name,Health,Speed,Power): super().__init__(Name,Health,Speed,Power) class enemy(object): def __init__(self,enemy_name = "Enemy",enemy_heath =20,Speed = 10, enemy_power = 15): self.enemy_name = enemy_name self.enemy_heath = enemy_heath self.enemy_power = enemy_power super().__init__(enemy_name,enemy_heath,Speed,enemy_power) def change_enemy_stats(self,Name,Heatlh,Power,Speed): self.enemy_name = Name self.enemy_heath = Heatlh self.enemy_power = Power self.Speed = Speed def show_enemy_luck(self): if self.Luck >=10 and self.Luck<100: return "This enemy has some luck" elif self.Luck>=100 and self.Luck<10_000: return "This enemy has luck" elif self.Luck>=10_000: return "This enemy is the luckiest" else: return "Return this enemy does not have much luck" def show_stats(self): enemy_text = "" enemy_dic = { "Name":self.enemy_name, "Health":self.enemy_heath, "Power":self.enemy_power, "Speed":self.Speed, "Luck":self.Luck, } for i,v in enemy_dic.items(): enemy_text += f"\n {i}: {v}" return enemy_text class boss(object): def __init__(self,Name,Health,Speed,Power,Destruction): self.Destruction = Destruction super().__init__(Name,Health,Speed,Power) self.enemy = enemy() def show_stats(self): boss_word ="" boss_dictonary = { "Name":self.Name, "Health":self.Health, "Speed":self.Speed, "Luck":self.Luck, "Destruction":self.Destruction, "Power":self.Power } for i,v in boss_dictonary.items(): boss_word += f"\n {i}: {v}" return boss_word greg = player("Greg",15,12,21) greg.update_luck(10) greg.add_luck(24) superboss = boss("Plant Eater",25,12,12,"BIG") superboss.update_luck(15) superboss.add_luck(12) superboss.enemy.change_enemy_stats("Small Plant Eater",10,25,12) print(superboss.show_stats()) print(superboss.enemy.show_stats()) bad_guy = enemy("Bad Guy",23,20) bad_guy.add_luck(14) print(bad_guy.show_stats()) superboss.enemy.update_luck(3) print(superboss.enemy.show_enemy_luck())
li = ["Improve","Problem","Solving","Skills"] li.sort() print(li) print("These tips are very good") li.reverse() print(li) print(len(li)) wonderOftheWorld = ["Great Wall of China","Christ The Reedemer","Machu Picchu","Chichen Itza","Roman Colosseum","Taj Mahal","Petra"] print(len(wonderOftheWorld)) print(f"This is the wonders of the world if it was sorted in alphabitcal order temporarly {sorted(wonderOftheWorld)}") print(wonderOftheWorld) print(f"This is what the it would look like if it was printed in reverse alphabetical order {sorted(wonderOftheWorld, reverse=True)}") wonderOftheWorld.reverse() print(wonderOftheWorld) wonderOftheWorld.reverse() print(wonderOftheWorld) wonderOftheWorld.sort() print(wonderOftheWorld) wonderOftheWorld.sort(reverse=True) print(wonderOftheWorld) wonderOftheWorld.sort() print(wonderOftheWorld)
#https://leetcode.com/problems/guess-number-higher-or-lower/description/ """ We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number is higher or lower. You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): -1 : My number is lower 1 : My number is higher 0 : Congrats! You got it! Example: n = 10, I pick 6. Return 6. if (nums.length <= 0) { return -1; } var low = 0; var high = nums.length - 1; while (low <= high) { var mid = low + parseInt( (high - low) / 2 ); // Prevent (LOW + HIGH) overflow if (nums[mid] === target) { return mid; } else if (nums[mid] < target) { low = mid + 1; } else if (nums[mid] > target) { high = mid - 1; } } return -1; """ def guess(n): if n == 6: return 0 if n > 6: return 1 if n < 6: return -1 class Solution(object): def guessNumber(self, n): """ :type n: int :rtype: int """ left, right = 1, n while (left <= right): mid = left + (right - left) // 2 if guess(mid) == 0: return mid elif guess(mid) == 1: left = mid + 1 elif guess(mid) == -1: right = mid - 1 s = Solution() print s.guessNumber(5) print s.guessNumber(6) print s.guessNumber(4)
# Write a function that takes a string in prefix notation (operator and two numbers) # Parse output and produce appropriate output # Assume only valid arguments # Implement each operation as a separate function; don't use an if statement from operator import add, sub, mul, truediv, mod, pow def calc(s): opmap = {'+':add , '-':sub , '*':mul , '/':truediv , '%':mod , '**':pow} args = s.split(' ') return opmap[args[0]](int(args[1]), int(args[2])) # Things to do better: # Assign during split to make more readable # Didn't need to split on whitespace (does this automatically) # Format dict to be more readable def calc_two(s): opmap = {'+':add , '-':sub , '*':mul , '/':truediv , '%':mod , '**':pow} op, arg1, arg2 = s.split(' ') return opmap[op](int(arg1), int(arg2))
# Write function that takes a string and translates it into Pig Latin def pig_latin(s): if s[0] in 'aeiou': return s + 'way' else: return s[1:] + s[0] + 'ay' #else if begins with other letter #take first letter, put at end, and add "ay" # Things we could have done better # No need for else # F strings # Instructor's version with f strings def pig_latin_two(s): if s[0] in 'aeiou': return f'{s}way' return f'{s[1:]}{s[0]}ay' if __name__ == "__main__": print('apple', pig_latin('apple')) print('car', pig_latin('car')) print('apple', pig_latin_two('apple')) print('car', pig_latin_two('car'))
# Write a version BigBowl that inherits from Bowl and takes more scoops class Scoop: def __init__(self, _flavor): self.flavor = _flavor class Bowl: max_scoops = 3 def __init__(self, _scoops): self.scoops = [] self.add_scoops(*_scoops) def __repr__(self): return "\n".join([scoop.flavor for scoop in self.scoops]) def add_scoops(self, *new_scoops): for new_scoop in new_scoops: if len(self.scoops) < self.max_scoops: self.scoops.append(new_scoop) class BigBowl(Bowl): max_scoops = 5 def __init__(self, _scoops): super().__init__(_scoops) # Reviewing the solution... # The only difference is that we had to add super() because of how we set up Bowl to take scoops during initialization. if __name__ == "__main__": scoops = [Scoop(x) for x in ["pasta", "squid ink", "yellow", "a", "b", "c"]] bowl = Bowl(scoops) bigbowl = BigBowl(scoops) print(bowl) print(bigbowl)
#!/usr/bin/python import numpy as np import matplotlib.pyplot as plt from matplotlib import animation from matplotlib import patches #import pylab import time import math class KalmanFilter: """ Class to keep track of the estimate of the robots current state using the Kalman Filter """ def __init__(self, markers): """ Initialize all necessary components for Kalman Filter, using the markers (AprilTags) as the map Input: markers - an N by 4 array loaded from the parameters, with each element consisting of (x,y,theta,id) where x,y gives the 2D position of a marker/AprilTag, theta gives its orientation, and id gives its unique id to identify which one you are seeing at any given moment """ self.markers = markers self.last_time = None # Used to keep track of time between measurements self.Q_t = np.eye(2) self.R_t = np.eye(3) # YOUR CODE HERE def prediction(self, v, imu_meas): """ Performs the prediction step on the state x_t and covariance P_t Inputs: v - a number representing in m/s the commanded speed of the robot imu_meas - a 5 by 1 numpy array consistening of the values (acc_x,acc_y,acc_z,omega,time), with the fourth of the values giving the gyroscope measurement for angular velocity (which you should use as ground truth) and time giving the current timestamp. Ignore the first three values (they are for the linear acceleration which we don't use) Outputs: a tuple with two elements predicted_state - a 3 by 1 numpy array of the predction of the state predicted_covariance - a 3 by 3 numpy array of the predction of the covariance """ # YOUR CODE HERE pass def update(self,z_t): """ Performs the update step on the state x_t and covariance P_t Inputs: z_t - an array of length N with elements that are 4 by 1 numpy arrays. Each element has the same form as the markers, (x,y,theta,id), with x,y gives the 2D position of the measurement with respect to the robot, theta the orientation of the marker with respect to the robot, and the unique id of the marker, which you can find the corresponding marker from your map Outputs: predicted_state - a 3 by 1 numpy array of the updated state predicted_covariance - a 3 by 3 numpy array of the updated covariance """ # YOUR CODE HERE pass def step_filter(self, v, imu_meas, z_t): """ Perform step in filter, called every iteration (on robot, at 60Hz) Inputs: v, imu_meas - descriptions in prediction. Will be None value if values are not available z_t - description in update. Will be None value if measurement is not available Outputs: x_t - current estimate of the state """ # YOUR CODE HERE pass
# -*- coding: utf-8 -*- # @Author: KeyangZhang # @Date: 2019-12-04 17:28:17 # @LastEditTime: 2020-04-29 18:10:26 # @LastEditors: Keyangzhang import warnings def _mid(a,b,c): """return the middle value of three numbers""" if a<=b<=c or c<=b<=a: return b elif b<=a<=c or c<=a<=b: return a elif a<=c<=b or b<=c<=a: return c class _Cell(object): """Cell cell is the basic element of section """ def __init__(self, demand=0, supply=0): super(_Cell, self).__init__() self.volume = 0 self.demand = 0 self.supply = 0 class Section(object): """road section Section is the basic element of the network and it can be signle-lane or multi-lanes It can be an artery, a link road, an entrance or an export road of an intersection Once the road is initialized the arritubes cannot be change Atrributes: lane_length: float, the length of the section, the unit is km lane_number: int, the number of lanes this section contains, default: 1 cell_length: float, the length of all the cells in this section, default: 0.05km free_speed: float, the free speed of vehicles in this section, default: 60km/h wave_speed: float, the wave_speed of this section, default:8km/h for its definition, please refer to fundamental diagram thoery of traffic flow jam_density: float, the jam_density of this section, default: 200veh/(km*lane) for its definition, please refer to traffic flow theory """ def __init__(self, lane_length, lane_number=1, cell_length=0.05, free_speed=60, wave_speed=8, jam_density=200, name='empty'): super(Section, self).__init__() # constant parameters self.lane_length = lane_length self.lane_number = lane_number self.cell_length = cell_length self.cells_number = int(lane_length/cell_length+0.5) # the number of cell this section contains if self.cells_number<=1: raise ValueError('the number of cells should not be smaller than 2') self.free_speed = free_speed self.wave_speed = wave_speed self.name = name # the actual jam density of this secthin self.jam_density = jam_density * lane_number # the capacity of each cell # the upper limit value of flow between two direct connected cells self.capacity = self.jam_density / \ (1 / self.free_speed + 1 / self.wave_speed) # the initial time interval of each simulation step self.interval = self.cell_length * 3600 / self.free_speed if self.interval < 1: raise ValueError('You should reset cell length and free speed to make the initial simulation interval be more than 1 second') # the maximum number of vehicles that flow form cell i-1 to cell i during sim interval self.max_volume = self.capacity * self.interval / 3600 # dynamic parameters self.cells = [_Cell() for i in range(self.cells_number)] self.flows = [0 for i in range(self.cells_number-1)] # demand of this section, equals to the demand of last cell self.demand = 0 # supply of this section, equals to the supply of first cell self.supply = min(self.max_volume, self.wave_speed / self.free_speed *(self.cell_length * self.jam_density -0) ) / self.interval # inflow of this section per simsecond self.inflow = 0 # outflow of this section per simsecond self.outflow = 0 def __getitem__(self, position): return self.cells[position] def __str__(self): return str([round(cell.volume,2) for cell in self]) def calculate_demand(self): """calculate demand of each cell and this section""" for cell in self.cells: cell.demand = min(cell.volume, self.max_volume) /self.interval self.demand = self.cells[-1].demand def calculate_supply(self): """calculate supply of each cell and this section""" for cell in self.cells: cell.supply = min(self.max_volume, self.wave_speed / self.free_speed * (self.cell_length * self.jam_density - cell.volume)) /self.interval self.supply = self.cells[0].supply def calculate_flow(self): """calculate flows between each two cells""" for i in range(0, self.cells_number-1): self.flows[i] = min(self.cells[i].demand, self.cells[i+1].supply) def update_volume(self): """update the volume of each cell""" # for the first cell self.cells[0].volume = self.cells[0].volume + \ self.inflow - self.flows[0] # for the intermediate cells for i in range(1, self.cells_number-1): self.cells[i].volume = self.cells[i].volume + \ self.flows[i-1]-self.flows[i] # for the last cells self.cells[-1].volume = self.cells[-1].volume + \ self.flows[-1] - self.outflow def last_sim_step_volume(self): """计算上一个仿真步长结束时的元胞内车辆数,同时也是当前仿真步长开始时的元胞内车辆数""" vols = [0 for i in range(self.cells_number)] vols[0] = self.cells[0].volume + self.flows[0] - self.inflow for i in range(1,self.cells_number-1): vols[i] = self.cells[i].volume + self.flows[i] - self.flows[i-1] vols[-1] = self.cells[-1].volume + self.outflow - self.flows[-1] return vols def velocity(self,level='cell'): """get the operation velocity(km/h) of each cell/section at just ended simluation step""" # 每个section中总是储存t+1时刻的volume,t到t+1的flow,即一个仿真步长(step)过程中的流量和仿真步长结束时的元胞中车辆数 # 但计算速度需要用到仿真步长开始时的元胞密度,因此要对应时刻的元胞中车辆数vol_t = Vol_t+1 + outflow_t - inflow_t vels = [] vols = self.last_sim_step_volume() if level=='cell': # 计算第一个元胞 vol = vols[0] outflow = self.flows[0] if vol == 0 : vels.append(0) else : vel = outflow*3600/(vol/self.cell_length) vels.append(round(vel,2)) # 计算中间元胞 for i in range(1,self.cells_number-1): vol = vols[i] outflow = self.flows[i] if vol == 0 : vels.append(0) else: vel = outflow*3600/(vol/self.cell_length) vels.append(round(vel,2)) # 计算最后一个元胞 vol = vols[-1] outflow = self.outflow if vol==0: vels.append(0) else: vel = outflow*3600/(vol/self.cell_length) vels.append(round(vel,2)) return vels elif level=='section': # 先计算每一个元胞的再按照volume计算加权平均 # 计算第一个元胞 vol = vols[0] outflow = self.flows[0] if vol == 0 : vels.append(0) else : vel = outflow*3600/(vol/self.cell_length) vels.append(round(vel,2)) # 计算中间元胞 for i in range(1,self.cells_number-1): vol = vols[i] outflow = self.flows[i] if vol == 0 : vels.append(0) else: vel = outflow*3600/(vol/self.cell_length) vels.append(round(vel,2)) # 计算最后一个元胞 vol = vols[-1] outflow = self.outflow if vol==0: vels.append(0) else: vel = outflow*3600/(vol/self.cell_length) vels.append(round(vel,2)) # 将速度按照volume加权平均 weighted_vels = [vel*vol for vel, vol in zip(vels,vols)] sum_vol = sum(vols) if sum_vol == 0: avg_vel = 0 else: avg_vel = round(sum(weighted_vels)/sum_vol,2) return avg_vel else : raise ValueError('no such level for collecting data') def queue(self,level='section', speed_threshold=8): """get number of vehicles in queue for current section at just ended simulation step """ queues = [0 for i in range(self.cells_number)] vels = self.velocity(level='cell') vols = self.last_sim_step_volume() for i, (vel, vol) in enumerate(zip(vels, vols)): if vel <= speed_threshold and vol != 0: queues[i] = vol if level == 'cell': return queues elif level == 'section': return sum(queues) else: raise ValueError('no such a level for data collection:{0}'.format(level)) def delay(self,level='section'): """get delay of cells/section in the just eded simulation step""" delays = [0 for i in range(self.cells_number)] vels = self.velocity(level='cell') vols = self.last_sim_step_volume() for i, (vel,vol) in enumerate(zip(vels,vols)): # 每一个仿真步长的时间是1s # 计算一秒内实际走过的路程,并计算此路程在自由流状态下的行驶时间 # 此时间和1s的差值乘以元胞内的车辆数,即为元胞的延误 delays[i] = (1 - 1*vel/self.free_speed)*vol if level == 'cell': return delays elif level == 'section': return sum(delays) else: raise ValueError('no such a level for data collection:{0}'.format(level)) def clear(self): for cell in self.cells: cell.volume = 0 class SignalController(object): """SignalController this class resembles the signal controller at the intersection, which controls the signal light status of each entrance Attributes: cycle: the cycle of the signal plan applied by this signal controller, the unit is second for its definition, please refer to the traffic signal control theory offset: the offset of the signal plan applied by this signal controller, the unit is second for its definition, please refer to the traffic signal control theory """ def __init__(self, cycle, offset=0): super(SignalController, self).__init__() self.lamps = {} # {lamp_id:(sec_id,pahse_id),...} self.phases = {} # {phase_id:phase,...} self.lane_groups = {} # {phase_id:[sec1,sec2,...],...} self.cycle = cycle self.offset = offset def create_phase(self,phase_id,start,end): if start>end : raise ValueError('start should be smaller than end') elif start>=self.cycle or end>self.cycle : text = """start or end exceeds the range of cycle and has taken the remainder of cycle. inital green start:{0}, now:{1}; inital green end:{2}, now:{3},cycle:{4}""".format(start,start % self.cycle,end,end % self.cycle,self.cycle) warnings.warn(text) start = start % self.cycle end = end % self.cycle phase = Phase(start,end) self.phases[phase_id]= phase self.lane_groups[phase_id] = [] # initial a lane group return phase else : phase = Phase(start,end) self.phases[phase_id]=phase self.lane_groups[phase_id] = [] # initial a lane group return phase def set_phase(self, phase_id, start, end): ph = self.phases[phase_id] if start>end : raise ValueError('start should be smaller than end [start:{0},end:{1}]'.format(start,end)) if start>self.cycle or end>self.cycle: text = """start or end exceeds the range of cycle and has taken the remainder of cycle. inital green start:{0}, now:{1}; inital green end:{2}, now:{3},cycle:{4}""".format(start,start % self.cycle,end,end % self.cycle,self.cycle) warnings.warn(text) start = start % self.cycle end = end % self.cycle ph.start = start ph.end = end def create_lamp(self,lamp_id,section_id, section, phase_id): """add a lamp on a section""" self.lamps[lamp_id]=(section_id,phase_id) self.lane_groups[phase_id].append(section) return (section_id,phase_id) def update_signal(self,current_time): """update the status of light controled by this signal controller""" time = (current_time+self.offset)%self.cycle for ph_id,group in self.lane_groups.items(): ph = self.phases[ph_id] if not (ph.start<=time<ph.end): # when the light is red, the section cannot generate demand for sec in group: sec.demand=0 def get_queue(self): """获取不同相位下最大排队长度""" result = {} for ph_id, group in self.lane_groups.items(): ques = [sec.queue(level='section') for sec in group] result[ph_id] = max(ques) return result def get_delay(self, method='average'): """获取各相位的延误""" result = {} if method == 'sum': for ph_id, group in self.lane_groups.items(): delays = [sec.delay(level='section') for sec in group] result[ph_id] = sum(delays) elif method == 'average': # 统计单车延误 for ph_id, group in self.lane_groups.items(): average_delay = 0 for sec in group: vol = sum(sec.last_sim_step_volume()) if vol !=0 : average_delay+=sec.delay(level='section')/vol result[ph_id] = average_delay return result def get_inflow(self): """获取各相位的流入车辆数 return: result:dict,{ph_id:inflow} """ result= {} for ph_id, group in self.lane_groups.items(): inflows = [sec.inflow for sec in group] result[ph_id] = sum(inflows) return result class Phase(object): """Phase A phase is a specific movement that has a unique signal indication different intersections can have the same phase combination Attributes: start: the start time of green status of a lamp in the cycle, the unit is second end: the end time of green status of a lamp in the cycle, the unit is second """ def __init__(self, start, end): super(Phase, self).__init__() self.start = start self.end = end class _Connector(object): """Connector the connector connects the upstream sections and downstream sections and it does not have volume and is used merely for calcuate flows between sections Attributes: upstream: list/tuple or Section, the upstream section/sections downstream: list/tuple or Section, the downstream section/sections connect_type: string, there are following three types of connection confluent: the upstream has mutilple sections (<=3) while the downstream only has one split: the upstream has one section while the upstream has severals (<=3) straight: the upstream and downstream both only have one section """ def __init__(self, upstream, downstream,priority=None): super(_Connector, self).__init__() self.upstream = upstream self.downstream = downstream if isinstance(upstream,(tuple,list)) and isinstance(downstream,Section) : self.upnum = len(upstream) self.downnum = 1 self.connect_type='confluent' self._func=self._confluent if priority is not None: s = sum(priority) self.priority = [p/s for p in priority] # standardize the priority else: self.priority = [1/self.upnum for i in range(self.upnum)] elif isinstance(upstream,Section) and isinstance(downstream,(tuple,list)): self.upnum=1 self.downnum=len(downstream) self.connect_type = 'split' self._func=self._split if priority is not None: s = sum(priority) self.priority = [p/s for p in priority] # standardize the priority else: self.priority = [1/self.downnum for i in range(self.downnum)] elif isinstance(upstream,Section) and isinstance(downstream,Section) : self.upnum=1 self.downnum=1 self.connect_type = 'straight' self._func = self._straight else: raise ValueError('cannot connect these two objects') def _straight(self): """the calculate method for staright connection""" flow = min(self.upstream.demand, self.downstream.supply) self.upstream.outflow = flow self.downstream.inflow = flow def _split(self): """the calculate method for split connection""" temp = [self.upstream.demand] for item, p in zip(self.downstream, self.priority): temp.append(item.supply/p) flow = min(temp) # total flow self.upstream.outflow = flow for item, p in zip(self.downstream, self.priority): item.inflow = p * flow def _confluent(self): """the calculate method for confluent connection""" # self.upnum == 2 means that this is a conflunce section if self.upnum == 2 : u1, u2 = self.upstream p1, p2 = self.priority supply = self.downstream.supply if (u1.demand+u2.demand) <= supply: u1.outflow = u1.demand u2.outflow = u2.demand self.downstream.inflow = (u1.demand+u2.demand) else: flow1 = _mid(u1.demand, supply-u2.demand, p1*supply) flow2 = _mid(u2.demand, supply-u1.demand, p2*supply) u1.outflow = flow1 u2.outflow = flow2 self.downstream.inflow = (flow1+flow2) # self.upnum == 3 means that this connector is in the intersection elif self.upnum == 3: # use "rec" to record entrance that is not in red (demand is not 0) rec = [] for i,item in enumerate(self.upstream): if item.demand == 0: item.outflow=0 else: rec.append(i) if len(rec) == 2 : u1 = self.upstream[rec[0]] p1 = self.priority[rec[0]] u2 = self.upstream[rec[1]] p2 = self.priority[rec[1]] # adjust p1 and p2 to satisfy the condition sum(priorities)=1 s = p1 + p2 p1 = p1/s p2 = p2/s supply = self.downstream.supply if (u1.demand+u2.demand) <= supply: u1.outflow = u1.demand u2.outflow = u2.demand self.downstream.inflow = (u1.demand+u2.demand) else: flow1 = _mid(u1.demand, supply-u2.demand, p1*supply) flow2 = _mid(u2.demand, supply-u1.demand, p2*supply) u1.outflow = flow1 u2.outflow = flow2 self.downstream.inflow = (flow1+flow2) elif len(rec) == 1: u = self.upstream[rec[0]] flow = min(u.demand, self.downstream.supply) u.outflow = flow self.downstream.inflow = flow else: # that means len(rec)==3 sumdemand = sum([item.demand for item in self.upstream]) if sumdemand <= self.downstream.supply: for item in self.upstream: item.outflow = item.demand self.downstream.inflow = sumdemand else: flows = [p*self.downstream.supply for p in self.priority] for item, flow in zip(self.upstream, flows): item.outflow = flow self.downstream.inflow = self.downstream.supply else: raise ValueError('there is a confluentor having more than three branches.') def calculate_flow(self): """calculate the inflows and outflows for the upstream and downstream sections""" self._func()
c = input('please enter ciuseuis: ') c = float(c) f = c * 9 / 5 + 32 print('ferenheit:', f)
""" Create a dictionary, using the List items as keys. This will automatically remove any duplicates because dictionaries cannot have duplicate keys. Then, convert the dictionary back into a list: """ MyList = ["a", "b", "a", "c", "c"] MyList = list(dict.fromkeys(MyList)) print(MyList) # Convert it into Set MyList = ["a", "b", "a", "c", "c"] MyList = set(MyList) print(MyList)
# This will generate Fibonacci Series def fibo_series(n): a = 0 b = 1 for i in range(n+1): print(a) c = a + b a = b b = c fibo_series(10)
# Selection Sort MyList = [5, 3, 8, 6, 7, 2] for i in range(len(MyList)): minpos = i for j in range(i, len(MyList), 1): if MyList[j] < MyList[minpos]: minpos = j tmp = MyList[i] MyList[i] = MyList[minpos] MyList[minpos] = tmp print(MyList)
# Linear Search MyList = [5, 3, 8, 6, 7, 2] for i in range(len(MyList)): if MyList[i] == 8: print("Element is found @Position ", i) break else: print("Element is Not Found in List")
import sys sys.setrecursionlimit(200) # This will set Recursion limit print(sys.getrecursionlimit()) # this will print recursion limit # This will calculate Factorial of Given Number def fact(n): if n == 1: return 1 else: return n * fact(n-1) print("Factorial = ", fact(5))
""" String concatenation, ..lets print a string "Welcome to_________ " """ # place = "himachal" # print("Welcome to " + place) # print("Welcome to {}".format(place)) # print(f"Welcome to {place} ") adjective = input("Adjective :") verb1 = input("verb1 : ") verb2 = input("verb 2 : ") famous_place = input('favorite tourist destination :') madlib = f"Himachal is such a {adjective}. You can so many activities here and enjoy nature.\ i love to do {verb1} and {verb2}. {famous_place} is my favorite place in Himachal ." print(madlib)
from random import randint as alea def quizz_table(): a = alea(1, 10) b = alea(1, 10) ab = str(a * b) c = alea(1, 10) d = alea(1, 10) cd = str(c * d) e = alea(1, 10) f = alea(1, 10) ef = str(e * f) g = alea(1, 10) h = alea(1, 10) gh = str(g * h) i = alea(1, 10) j = alea(1, 10) ij = str(i * j) k = alea(1, 10) l = alea(1, 10) kl = str(k * l) m = alea(1, 10) n = alea(1, 10) mn = str(m * n) o = alea(1, 10) p = alea(1, 10) op = str(o * p) q = alea(1, 10) r = alea(1, 10) qr = str(q * r) s = alea(1, 10) t = alea(1, 10) st = str(s * t) score = 0 print(" ________________ ") print(" | |") print(" | QUIZZ |") print(" | TABLE DE |") print(" | MULTIPLICATION |") print(" |________________|\n") # question 1 print("Question 1 :") print(a, "*", b, "= ?") r1 = input("Resultat = ") if ab == r1.replace(" ", ""): print("Bonne reponse !\n") score += 1 else: print("Mauvaise Reponse,\nle resultat etait : ", ab, "\n") # question 2 print("Question 2 :") print(c, "*", d, "= ?") r2 = input("Resultat = ") if cd == r2.replace(" ", ""): print("Bonne reponse !\n") score += 1 else: print("Mauvaise Reponse,\nle resultat etait : ", cd, "\n") # question 3 print("Question 3 :") print(e, "*", f, "= ?") r3 = input("Resultat = ") if ef == r3.replace(" ", ""): print("Bonne reponse !\n") score += 1 else: print("Mauvaise Reponse,\nle resultat etait : ", ef, "\n") # question 4 print("Question 4 :") print(g, "*", h, "= ?") r4 = input("Resultat = ") if gh == r4.replace(" ", ""): print("Bonne reponse !\n") score += 1 else: print("Mauvaise Reponse,\nle resultat etait : ", gh, "\n") # question 5 print("Question 5 :") print(i, "*", j, "= ?") r5 = input("Resultat = ") if ij == r5.replace(" ", ""): print("Bonne reponse !\n") score += 1 else: print("Mauvaise Reponse,\nle resultat etait : ", ij, "\n") # question 6 print("Question 6 :") print(k, "*", l, "= ?") r6 = input("Resultat = ") if kl == r6.replace(" ", ""): print("Bonne reponse !\n") score += 1 else: print("Mauvaise Reponse,\nle resultat etait : ", kl, "\n") # question 7 print("Question 7 :") print(m, "*", n, "= ?") r7 = input("Resultat = ") if mn == r7.replace(" ", ""): print("Bonne reponse !\n") score += 1 else: print("Mauvaise Reponse,\nle resultat etait : ", mn, "\n") # question 8 print("Question 8 :") print(o, "*", p, "= ?") r8 = input("Resultat = ") if op == r8.replace(" ", ""): print("Bonne reponse !\n") score += 1 else: print("Mauvaise Reponse,\nle resultat etait : ", op, "\n") # question 9 print("Question 9 :") print(q, "*", r, "= ?") r9 = input("Resultat = ") if qr == r9.replace(" ", ""): print("Bonne reponse !\n") score += 1 else: print("Mauvaise Reponse,\nle resultat etait : ", qr, "\n") # question 10 print("Question 10 :") print(s, "*", t, "= ?") r10 = input("Resultat = ") if st == r10.replace(" ", ""): print("Bonne reponse !\n") score += 1 else: print("Mauvaise Reponse,\nle resultat etait : ", st, "\n") # score print("Tu as obtenu", score, "points") if score == 10: print("CARTON PLEIN !\n") elif score == 9: print("A 1 point d'avoir tout juste,\ndommage...\n") elif score > 5: print("C'est bien ça !\n") elif score == 5: print("Bien joue !\nTu as obtenu la moyenne\n") elif score == 4: print("Grrrr à 1 point de la moyenne !\n") else: print("Continue à reviser,\ntu vas y arriver !!!\n") boucle = True while boucle: quizz_table() continuer = input("Voulez-vous rejouer ? (O/N): ") if continuer not in ('O', 'o', 'Y', 'y') and continuer in ('N', 'n', ''): boucle = False exit()
""" Class Book: stores individual book information and returns it """ class Book(object): def __init__(self, name, writer, ISBN): self.name = name.strip() self.writer = writer.strip() self.ISBN = ISBN.strip() def print_info(self): print("{:<30} {:<30} {:<30}" .format(self.writer, self.name, self.ISBN)) def get_info(self): return ("{0}\t {1}\t {2}" .format(self.name, self.writer, self.ISBN)) def __eq__(self, other): return self.writer == other.writer def __lt__(self, other): return self.writer < other.writer
#!/usr/bin/env python # coding: utf-8 # In[1]: user_input = str(input("Enter a Phrase: ")) text = user_input.split() a = " " for i in text: a = a+str(i[0]).upper() print(a) # In[ ]:
import bs4 import requests import urllib url = "https://www.nytimes.com/2014/09/21/arts/design/ai-weiwei-takes-his-work-to-a-prison.html" html = requests.get(url).text #it creates a BeautifulSoup object that parsing the html soup = bs4.BeautifulSoup(html,'html.parser') #the css select that we inspected before contents = soup.find_all("p",class_= "story-body-text story-content") for content in contents: #ascii for text blob to analyze, it cant handle utf-8 print content.text.encode("ascii","ignore").strip() # print content.text
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root is None: return [] queue = [[root, 0]] res = [] while len(queue) > 0: cur = queue.pop() node, level = cur[0], cur[1] if node.left is not None: queue.insert(0, [node.left, level + 1]) if node.right is not None: queue.insert(0, [node.right, level + 1]) if level > len(res) - 1: res.append([]) if level % 2 == 0: res[level].append(node.val) else: res[level].insert(0, node.val) return res s = Solution() a = [] for i in range(0, 10): a.append(TreeNode(i)) root = a[0] root.left = a[1] root.right = a[2] a[1].left = a[5] a[2].left = a[3] a[2].right = a[4] # print(root.right.left.val) print(s.zigzagLevelOrder(root))
class Node(object): def __init__(self, val): self.val = val self.next = None def reverse(head): cur = head p = None while cur: q = cur.next cur.next = p p = cur cur = q return p def merge(node1, node2): dummy = Node(0) p = dummy p1, p2 = node1, node2 while p1 and p2: if p1.val < p2.val: p = p.next = p1 p1 = p1.next else: p = p.next = p2 p2 = p2.next while p1: p = p.next = p1 p1 = p1.next while p2: p = p.next = p2 p2 = p2.next return dummy.next def func(head): odd_head = head even_head = head.next p2 = even_head p = p1 = odd_head count = 1 while p: if count % 2 == 0: p2 = p2.next = p else: p1 = p1.next = p p = p.next count += 1 even_head = reverse(even_head) merge(odd_head, even_head)
fibonacci_numbers = [0, 1] # Uses memoization for previously calculated fibonacci numbers def nth_fibonacci_number(n): if n < 0: print(f'Błąd - liczba n: {n} < 0') else: if n >= len(fibonacci_numbers): for i in range(2, n + 1): if i >= len(fibonacci_numbers): fibonacci_numbers.append(fibonacci_numbers[i - 1] + fibonacci_numbers[i - 2]) return fibonacci_numbers[n]
# DONE user_quit_flag = 1 list_of_strings = [] user_input = '' string_found_flag = 0 while user_quit_flag == 1: user_input = raw_input("Enter string to be inserted into a list of strings, enter q to terminate: ") if user_input != 'q': list_of_strings.append(user_input) user_input = '' elif user_input == 'q': user_quit_flag = 0 print(list_of_strings) user_input = raw_input("Enter a string to be searched for in the list of strings: ") for i in range(0, len(list_of_strings)): if user_input == list_of_strings[i]: string_found_flag = 1 if string_found_flag == 1: print("String matched at index: " + str(i)) elif string_found_flag == 0: print("String not found.")
class RSA: def __init__(self, p, q): self.phi = (p - 1) * (q - 1) self.n = p*q self.e = RSA.find_e(self.phi) self.d = self.find_d(self.e, self.phi, self.n) self.public_key = self.e, self.n self.private_key = self.d, self.n print(f"Private key is: '{self.private_key}'") print(f"Public key is : '{self.public_key}'") @staticmethod def find_d(e, phi, n) -> int: """ Brute force algorithm: d*e % phi == 1, where d < n """ d = 1 while d < n: if d*e % phi == 1: return d d += 1 class Decorators: @staticmethod def args_to_int(decorated): def worker(self, message): if type(message) is str: temp_l = [] for char in message: # ord(char) returns a Unicode position of the char, for example, "HI": H -> 72, I -> 73 temp_l.append(str(ord(char))) # for "Hi" it would return 7273 new_message = int("".join(temp_l)) else: try: new_message = int(message) except Exception as e: raise Exception("Message is not integer or string") return decorated(self, new_message) return worker @staticmethod def find_e(phi): e = 2 while e < phi: if RSA.gcd(e, phi) == 1: return e else: e += 1 # Euclid algorithm @staticmethod def gcd(divisor, dividend): quotient = divisor // dividend ## not used remainder = divisor % dividend if remainder == 0: return dividend return RSA.gcd(dividend, remainder) @Decorators.args_to_int def create_signature(self, message): signature = (message**self.e) % self.n print(f"Signature for '{message}' has been created: {signature}") return signature def check_signature(self, signature): message = signature**self.d % self.n print(f"Signature '{signature}' is decrypted to '{message}'") return message def main(): """ Private key is: '(191, 462)' Public key is : '(11, 462)' Signature for '150' has been created: 348 Signature '348' is decrypted to '150' """ rsa_worker = RSA(21,22) s = 150 e = rsa_worker.create_signature(s) d = rsa_worker.check_signature(e)
""" https://leetcode-cn.com/problems/group-anagrams/submissions/ https://leetcode-cn.com/problems/group-anagrams/solution/python-4xing-dai-ma-duo-chong-jie-fa-by-x62e3/ """ class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: strs_dict = {} strs_list = [] n = 0 for str_ in strs: # 字符串排序后进行hash str_sorted = str(sorted(str_)) # 用n记录当前hash的字符串的在list中的下标 if str_sorted not in strs_dict: strs_dict[str_sorted] = n strs_list.append([]) n += 1 strs_list[strs_dict[str_sorted]].append(str_) return strs_list
""" https://leetcode-cn.com/problems/find-all-duplicates-in-an-array/ """ # 1 class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: if len(nums) < 2: return [] nums = sorted(nums) nums_len = len(nums) i = 0 for j in range(1, nums_len): if nums[j] == nums[j-1]: nums[i] = nums[j] i = i + 1 return nums[:i] # 2 class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: if not nums: return [] rst = [] for num in nums: # 因为我们是直接原地修改元素为负值来标记是否访问过,因此这里的num一定要取绝对值 index = abs(num) - 1 val = nums[index] if val < 0: # 如果元素值为负数,说明之前存在同一个索引为num的元素 rst.append(abs(num)) # 原地修改访问标志 nums[index] = -nums[index] return rst
""" https://leetcode-cn.com/problems/validate-binary-search-tree/ https://leetcode-cn.com/problems/validate-binary-search-tree/solution/yan-zheng-er-cha-sou-suo-shu-by-leetcode-solution/ """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: def helper(root, lower=float('-inf'), upper=float('inf')): if root is None: return True val = root.val if val <= lower or val >= upper: return False # 若当前val大于lower,则若是一颗正常的二叉搜索树,他的右节点毕竟也大于当前下界 # 而如果是一颗正常的二叉搜索树,右子树的值需要大于当前节点,所以改变下界为当前节点 if not helper(root.right, lower=val, upper=upper): return False if not helper(root.left, lower=lower, upper=val): return False return True return helper(root)
""" https://leetcode-cn.com/problems/word-ladder/description/ https://leetcode-cn.com/problems/word-ladder/solution/python3-bfshe-shuang-xiang-bfsshi-xian-dan-ci-jie-/ https://leetcode-cn.com/problems/word-ladder/solution/python-shen-du-jiang-jie-bfsde-jie-gou-by-allen-23/ """ class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: import string if endWord not in wordList: return 0 wordList = {i:1 for i in wordList} queue = [(beginWord, 1)] while queue: word, step = queue.pop(0) if word == endWord: return step for idx, c in enumerate(word): for w in string.ascii_lowercase: if w == c: continue search_c = word[: idx] + w + word[idx+1: ] if search_c in wordList: queue.append((search_c, step+1)) wordList.pop(search_c) return 0
def find_sum_pair(l,sum,s): for i in range(len(l)): temp = sum - l[i] if temp>=0 and temp in s: print "pairs with given sum is :"+str(l[i])+" "+str(temp) break l = map(int,raw_input().split()) sum = input() s = set() for i in range(len(l)): s.add(l[i]) find_sum_pair(l,sum,s)
#!/usr/bin/env python3 """Solution for: https://www.hackerrank.com/challenges/primsmstsub """ from collections import defaultdict, namedtuple from queue import PriorityQueue from typing import Dict, List Edge = namedtuple("Edge", ['weight', 'src', 'dest']) Graph = Dict[int, List[Edge]] def prims_mst(graph: Graph, start: int) -> List[Edge]: """Calculate the minimum spanning tree of a given graph.""" mst = [] visited = {0} edge_candidates = PriorityQueue() next_vertex = start for _ in range(len(graph) - 1): visited.add(next_vertex) for edge in graph[next_vertex]: if edge.dest not in visited: edge_candidates.put(edge) candidate = edge_candidates.get() # type: Edge while candidate.dest in visited: candidate = edge_candidates.get() next_vertex = candidate.dest mst.append(candidate) return mst def main(): """Print the total weight of the smallest minimum spanning tree.""" n, m = [int(x) for x in input().split()] graph = defaultdict(list) for _ in range(m): v1, v2, w = [int(x) for x in input().split()] # type: Edge graph[v1].append(Edge(src=v1, dest=v2, weight=w)) graph[v2].append(Edge(src=v2, dest=v1, weight=w)) start = int(input().strip()) print(sum(x.weight for x in prims_mst(graph, start))) if __name__ == '__main__': main()
#!/usr/bin/env python3 """Solution for: https://www.hackerrank.com/contests/gs-codesprint/challenges/buy-maximum-stocks""" from collections import namedtuple from typing import List Stock = namedtuple('Stock', ['price', 'count']) def buy_max_stocks(dollars: int, stock_prices: List[int]) -> int: """Calculate ...""" max_stocks = 0 stocks = [] for i, stock_price in enumerate(stock_prices, start=1): stocks.append(Stock(stock_price, i)) sorted_stocks = sorted(stocks, key=lambda x: x.price) for stock in sorted_stocks: if stock.price > dollars: break stock_amount = min(dollars // stock.price, stock.count) max_stocks += stock_amount dollars -= stock.price * stock_amount return max_stocks def main(): """Print ...""" input() stock_prices = [int(x) for x in input().split()] dollars = int(input()) result = buy_max_stocks(dollars, stock_prices) print(result) if __name__ == '__main__': main()
import sys import os def is_leap(year): leap = False # Write your logic here # By doing year and modulo 4, it will check if it evenly divides by 4 # At the same time, it will check if it evenly divides by 400. # An or comparison statement is in place incase if a year is does not evenly # divide by 100 and returns a remainder. If so, then it is not a leap year. return year % 4 == 0 and (year % 400 == 0 or year % 100 != 0) return leap # inputtted year is 1990 and going through the statement, it returns a remainder # Thus, the output will print out false since it does not evenly divide by 100 year = int(raw_input()) print is_leap(year)
#METODO DE LA BISECCIÓN import numpy as np import matplotlib.pyplot as plt from math import* def f(x): return x+cos(x) def biseccion(a,b,tol): m=a c=b k=0 if(f(a)*f(b)>0): print("\nLa función no cambia de signo") print() while(abs(m-c)>tol): m=c c=(a+b)/2 if(f(a)*f(c)<0): b=c if(f(c)*f(b)<0): a=c print("El intervalo es: [",a,"",b,"]") k=k+1 print() print("El resultado de la raiz es: ") print("x",k,"=",c,"aproximacion resultante de la raiz") biseccion(-2,0,10**(-4))
print('今、何歳?') age = int(input('you > ')) print('初恋はいくつのときだった?') first_love = int(input('you > ')) print('あれから' + str(age - first_love) + '年経ったね')
import bisect import random SIZE = 7 random.seed(1729) my_list = [] ''' bisect is a library that calculates insertion index when adding a certain value to any list. bisect is as same as bitsect_right. ''' print('---< bisect.insort >---') for i in range(SIZE): new_item = random.randrange(SIZE*2) bisect.insort(my_list, new_item) print('%2d ->' % new_item, my_list) print() print ('---< bisect.bisect() >---') A = [1, 2, 3, 3, 3, 4, 4, 6, 6, 6, 6] x = 5 print ('A = {0}, x = {1}'.format(A, x)) print ('bitsect.bisect_left(A, x) = insert position:{0}'.format(bisect.bisect_left(A, x))) print() B = [0, 2, 2, 5, 5, 5, 8, 8, 11, 15, 18] y = 11 print ('B = {0}, y = {1}'.format(B, y)) print ('bitsect.bisect_left(B, x) = insert position:{0}'.format(bisect.bisect_left(B, y))) print ('bitsect.bisect_right(B, x) = insert position:{0}'.format(bisect.bisect_right(B, y))) print ('bitsect.bisect(B, x) = insert position:{0}'.format(bisect.bisect(B, y))) print() ''' insort is a library that calculates the insertion index when adding a value to an arbitrary list, and sends it to the insertion operation. insort is as same as insort_right. ''' print ('---< bisect.insort() >---') C = [] z = 4 for i in range(10): C.append(i) print ('C = {0}, z = {1}'.format(C, z)) print ('bitsect.insort_left(B, x) = insert position:{0}'.format(bisect.insort_left(C, z))) print() print ('C = {0}, z = {1}'.format(C, z)) print ('bitsect.insort_right(B, x) = insert position:{0}'.format(bisect.insort_right(C, z))) print() print ('C = {0}, z = {1}'.format(C, z)) print ('bitsect.bisect(B, x) = insert position:{0}'.format(bisect.bisect(B, y))) print()
""" A multi-dimensional ``Vector`` class, take 3 """ from array import array import reprlib import math import numbers print(__doc__) class Vector: typecode = 'd' def __init__(self, components): self._components = array(self.typecode, components) def __iter__(self): return iter(self._components) def __repr__(self): components = reprlib.repr(self._components) components = components[components.find('['):-1] return 'Vector({})'.format(components) def __str__(self): return str(tuple(self)) def __bytes__(self): return (bytes([ord(self.typecode)]) + bytes(self._components)) def __eq__(self, other): return tuple(self) == tuple(other) def __abs__(self): return math.sqrt(sum(x * x for x in self)) def __bool__(self): return bool(abs(self)) def __len__(self): return len(self._components) def __getitem__(self, index): cls = type(self) if isinstance(index, slice): return cls(self._components[index]) elif isinstance(index, numbers.Integral): return self._components[index] else: msg = '{.__name__} indices must be integers' raise TypeError(msg.format(cls)) # BEGIN VECTOR_V3_GETATTR shortcut_names = 'xyzt' def __getattr__(self, name): cls = type(self) # <1> if len(name) == 1: # <2> pos = cls.shortcut_names.find(name) # <3> if 0 <= pos < len(self._components): # <4> return self._components[pos] msg = '{.__name__!r} object has no attribute {!r}' # <5> raise AttributeError(msg.format(cls, name)) # END VECTOR_V3_GETATTR # BEGIN VECTOR_V3_SETATTR def __setattr__(self, name, value): cls = type(self) if len(name) == 1: # <1> if name in cls.shortcut_names: # <2> error = 'readonly attribute {attr_name!r}' elif name.islower(): # <3> error = "can't set attributes 'a' to 'z' in {cls_name!r}" else: error = '' # <4> if error: # <5> msg = error.format(cls_name=cls.__name__, attr_name=name) raise AttributeError(msg) super().__setattr__(name, value) # <6> # END VECTOR_V3_SETATTR @classmethod def frombytes(cls, octets): typecode = chr(octets[0]) memv = memoryview(octets[1:]).cast(typecode) return cls(memv) # BEGIN VECTOR_DEMO: take_3 print ( '------------------------------------------------------------------------------------------------------------\n' ' A ``Vector`` is built from an iterable of numbers:: \n' '------------------------------------------------------------------------------------------------------------\n' ) print('Vector([3.1, 4.2]) = {0}\n'.format(Vector([3.1, 4.2]))) print('Vector((3, 4, 5)) = {0}\n'.format(Vector((3, 4, 5)))) print('Vector(range(10)) = {0}\n'.format(Vector(range(10)))) print ( '------------------------------------------------------------------------------------------------------------\n' ' Tests with 2-dimensions (same results as ``vector2d_v1.py``):: \n' '------------------------------------------------------------------------------------------------------------\n' ) v1 = Vector([3, 4]) x, y = v1 print('({0}, {1})\n'.format(x, y)) print('v1 = {0}\n'.format(v1)) v1_clone = eval(repr(v1)) print('v1 == v1_clone = {0}\n'.format(v1 == v1_clone)) print('v1 = {0}\n'.format(v1)) octets = bytes(v1) print('octets = \n{0}\n'.format(octets)) print('abs(v1) = {0}\n'.format(abs(v1))) print('({0}, {1})\n'.format(bool(v1), bool(Vector([0, 0])))) print ( '------------------------------------------------------------------------------------------------------------\n' ' Test of ``.frombytes()`` class method: \n' '------------------------------------------------------------------------------------------------------------\n' ) v1_clone = Vector.frombytes(bytes(v1)) print('v1_clone = {0}\n'.format(v1_clone)) print('v1 == v1_clone = {0}\n'.format(v1 == v1_clone)) print ( '------------------------------------------------------------------------------------------------------------\n' ' Tests with 3-dimensions:: \n' '------------------------------------------------------------------------------------------------------------\n' ) v1 = Vector([3, 4, 5]) x, y, z = v1 print('({0}, {1}, {2})\n'.format(x, y, z)) print('v1 = {0}\n'.format(v1)) v1_clone = eval(repr(v1)) print('v1 == v1_clone = {0}\n'.format(v1 == v1_clone)) print('v1 = {0}\n'.format(v1)) print('abs(v1) = {0}\n'.format(abs(v1))) # doctest:+ELLIPSIS print('({0}, {1})\n'.format(bool(v1), bool(Vector([0, 0, 0])))) print ( '------------------------------------------------------------------------------------------------------------\n' ' Tests with many dimensions:: \n' '------------------------------------------------------------------------------------------------------------\n' ) v7 = Vector(range(7)) print('v7 = {0}\n'.format(v7)) print('abs(v7) = {0}\n'.format(abs(v7))) # doctest:+ELLIPSIS print ( '------------------------------------------------------------------------------------------------------------\n' ' Test of ``.__bytes__`` and ``.frombytes()`` methods:: \n' '------------------------------------------------------------------------------------------------------------\n' ) v1 = Vector([3, 4, 5]) v1_clone = Vector.frombytes(bytes(v1)) print('v1_clone = {0}\n'.format(v1_clone)) print('v1 == v1_clone = {0}\n'.format(v1 == v1_clone)) print ( '------------------------------------------------------------------------------------------------------------\n' ' Tests of sequence behavior:: \n' '------------------------------------------------------------------------------------------------------------\n' ) v1 = Vector([3, 4, 5]) print('len(v1) = {0}\n'.format(len(v1))) print('({0}, {1}, {2})\n'.format(v1[0], v1[len(v1)-1], v1[-1])) print ( '------------------------------------------------------------------------------------------------------------\n' ' Test of slicing:: \n' '------------------------------------------------------------------------------------------------------------\n' ) v7 = Vector(range(7)) print('v7[-1] = {0}\n'.format(v7[-1])) print('v7[1:4] = {0}\n'.format(v7[1:4])) print('v7[-1:] = {0}\n'.format(v7[-1:])) try: print('v7[1,2] = {0}\n'.format(v7[1,2])) pass except Exception as ex: print(ex) pass finally: pass print ( '------------------------------------------------------------------------------------------------------------\n' ' Tests of dynamic attribute access:: \n' '------------------------------------------------------------------------------------------------------------\n' ) v7 = Vector(range(10)) print('v7.x = {0}\n'.format(v7.x)) print('({0}, {1}, {2})\n'.format(v7.y, v7.z, v7.t)) print ( '------------------------------------------------------------------------------------------------------------\n' ' Dynamic attribute lookup failures:: \n' '------------------------------------------------------------------------------------------------------------\n' ) try: print('v7.k = {0}\n'.format(v7.k)) pass except Exception as ex: print(ex) pass else: pass finally: pass v3 = Vector(range(3)) try: print('v3.t = {0}\n'.format(v3.t)) pass except Exception as ex: print(ex) pass finally: pass try: print('v3.spam = {0}\n'.format(v3.spam)) pass except Exception as ex: print(ex) pass finally: pass print ( '------------------------------------------------------------------------------------------------------------\n' ' Tests of preventing attributes from ''a'' to ''z'':: \n' '------------------------------------------------------------------------------------------------------------\n' ) try: v1.x = 7 pass except Exception as ex: print(ex) pass finally: pass try: v1.w = 7 pass except Exception as ex: print(ex) pass finally: pass print ( '------------------------------------------------------------------------------------------------------------\n' ' Other attributes can be set:: \n' '------------------------------------------------------------------------------------------------------------\n' ) v1.X = 'albatross' print('v1.X = {0}\n'.format(v1.X)) v1.ni = 'Ni!' print('v1.ni = {0}\n'.format(v1.ni)) # END VECTOR_DEMO: take_3
n1=int("22") n2=int("17") n3=int("56") if(n1>n2)and(n1>n3): largest number=1 elif(n2>n1)and(n2>n3): largest number=2 else(n3): largest number=3 print("largest number")
# Time Complexity: O(N) +O(M) where O(N) time taken to traverse left side of array and O(M) is time taken to traverse right side of array # Space Complexity: O(1) as Output array result is not considered as extra space in single array calculation is done class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ result = [] result.append(1) main = 1 i = 1 while i < len(nums): main = nums[i-1]*main result.append(main) i+=1 j = len(nums)-2 main = 1 while j>=0: main = nums[j+1]*main result[j] = result[j]*main j-=1 return result
""" PRACTICE Test 3. This problem provides practice at: *** LOOPS WITHIN LOOPS, SEQUENCES and MUTATION *** Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder, their colleagues and Dave Fisher. """ # TO DO: 1. PUT YOUR NAME IN THE ABOVE LINE. def main(): """ Calls the TEST functions in this module. """ run_test_zero_changer() ######################################################################## # Students: # # These problems have DIFFICULTY and TIME ratings: # DIFFICULTY rating: 1 to 10, where: # 1 is very easy # 3 is an "easy" Test 2 question. # 5 is a "typical" Test 2 question. # 7 is a "hard" Test 2 question. # 10 is an EXTREMELY hard problem (too hard for a real test question) # # TIME ratings: A ROUGH estimate of the number of minutes that we # would expect a well-prepared student to take on the problem. # # IMPORTANT: For ALL the problems in this module, # if you reach the time estimate and are NOT close to a solution, # STOP working on that problem and ASK YOUR INSTRUCTOR FOR HELP # on it, in class or via Piazza. ######################################################################## def run_test_zero_changer(): """ Tests the zero_changer function. """ # ------------------------------------------------------------------ # TODO: 2. Write tests for the zero_changer function. # Include as many tests as required to give you confidence # that your implementation of zero_changer is correct. # # IMPORTANT: GET SOMEONE RELIABLE (like your instructor or a # course assistant) to confirm that your TESTS are CORRECT # and ADEQUATE. # ------------------------------------------------------------------ # ------------------------------------------------------------------ # DIFFICULTY AND TIME RATINGS (see top of this file for explanation) # DIFFICULTY: 7 # TIME ESTIMATE: 10 minutes. # ------------------------------------------------------------------ print() print('--------------------------------------------------') print('Testing the zero_changer function:') print('--------------------------------------------------') # Test 1: test1 = ([8, 4, 0, 9], [77, 0, 0, 1, 5, 0], [4, 4, 4], [4, 0, 4]) expected1 = ([8, 4, 1, 9], [77, 2, 3, 1, 5, 4], [4, 4, 4], [4, 5, 4]) zero_changer(test1) print() print('Test 1:') print(' Expected:', expected1) print(' Actual: ', test1) def zero_changer(tuple_of_lists): """ What comes in: A TUPLE of LISTs, where the interior lists contain only integers. What goes out: Nothing (i.e., none) Side effects: The argument is MUTATED so that: -- the 1st 0 in the given tuple of lists is changed to 1. -- the 2nd 0 in the given tuple of lists is changed to 2. -- the 3rd 0 in the given tuple of lists is changed to 3. etc. Example: If the given tuple of lists is: ([8, 4, 0, 9], [77, 0, 0, 1, 5, 0], [4, 4, 4], [4, 0, 4]) then AFTER this function is called with that tuple of lists, the tuple of lists has been MUTATED to: ([8, 4, 1, 9], [77, 2, 3, 1, 5, 4], [4, 4, 4], [4, 5, 4]) Note that: -- If there are no zeros in the given tuple of lists, then this function does nothing. -- After this function call, the tuple of lists IN THE CALLER should contain no zeros. """ # ------------------------------------------------------------------ # TODO: 3. Implement and test this function. # Note that you should write its TEST function first (above). # ------------------------------------------------------------------ # ------------------------------------------------------------------ # DIFFICULTY AND TIME RATINGS (see top of this file for explanation) # DIFFICULTY: 7 # TIME ESTIMATE: 10 minutes. # ------------------------------------------------------------------ next_replacement_value = 1 for l in tuple_of_lists: for k in range(len(l)): if l[k] == 0: l[k] = next_replacement_value next_replacement_value += 1 # ---------------------------------------------------------------------- # Calls main to start the ball rolling. # ---------------------------------------------------------------------- main()
""" Credit to : https://stackoverflow.com/a/7392364 """ class Bin(object): """ Container for items that keeps a running sum """ def __init__(self): self.items = [] self.sum = 0 def append(self, item): self.items.append(item) self.sum += item def __str__(self): """ Printable representation """ return 'Bin(sum=%d, items=%s)' % (self.sum, str(self.items)) def pack(values, maxValue): values = sorted(values, reverse=True) bins = [] for item in values: # Try to fit item into a bin for bin in bins: if bin.sum + item <= maxValue: #print 'Adding', item, 'to', bin bin.append(item) break else: # item didn't fit into any bin, start a new bin #print 'Making new bin for', item bin = Bin() bin.append(item) bins.append(bin) return bins if __name__ == '__main__': import random def packAndShow(aList, maxValue): """ Pack a list into bins and show the result """ print('List with sum', sum(aList), 'requires at least', (sum(aList) + maxValue - 1) / maxValue, 'bins') bins = pack(aList, maxValue) print('Solution using', len(bins), 'bins:') for bin in bins: print(bin) print aList = [ random.randint(1, 130) for i in range(50000) ] packAndShow(aList, 130)
""" generateMap.py This Python program loads a set of map-generation parameters from a given named module, and then generates a map using those parameters. This program is provided as an extended example of the "shapeToMap.py" program used in Chapter 4 of the book Python Geospatial Analysis. """ import os import mapnik import osgeo.ogr import osgeo.osr ############################################################################# # The following import statement should load a Python module containing the # map-generation parameters. The following global constants should be defined # in the imported module: # # BACKGROUND_COLOR # # A string containing an HTML color code to use as the background for # the entire map. # # OVERRIDE_MIN_LAT # OVERRIDE_MAX_LAT # OVERRIDE_MIN_LONG # OVERRIDE_MAX_LONG # # These constants define an override boundary to use for the map. If # these are set to None, the map will cover all the features in the # map's data sources. # # BOUNDS_FILTER # # If this is defined, it should be a dictionary mapping field names to # values. When calculating the boundary of the map, only those # features which have field values matching this filter will be # included. Note that this is only used if the various OVERRIDE_XXX # constants are set to None. # # BOUNDS_MARGIN # # If this is defined, it should be an angular distance (ie, a distance # measured as a lat/long value) that gets added to the bounds # calculated by the BOUNDS_FILTER parameter, above. This lets you # place a simple "margin" around the calculated bounds. # PRINT_BOUNDS # # If defined and True, the map generator will print the calculated # bounds to stdout. This can be usedful when setting up OVERRIDE_XXX # values for later use. # # LAYERS # # A list of layers to display on the map. Each list item should be a # dictionary with the following entries: # # 'sourceFile' # # The name of the file to get the layer's data from. If this # ends in ".shp", we will open a shapefile. Otherwise, we will # use OGR to load whatever data is in the file. # # 'layer' # # If defined, the name of a layer to pass to the OGR reader. # This only applies to non-shapefile data sources. # # 'filter' # # If defined, a string filtering the features to draw. # # 'lineColor' # # The HTML color code to use for drawing the lines, or None if # no lines are to be drawn. # # 'lineWidth' # # The width of the lines, in pixels. # # 'lineJoin' # # How to join the lines. One of: "miter", "round", "bevel". If # not defined, defaults to "miter". # # 'lineCap' # # How to cap the end of the lines. One of: "round", "butt" or # "square". If not defined, defaults to "round". # # 'lineDash' # # A line dash length, in pixels. If this is not defined, the # line will be drawn solid. # # 'fillColor' # # The HTML color code to use for filling the polygons, or None # if the polygons are not to be filled. # # 'labelField' # # The name of the field to display as a label, or None if no # labels are to be displayed. # # 'labelSize' # # The size of label's text, in points. This should be None if # the labels are not displayed. # # 'labelColor' # # The HTML color code to use for drawing the labels. This # should be None if the labels are not displayed. # # 'labelHalo' # # If defined, this should be a radius, in points, to draw a # white "halo" around the text. # # 'labelPlacement' # # How to place the label onto the feature. One of: "point" or # "line". If this is not defined, defaults to "point". # # 'labelAllowOverlap' # # If defined, this should be a boolean indicating whether or not # the label's text can overlap other laps. If this is not # defined the label overlap will be set to True. # # 'printAttrs' # # If defined and True, the data source's feature's attributes # will be printed to stdout. This is useful for figuring out # which field(s) to display on the map. from mapParams import * ############################################################################# # The maximum width and height of each map, in pixels. Note that the actual # width or height of each map is likely to be smaller than these maximum # values, depending on the map's aspect ratio. MAX_WIDTH = 1600 MAX_HEIGHT = 800 ############################################################################# def main(): """ Our main program. """ # Open up each layer's data source, remember the projection, and calculate # the overall boundary for all the displayed data that matches our bounds # filter. projections = [] minLong = None maxLong = None minLat = None maxLat = None try: boundsFilter = BOUNDS_FILTER except NameError: boundsFilter = {} for i in range(len(LAYERS)): src = LAYERS[i] print "Processing " + src['sourceFile'] + "..." shapefile = osgeo.ogr.Open(src['sourceFile']) layer = shapefile.GetLayer(0) spatialRef = layer.GetSpatialRef() if spatialRef != None: projection = spatialRef.ExportToProj4() else: if len(projections) > 0: projection = projections[0] else: spatialRef = osgeo.osr.SpatialReference() spatialRef.SetWellKnownGeogCS('WGS84') projection = spatialRef.ExportToProj4() for i in range(layer.GetFeatureCount()): feature = layer.GetFeature(i) matches = True for key,value in boundsFilter.items(): if feature.GetField(key) != value: matches = False break if not matches: continue if src.get("printAttrs") == True: print " " + repr(feature.items().items()) bounds = feature.GetGeometryRef().GetEnvelope() if minLong == None: minLong,maxLong,minLat,maxLat = bounds else: if bounds[0] < minLong: minLong = bounds[0] if bounds[1] > maxLong: maxLong = bounds[1] if bounds[2] < minLat: minLat = bounds[2] if bounds[3] > maxLat: maxLat = bounds[3] projections.append(projection) # Adjust the calculated bounds by the bounds margin, if any. try: minLong = minLong - BOUNDS_MARGIN maxLong = maxLong + BOUNDS_MARGIN minLat = minLat - BOUNDS_MARGIN maxLat = maxLat + BOUNDS_MARGIN except NameError: pass # If we've been asked to do so, print out the calculated bounds. try: if PRINT_BOUNDS: print "MIN_LAT = %0.4f" % minLat print "MAX_LAT = %0.4f" % maxLat print "MIN_LONG = %0.4f" % minLong print "MAX_LONG = %0.4f" % maxLong except NameError: pass # Calculate the size of the map image, based on the calculated boundaries. if OVERRIDE_MIN_LAT != None: minLat = OVERRIDE_MIN_LAT if OVERRIDE_MAX_LAT != None: maxLat = OVERRIDE_MAX_LAT if OVERRIDE_MIN_LONG != None: minLong = OVERRIDE_MIN_LONG if OVERRIDE_MAX_LONG != None: maxLong = OVERRIDE_MAX_LONG mapBounds = mapnik.Envelope(minLong, minLat, maxLong, maxLat) aspectRatio = mapBounds.width() / mapBounds.height() mapWidth = MAX_WIDTH mapHeight = int(mapWidth / aspectRatio) if mapHeight > MAX_HEIGHT: # Scale the map to fit. scaleFactor = float(MAX_HEIGHT) / float(mapHeight) mapWidth = int(mapWidth * scaleFactor) mapHeight = int(mapHeight * scaleFactor) # Create our map. m = mapnik.Map(mapWidth, mapHeight, projections[0]) m.background = mapnik.Color(BACKGROUND_COLOR) # Setup the stylesheets to show the contents of each shapefile. for i in range(len(LAYERS)): src = LAYERS[i] s = mapnik.Style() r = mapnik.Rule() if src.get("filter") != None: r.filter = mapnik.Filter(src['filter']) if src['fillColor'] != None: ps = mapnik.PolygonSymbolizer(mapnik.Color(src['fillColor'])) r.symbols.append(ps) if src['lineColor'] != None: stroke = mapnik.Stroke(mapnik.Color(src['lineColor']), src['lineWidth']) if src.get("lineJoin") == "miter": stroke.line_join = mapnik.line_join.MITER_JOIN elif src.get("lineJoin") == "round": stroke.line_join = mapnik.line_join.ROUND_JOIN elif src.get("linJoin") == "bevel": stroke.line_join = mapnik.line_join.BEVEL_JOIN if src.get("lineCap") == "round": stroke.line_cap = mapnik.line_cap.ROUND_CAP elif src.get("lineCap") == "square": stroke.line_cap = mapnik.line_cap.SQUARE_CAP elif src.get("lineCap") == "butt": stroke.line_cap = mapnik.line_cap.BUTT_CAP if src.get("lineDash") != None: stroke.add_dash(src['lineDash'], src['lineDash']*2) ls = mapnik.LineSymbolizer(stroke) r.symbols.append(ls) if src['labelField'] != None: ts = mapnik.TextSymbolizer(mapnik.Expression("[" + src['labelField'] + "]"), "DejaVu Sans Bold", src['labelSize'], mapnik.Color(src['labelColor'])) if src.get("labelHalo") != None: ts.halo_radius = src['labelHalo'] if src.get("labelPlacement") == "line": ts.label_placement = mapnik.label_placement.LINE_PLACEMENT if src.get("labelAllowOverlap") != None: ts.allow_overlap = src['labelAllowOverlap'] else: ts.allow_overlap = True r.symbols.append(ts) s.rules.append(r) m.append_style("style-"+str(i+1), s) # Setup our various map layers. for i in range(len(LAYERS)): src = LAYERS[i] l = mapnik.Layer("layer-"+str(i+1), projections[i]) if src['sourceFile'].endswith(".shp"): l.datasource = mapnik.Shapefile(file=src['sourceFile']) else: l.datasource = mapnik.Ogr(file=src['sourceFile'], layer=src.get("layer")) l.styles.append("style-"+str(i+1)) m.layers.append(l) # Finally, render the map. m.zoom_to_box(mapBounds) mapnik.render_to_file(m, "map.png", "png") os.system("open map.png") ############################################################################# if __name__ == "__main__": main()
class TreeNode: def __init__(self, val): self.val = val self.left = self.right = None def print_level_order(root): h = _height(root) for i in range(1, h + 1): print_given_level(root, i) def print_given_level(root, level): if root is None: return elif level == 1: print(root.val, end=' ') else: print_given_level(root.left, level - 1) print_given_level(root.right, level - 1) # Compute the height of tree def _height(node): if node is None: return 0 else: left_height = _height(node.left) right_height = _height(node.right) if left_height > right_height: return left_height + 1 else: return right_height + 1 # 1 # / \ # 2 3 # / / \ # 4 2 4 # / # 4 root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.right.left = TreeNode(2) root.right.right = TreeNode(4) root.right.left.left = TreeNode(4) height = _height(root) print(height) print_level_order(root)
import collections """ Shortest Word Distance For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. Given word1 = "coding", word2 = "practice", return 3. Given word1 = "makes", word2 = "coding", return 1. """ class Solution: def distance(self, input, word1, word2): dict = collections.defaultdict(list) for index in range(len(input)): dict[input[index]].append(index) print(dict) list1 = dict[word1] if word1 in dict else [] list2 = dict[word2] if word2 in dict else [] print(list1, list2) """ Smallest Difference pair of values between two sorted Arrays """ min = float('inf') i = 0 j = 0 while i < len(list1) and j < len(list2): if min >= abs(list1[i] - list2[j]): min = abs(list1[i] - list2[j]) if list1[i] >= list2[j]: j += 1 else: i += 1 print(min) input = ["practice", "makes", "perfect", "coding", "makes"] word1 = "makes" word2 = "makes" Sol = Solution() Sol.distance(input, word1, word2)
from algos import STRATEGIES from algos.searching import UNSUCCESSFUL def iinterpolation_search(arr, target): """Iterative implementation of interpolation search. :param arr: input list :param target: search item :return: index of item if found `-1` otherwise """ result = UNSUCCESSFUL length = len(arr) #: find indexes of two corners low = 0 high = (length - 1) #: since array is sorted, an element present in array must be in range defined by corner while low <= high and arr[high] >= target >= arr[low]: if low == high: if arr[low] == target: result = low break #: probing the position with keeping uniform distribution in mind. position = low + int(((float(high - low) / (arr[high] - arr[low])) * (target - arr[low]))) if arr[position] == target: #: target found result = position break if arr[position] < target: #: if target is larger, target is in upper part low = position + 1 else: #: if target is smaller, target is in lower part high = position - 1 return result def rinterpolation_search(arr, target, low=0, high=None): """Recursive implementation of interpolation search. :param arr: input list :param target: search item :param low: left most item :param high: right most item :return: index of item if found `-1` otherwise """ result = UNSUCCESSFUL length = len(arr) #: find indexes of two corners high = length - 1 if high is None else high if low <= high: #: probing the position with keeping uniform distribution in mind. position = low + int(((float(high - low) / (arr[high] - arr[low])) * (target - arr[low]))) #: check position is not out of range if position < length: #: if target is larger, target is in upper part if arr[position] < target: result = rinterpolation_search(arr, target, low=position + 1, high=high) #: if target is smaller, target is in lower part elif arr[position] > target: result = rinterpolation_search(arr, target, low=low, high=position - 1) #: target found else: result = position return result STRATEGY_MAP = { STRATEGIES.ITERATIVE: iinterpolation_search, STRATEGIES.RECURSIVE: rinterpolation_search } def interpolation_search(arr, target, strategy=STRATEGIES.ITERATIVE): return STRATEGY_MAP.get(strategy, iinterpolation_search)(arr, target)
from algos import STRATEGIES from algos.sorting import ASCENDING, GREATER_THAN, SORTING_OPERATORS def iinsertion_sort(arr, order=ASCENDING): """Iterative implementation of insertion sort. :param arr: input list :param order: sorting order i.e "asc" or "desc" :return: list sorted in the order defined """ operator = SORTING_OPERATORS.get(order.lower(), GREATER_THAN) for i in range(1, len(arr)): position = i - 1 value = arr[i] while position >= 0 and operator(arr[position], value): arr[position + 1] = arr[position] position -= 1 arr[position + 1] = value return arr def rinsertion_sort(arr, order=ASCENDING, position=1): """Recursive implementation of heap sort. :param arr: input list :param order: sorting order i.e "asc" or "desc" :param position: sorting position :return: list sorted in the order defined """ value = arr[position] operator = SORTING_OPERATORS.get(order.lower(), GREATER_THAN) while position > 0 and operator(arr[position - 1], value): arr[position] = arr[position - 1] position -= 1 arr[position] = value if position < len(arr) - 1: rinsertion_sort(arr, order=order, position=position + 1) return arr STRATEGY_MAP = { STRATEGIES.ITERATIVE: iinsertion_sort, STRATEGIES.RECURSIVE: rinsertion_sort } def insertion_sort(arr, order=ASCENDING, strategy=STRATEGIES.ITERATIVE): return STRATEGY_MAP.get(strategy, insertion_sort)(arr=arr, order=order)
from algos import STRATEGIES from algos.searching.binary_search.search import binary_search def exponential_search(arr, target, strategy=STRATEGIES.ITERATIVE): """Implementation of exponential search. :param arr: input list :param target: search item :param strategy: search strategy i.e "iterative" or "recursive" :return: index of item if found `-1` otherwise """ length = len(arr) #: find range for binary search j by repeated doubling i = 1 while i < length and arr[i] <= target: i = i * 2 #: call binary search for the found range return binary_search(arr, target=target, left=i//2, right=min(i, length - 1), strategy=strategy)
days = "Mon Tue Wed Thus Fri Sat Sun" months = "Jan\n Feb\n Mar\n Apr\n May\n Jun\n Jul\n Aug\n Sep\n Oct\n Nov\n Dec\n" print "Here are days: ", days print "Here are months: ", months print """ There's something going on here. With three double quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6 """
file_name_input = raw_input("Please enter file path: ") file_name = open(file_name_input) def print_all(file_name_in): print file_name_in.read() def revind(file_name_in): file_name_in.seek(0) def print_a_line(line_number,file_name_in): print line_number,file_name_in.readline() print_all(file_name) revind(file_name) current_line = 1 print_a_line(current_line,file_name) current_line += 1 print_a_line(current_line,file_name) current_line += 1 print_a_line(current_line,file_name) file_name.close()
__author__ = 'chris' """ Lab 16, Objective 1: This project tests your understanding of analyzing the structure of code, and your ability to mercilessly refactor. 1. Create a new Python source file named refactory.py. 2. Copy the code below into the refactory.py file. 3. Run the program. If you copied it correctly, no errors will occur. The program works, but the code is less than Pythonic. 4. Refactor the code mercilessly to be leaner and easier to understand. The example includes a lot of unnecessary code, some of which is difficult to understand, and individual lines of code are not documented. 5. Make sure all tests pass. There is no example of possible output from running the program, because successful tests are silent so nothing should be displayed. Here's the refactory.py code:""" small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') def book_title(title): """ Takes a string and returns a title-case string. All words EXCEPT for small words are made title case unless the string starts with a preposition, in which case the word is correctly capitalized. >>> book_title('DIVE Into python') 'Dive into Python' >>> book_title('the great gatsby') 'The Great Gatsby' >>> book_title('the WORKS OF AleXANDer dumas') 'The Works of Alexander Dumas' """ lst_of_words = title.lower().title().split() if len(lst_of_words) < 1: return '' for index, word in enumerate(lst_of_words): #checks if word is a preposition and not at the #beginning of the string if word.lower() in small_words and index != 0: lst_of_words[index] = word.lower() return ' '.join(lst_of_words) def _test(): import doctest, refactory return doctest.testmod(refactory) if __name__ == "__main__": _test()
__author__ = 'chris' #Python 1: Lesson 4: Iteration: For and While Loops """Program to locate the first space in the input string.""" s = input("Enter any string: ") pos = 0 for c in s: if c == " ": print("First space occurred at position ", pos) break pos += 1 else: #Python loops come with such extra logic built in, in the shape of the optional else clause. This clause is placed # at the same indentation level as the for or while loop that it matches, and (just as with the if statement) is # followed by an indented suite of one or more statements. This suite is only executed if the loop terminates # normally. # If the loop ends because a break statement is executed, then the interpreter just skips over the else suite. print("No spaces in that string ")
__author__ = 'chris' """ Lab 12, Objective 1: This project tests your ability to use modules and imports. 1.Create a new Python source file named guessing_game.py. 2.Import the random module. 3.Use the help() function on the random module to determine how to generate a random number between 1 and 99 inclusive. 4.Generate a random number between 1 and 99 and store it in a variable. 5.Use a while loop to accept integers from the user (don't forget--you'll need to convert the input string). 6.Compare the user's guess with the saved random number. 7.If the user successfully guesses the target number, inform them and terminate the program. 8.Otherwise, inform the user whether their guess was higher or lower than the saved random number and loop around to allow them to guess again. Below is an example of possible output from running the program. Guess a number: 25 Too low Guess a number: 75 Too high Guess a number: 60 Too high Guess a number: 45 Too low Guess a number: 53 You guessed it! """ import random #generating random number between 1 and 99 numberToGuess = random.randint(0,99) print("Random Number to guess: {0}".format(numberToGuess)) while True: inp = int(input("Guess a number: ")) if not inp: break if inp > numberToGuess: print("Too high") if inp < numberToGuess: print("Too low") if inp == numberToGuess: print("You guessed it!") break
__author__ = 'chris' """Write a GUI-based program that provides two Entry fields, a button and a label. When the button is clicked, the value of each Entry should (if possible) be converted into a float. If both conversions succeed, the label should change to the sum of the two numbers. Otherwise it should read "***ERROR***".""" from tkinter import * class Application(Frame): def __init__(self, master=None): """Main frame initialisation""" Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): top_frame = Frame(self) self.float_entry1 = Entry(top_frame) self.float_entry2 = Entry(top_frame) self.float_entry1.pack() self.float_entry2.pack() top_frame.pack() bottom_frame = Frame(self) bottom_frame.pack(side=TOP) self.convertButton = Button(bottom_frame, text="Convert", command=self.convert) self.convertButton.pack(side=TOP) self.label = Label(bottom_frame, text="Output") self.label.pack(side=BOTTOM) def convert(self): try: value_1 = float(self.float_entry1.get()) value_2 = float(self.float_entry2.get()) output = value_1 + value_2 except ValueError: output = "***ERROR***" self.label.config(text=output) root = Tk() app = Application(master=root) app.mainloop()
__author__ = 'chris' #Pyton 1: Lesson 4: Lab 4, Quiz 1 """Create a new Python source file named guess.py. Write a program that uses a while loop to ask the user to guess a number. Each guess should be checked against a number stored in the "secret" variable, to which a value between 1 and 20 should be assigned at the start. Otherwise it should report whether the guess was higher or lower than the secret. If the user guesses correctly, the loop should terminate. The loop should also keep a count of the user's guesses, and should terminate if the user makes five incorrect guesses. After the loop is over, the program should print a message if the user guessed the number correctly.""" #random — Generate pseudo-random numbers, should not be used for security purposes from random import randrange secret = randrange(1, 20) #Integer from 1 to 20 print("Chosen secret", secret) secretFound = False; attempt = 0 while (not secretFound and attempt < 5): attempt += 1 guess = int(input("Guess a number: ")) if guess == secret: secretFound = True elif guess < secret: print("Guess higher") elif guess > secret: print("Guess lower") if secretFound: print("Correct! Well done, the number was", guess) else: print("Sorry, the number was", secret)
import random name = input("give me everybody's name spearated by coma") names = name.split(" , ") num_items = len(names) random.randint = len(names) random_choice = random.randint(0, num_items - 1) person_will_pay = names[random_choice] print((person_will_pay + "is going to buy meal today"))
List1 = [ "Vishu",5,10,2,"Mansi"] for items in List1: if str(items).isnumeric() and items>6: print(items)
from coding import encoding class Client: def __init__(self, login, psswd): self.login = login self.psswd = encoding(psswd) def __str__(self): return self.login def __gt__(self, obj): return self.login > obj.login def __eq__(self, obj): return self.login == obj.login def check_psswd(self, psswd): return self.psswd == encoding(psswd) def get_name(self): return self.login def to_login(self): print(f"Клиент {self.login} вошёл") if __name__ == "__main__": c1 = Client(12, "11032004") c2 = Client(2, "11032004") print(c1 == c2) print(c1 > c2) print(c1 < c2) print() print() print()
###################### ## Merge Sort ## ###################### data = list(map(int, open("input.txt","r").read().split(" "))) n = len(data) print(data) def Merge(A,p,q,r): n1 = q-p+1 n2 = r-q L = [] R = [] for i in range(1,n1+1): L.append(A[p+i-1]) for j in range(1,n2+1): R.append(A[q+j]) L.append(n+1) R.append(n+1) i=0 j=0 for k in range(p,r+1): if L[i]<=R[j]: A[k] = L[i] i = i+1 else: A[k] = R[j] j = j+1 def MergeSort(A,p,r): if p<r: q=int((p+r)/2) MergeSort(A,p,q) MergeSort(A,q+1,r) Merge(A,p,q,r) MergeSort(data,0,n-1) print(data)
#!/usr/bin/env python3 import json import yaml from sys import argv from os import path if len(argv) < 2: print("You have to provide a path to the file you want to convert. Exiting.") elif not path.isfile(argv[1]): print(f"File {argv[1]} doesn't exist. Exiting.") else: file_path = argv[1] try: with open(file_path) as f: data = json.load(f) print("Got JSON, Exporting as YAML...") output_file = f"{file_path.split('.')[0]}.yml" with open(output_file, "w") as o: yaml.dump(data, o) except json.JSONDecodeError as e: print(f"Error: {e.msg} at line {e.lineno}") print("Failed to import JSON, will try YAML next...") try: with open(file_path) as f: data = yaml.safe_load(f) print("Got YAML, Exporting as JSON...") output_file = f"{file_path.split('.')[0]}.json" with open(output_file, "w") as o: json.dump(data, o, indent=4) except yaml.parser.ParserError as e: print(f"Error: {e.problem} at line {e.problem_mark.line}") print( "Failed to import file. Check if the file is valid JSON or YAML. Exiting.")
class Tree: def __init__(self, name="root", children=None): self.name = name self.children = [] if children is not None: for child in children: self.add_child(child) def __repr__(self): return self.name + (str(self.children) if self.children else "") def add_child(self, node): assert isinstance(node, Tree) self.children.append(node) def parse(expr): """ Parse layout expression into a tree structure. | split vertically / split horizontally ex. parse("A|B") "|" / \ A B ex. parse("A|(B/C)") "|" / \ A "/" / \ B C """ tree, _ = parse_tree(expr) return tree def parse_tree(expr, start_from=0, left_parentheses=False): node = Tree() s_ptr = start_from curr_name = "" expect_rhs = False while s_ptr < len(expr): s = expr[s_ptr] if s.isalpha(): expect_rhs = False curr_name += s else: if curr_name: node.add_child(Tree(curr_name)) curr_name = "" if s == "|" or s == "/": if node.name == "root" or node.name == s: expect_rhs = True node.name = s else: raise Exception("ambigious") elif s == "(": expect_rhs = False subtree, s_ptr = parse_tree( expr, start_from=s_ptr + 1, left_parentheses=True ) node.add_child(subtree) elif s == ")": if left_parentheses: left_parentheses = False break else: raise Exception("where is left parentheses") s_ptr += 1 if left_parentheses: raise Exception("where is right parentheses") if expect_rhs: raise Exception("got not rhs") if curr_name: node.add_child(Tree(curr_name)) if node.name == "root" and len(node.children) == 1: node = node.children[0] return node, s_ptr
#Escriba el codigo necesario para que al ejecutar #python ejercicio1.py se impriman los enteros del 10 al 1 en cuenta regresiva. import numpy as np nume=10 for i in range(0,nume+1): print(nume-i) print("Hasta la vista, Baby")
from tkinter import * # allows the use of the UI # importing global variables label_text = '' not_breaking_equals = False not_breaking_equals_2 = False root = Tk() label_equals = '' # defining what happens when you press the one button def one(): # importing global variables global label_text global not_breaking_equals_2 global label_equals # list used for an if statement delete_list = list(label_text) # If equals was the last button pressed the user cannot enter numbers as there is a number present if not_breaking_equals == False: # so it doesn't expand the application if len(delete_list) <= 17: if not_breaking_equals_2 == True: # redefining variables used for the display label_text = '' label_equals = '' not_breaking_equals_2 = False # redefining variables used for the display label_text = str(label_text + "1") label_equals = str(label_equals + "1") # outputting the display so the user can see the number they inputed output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) # defining the two button, all numbers have the same code apart from the number so look at 1 to see what it does def two(): global label_text global not_breaking_equals_2 global label_equals delete_list = list(label_text) if not_breaking_equals == False: if len(delete_list) <= 17: if not_breaking_equals_2 == True: label_text = '' label_equals = '' not_breaking_equals_2 = False label_text = str(label_text + "2") label_equals = str(label_equals + "2") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) def three(): global label_text global not_breaking_equals_2 global label_equals delete_list = list(label_text) if not_breaking_equals == False: if len(delete_list) <= 17: if not_breaking_equals_2 == True: label_text = '' label_equals = '' not_breaking_equals_2 = False label_text = str(label_text + "3") label_equals = str(label_equals + "3") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) def four(): global label_text global not_breaking_equals_2 global label_equals delete_list = list(label_text) if not_breaking_equals == False: if len(delete_list) <= 17: if not_breaking_equals_2 == True: label_text = '' label_equals = '' not_breaking_equals_2 = False label_text = str(label_text + "4") label_equals = str(label_equals + "4") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) def five(): global label_text global not_breaking_equals_2 global label_equals delete_list = list(label_text) if not_breaking_equals == False: if len(delete_list) <= 17: if not_breaking_equals_2 == True: label_text = '' label_equals = '' not_breaking_equals_2 = False label_text = str(label_text + "5") label_equals = str(label_equals + "5") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) def six(): global label_text global not_breaking_equals_2 global label_equals delete_list = list(label_text) if not_breaking_equals == False: if len(delete_list) <= 17: if not_breaking_equals_2 == True: label_text = '' label_equals = '' not_breaking_equals_2 = False label_text = str(label_text + "6") label_equals = str(label_equals + "6") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) def seven(): global label_text global not_breaking_equals_2 global label_equals delete_list = list(label_text) if not_breaking_equals == False: if len(delete_list) <= 17: if not_breaking_equals_2 == True: label_text = '' label_equals = '' not_breaking_equals_2 = False label_text = str(label_text + "7") label_equals = str(label_equals + "7") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) def eight(): global label_text global not_breaking_equals_2 global label_equals delete_list = list(label_text) if not_breaking_equals == False: if len(delete_list) <= 17: if not_breaking_equals_2 == True: label_text = '' label_equals = '' not_breaking_equals_2 = False label_text = str(label_text + "8") label_equals = str(label_equals + "8") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) def nine(): global label_text global not_breaking_equals_2 global label_equals delete_list = list(label_text) if not_breaking_equals == False: if len(delete_list) <= 17: if not_breaking_equals_2 == True: label_text = '' label_equals = '' not_breaking_equals_2 = False label_text = str(label_text + "9") label_equals = str(label_equals + "9") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) def zero(): global label_text global not_breaking_equals_2 global label_equals delete_list = list(label_text) if not_breaking_equals == False: if len(delete_list) <= 17: if not_breaking_equals_2 == True: label_text = '' label_equals = '' not_breaking_equals_2 = False label_text = str(label_text + "0") label_equals = str(label_equals + "0") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) def decimal(): global label_text global not_breaking_equals_2 global label_equals # jump is used if the code meets the requirements given to save some lines of coding jump = 0 # making all the functions ! for easy list making delete_list = label_text.replace('/','!') delete_list = delete_list.replace('*','!') delete_list = delete_list.replace('-','!') delete_list = delete_list.replace('+','!') delete_list = delete_list.split('!') decimal_check = delete_list[len(delete_list)-1] # same as with the numbers if not_breaking_equals_2 == True: label_text = '' label_equals = '' label_text = str(label_text + ".") label_equals = str(label_equals + ".") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) not_breaking_equals_2 = False # if the last number after the function is blank a decimal point may be placed if delete_list[len(delete_list)-1] == '': label_text = str(label_text + ".") label_equals = str(label_equals + ".") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) # checking if there is already a decimal point in that number for x in decimal_check: if x == '.': error = True else: if '.' in delete_list[len(delete_list)-1]: error = True if '.' not in delete_list[len(delete_list)-1]: if not_breaking_equals == False: if len(label_text) <= 17: if len(label_text) == 0: jump = 1 # making sure the previous input isn't . elif '.' != label_text[-1]: jump = 1 # goes to this if requirements are met if jump == 1: label_text = str(label_text + ".") label_equals = str(label_equals + ".") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) def multiply(): global label_text global not_breaking_equals global not_breaking_equals_2 global label_equals # splits the variable for easy manipulation delete_list = label_equals.split(' ') if delete_list[-1] == '0': label_text = ''.join(delete_list) # used to solve numbers with leading 0s elif delete_list[-1] != '': delete_list[-1] = delete_list[-1].lstrip('0') if delete_list[-1] == '': delete_list[-1] = '0' label_text = ''.join(delete_list) label_equals = label_text delete_list = list(label_text) if not_breaking_equals_2 == True: error = True elif len(delete_list) <= 17 and len(delete_list) != 0: if delete_list[-1] != '*' and delete_list[-1] != '/' and delete_list[-1] != '+' and delete_list[-1] != '-' and delete_list[-1] != '.': label_equals = str(label_text + '* ') label_text = str(label_text + "*") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) not_breaking_equals = False def divide(): global label_text global not_breaking_equals global not_breaking_equals_2 global label_equals delete_list = label_equals.split(' ') if delete_list[-1] == '0': label_text = ''.join(delete_list) elif delete_list[-1] != '': delete_list[-1] = delete_list[-1].lstrip('0') if delete_list[-1] == '': delete_list[-1] = '0' label_text = ''.join(delete_list) label_equals = label_text delete_list = list(label_text) if not_breaking_equals_2 == True: error = True elif len(delete_list) <= 17 and len(delete_list) != 0: if delete_list[-1] != '*' and delete_list[-1] != '/' and delete_list[-1] != '+' and delete_list[-1] != '-' and delete_list[-1] != '.': label_equals = str(label_text + '/ ') label_text = str(label_text + "/") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) # allows numbers to be placed afterwards if equals has been pressed not_breaking_equals = False def plus(): # you can start the input with a plus as my stakeholder and I decided it would be best so an error wouldn't pop up # if someone was to do so. You can't place a plus after a multiplication or divide as we decided that it looks a bit # weird and didn't want to confuse those using it. global label_text global not_breaking_equals global not_breaking_equals_2 global label_equals delete_list = label_equals.split(' ') if delete_list[-1] == '0': label_text = ''.join(delete_list) elif delete_list[-1] != '': delete_list[-1] = delete_list[-1].lstrip('0') if delete_list[-1] == '': delete_list[-1] = '0' label_text = ''.join(delete_list) label_equals = label_text delete_list = list(label_text) if not_breaking_equals_2 == True: label_text = '' label_equals = '' # symbols add a space after the symbol in the label_equals as we can then split it into a list without changing # any part of the code label_equals = str(label_text + '+ ') label_text = str(label_text + "+") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) not_breaking_equals_2 = False elif len(delete_list) <= 17: if len(delete_list) == 0: label_equals = str(label_text + '+ ') label_text = str(label_text + "+") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) # so you can't place one after a symbol elif delete_list[-1] != '*' and delete_list[-1] != '/' and delete_list[-1] != '+' and delete_list[-1] != '.' and delete_list[-1] != '-': label_equals = str(label_text + '+ ') label_text = str(label_text + "+") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) not_breaking_equals = False def subtract(): global label_text global not_breaking_equals global not_breaking_equals_2 global label_equals delete_list = label_equals.split(' ') if delete_list[-1] == '0': label_text = ''.join(delete_list) elif delete_list[-1] != '': delete_list[-1] = delete_list[-1].lstrip('0') if delete_list[-1] == '': delete_list[-1] = '0' label_text = ''.join(delete_list) label_equals = label_text delete_list = list(label_text) if not_breaking_equals_2 == True: label_text = '' label_equals = '' label_equals = str(label_text + '- ') label_text = str(label_text + "-") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) not_breaking_equals_2 = False elif len(delete_list) <= 17: if len(delete_list) == 0: label_equals = str(label_text + '- ') label_text = str(label_text + "-") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) elif delete_list[-1] != '/' and delete_list[-1] != '.': label_equals = str(label_text + '- ') label_text = str(label_text + "-") output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) not_breaking_equals = False def AC(): global label_text global not_breaking_equals global not_breaking_equals_2 global label_equals label_text = str("") label_equals = str('') output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) not_breaking_equals = False def equals(): global label_text global not_breaking_equals global not_breaking_equals_2 global label_equals delete_list = label_equals.split(' ') # an error message if someone ends with an operator if delete_list[-1] == '' and delete_list[0] != delete_list[-1]: label_text = ''.join(delete_list) delete_list = ''.join(delete_list) output = Label(root, text="Missing number after operator", font=("Helvetica", "20"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) not_breaking_equals_2 = True # getting rid of leading zeros elif delete_list[-1] == '0': label_text = ''.join(delete_list) delete_list = ''.join(delete_list) else: delete_list[-1] = delete_list[-1].lstrip('0') if delete_list[-1] == '' and delete_list[0] != '': delete_list[-1] = '0' label_text = ''.join(delete_list) delete_list = ''.join(delete_list) label_equals = label_text # so you don't get an error by typing nothing if label_text == '': error = True elif delete_list[-1] == '-' or delete_list[-1] == '+' or delete_list[-1] == '*' or delete_list[-1] == '/' or delete_list[-1] == '.': error = True else: # try and except block incase they divide by zero try: label_text = str(eval(label_text)) label_equals = str(eval(label_text)) # making sure the number doesn't expand the screen if len(label_text) > 17: output = Label(root, text='number to big/small', font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) not_breaking_equals_2 = True else: output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) not_breaking_equals = True except ZeroDivisionError: output = Label(root, text="Can't divide by zero", font=("Helvetica", "20"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) not_breaking_equals_2 = True def delete(): global label_text global not_breaking_equals global label_equals label_equals = list(label_equals) if ''.join(label_equals) == '': error = True # so it deletes the symbol from label equals as well as label text elif str(label_equals[-1]) == ' ': del label_equals[-2] del label_equals[-1] elif len(label_equals) != 0: del label_equals[-1] label_equals = ''.join(label_equals) label_text = label_equals if str(label_text) == '': not_breaking_equals = False if not_breaking_equals_2 == False: output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") output.grid(row=0, column=0, columnspan=5, sticky=NSEW) not_breaking_equals = False # making buttons for grid layout buttons=Frame(root) buttons.grid(columnspan=5, rowspan=5, ipady=200, ipadx=210) # organising what the buttons look like on the UI and what happens when they click them output = Label(root, text=str(label_text), font=("Helvetica", "30"), bg="Gray20", fg="Gray85") one = Button(root, text="1", font=("Helvetica", "30"), bg="Gray20", fg="Gray85", command=one) two = Button(root, text="2", font=("Helvetica", "30"), bg="Gray20", fg="Gray85", command=two) three = Button(root, text="3", font=("Helvetica", "30"), bg="Gray20", fg="Gray85", command=three) four = Button(root, text="4", font=("Helvetica", "30"), bg="Gray20", fg="Gray85", command=four) five = Button(root, text="5", font=("Helvetica", "30"), bg="Gray20", fg="Gray85", command=five) six = Button(root, text="6", font=("Helvetica", "30"),bg="Gray20", fg="Gray85", command=six) seven = Button(root, text="7", font=("Helvetica", "30"), bg="Gray20", fg="Gray85", command=seven) eight = Button(root, text="8", font=("Helvetica", "30"), bg="Gray20", fg="Gray85", command=eight) nine = Button(root, text="9", font=("Helvetica", "30"), bg="Gray20", fg="Gray85", command=nine) zero = Button(root, text="0", font=("Helvetica", "30"), bg="Gray20", fg="Gray85", command=zero) multiply = Button(root, text="*", font=("Helvetica", "30"), bg="Gray80", fg="Gray20", command=multiply) divide = Button(root, text="/", font=("Helvetica", "30"), bg="Gray80", fg="Gray20", command=divide) plus = Button(root, text="+", font=("Helvetica", "30"), bg="Gray80", fg="Gray20", command=plus) subtract = Button(root, text="-", font=("Helvetica", "30"), bg="Gray80", fg="Gray20", command=subtract) equals = Button(root, text="=", font=("Helvetica", "30"), bg="Gray80", fg="Gray20", command=equals) AC = Button(root, text="AC", font=("Helvetica", "30"), bg="Gray80", fg="Gray20", command=AC) decimal = Button(root, text=".", font=("Helvetica", "30"), bg="Gray20", fg="Gray85", command=decimal) delete = Button(root, text="Del", font=("Helvetica", "30"), bg="Gray80", fg="Gray20", command=delete) # sorting out where the buttons appear in the window output.grid(row=0, column=0, columnspan=5, sticky=NSEW) one.grid(row=3, column=0, sticky=NSEW) two.grid(row=3, column=1, sticky=NSEW) three.grid(row=3, column=2, sticky=NSEW) four.grid(row=2, column=0, sticky=NSEW) five.grid(row=2, column=1, sticky=NSEW) six.grid(row=2, column=2, sticky=NSEW) seven.grid(row=1, column=0, sticky=NSEW) eight.grid(row=1, column=1, sticky=NSEW) nine.grid(row=1, column=2, sticky=NSEW) zero.grid(row=4, column=0, columnspan=2, sticky=NSEW) multiply.grid(row=3, column=3, sticky=NSEW) divide.grid(row=4, column=3, sticky=NSEW) plus.grid(row=1, column=3, sticky=NSEW) subtract.grid(row=2, column=3, sticky=NSEW) equals.grid(row=3, column=4, rowspan=2, sticky=NSEW) AC.grid(row=1, column=4, sticky=NSEW) decimal.grid(row=4, column=2, sticky=NSEW) delete.grid(row=2, column=4, sticky=NSEW) # Charles starts with a C so my stakeholder and I decided it would be a fitting calculator name to add personality root.title("Charles") # so you can't expand the window as all the buttons are a set size root.resizable(0,0) # runs the window root.mainloop()
d = {'name':'laowang','age':18} ''' d1 = {} ''' d2 = {} for k,v in d.items(): d[v]=k print(d) print(d2) ''' d1=([v,k] for k,v in d.items()) print(d) print(d1) '''
class Dog(): def __init__(self): self.name = '' self.__age = 0 def setAge(self,age): if age >15 and age < 1: print('不符和实际') else: self.__age = age def getAge(self): return self.__age ly = Dog() ly.setAge(12) print(ly.getAge())
def Tool(a,b,c): if c == '+': return a+b elif c == '-': return a-b elif c == '*': return a*b elif c == '/': if b != 0: return a/b else: print('输入有误') class Test(): pass
class Student(): count = 0 @staticmethod def listen(): print('上课学习') def __init__(self,name): self.name = name Student.count += 1 s1 = Student('小李') s2 = Student('小张') s3 = Student('小刘') print(Student.count)
s1 = set(input("Enter a set1").split()) s2 = set(input("Enter a set2").split()) if(s1.issuperset(s2) and len(s1)>len(s2)): print("Yes") else: print("No")
n = int(input("Enter no")) nums = list(input().split(" ")) for i in range(n): for j in range(n-1-i): if nums[j] > nums[j+1]: nums[i], nums[j]=nums[j], nums[i]; print(nums)
# d ={'x':1} d1 = {'y':3} result = filter(lambda s: 0 in s.items(),[d,d1]) print(list(result)) # # """ # It is better to return result because if we want to add element because we can add in empty and if we write None this will create an exception. # nums =[1,2,3,4,5,6,7] # Implementing filter # def my_filter(func,iter): # for item in iter: # res = func(item) # if res: # yield item # # even_nos = my_filter(lambda x:x%2==0,nums) # print(list(even_nos)) # op:[2,54,6] # # Implement map: # def my_map(func,iter): # for item in iter: # res = fun(item) # yield res # numbers = [1,2,3,4,5,6,7] # res = map(lambda x:x**2,numbers) # print(list(res)) # op:[1,4,9,16,25,36,49] # # Reduce function: # def sum(x,y): # return x+y # numbers = [1,2,3,4,5,6,7] # reduce()-->builtins.py mein nahi hain # it is located in module function tools so to use reduce func func tool import reduce # result = reduce(add,nums) # Implement a reduce: # """ # """from functools import reduce # words =["Happy","New","Year"] # result = reduce(lambda x,y:x+" "+y,words) # print(result) # r =[] # print(bool(r)) # Kwargs? # def func(param1,**kwargs): # print(kwargs) # # the type of keyword arguments is dictionary # func(name="xyz",rollno=5,sem ='iv) # op: # dictionary # If we want to add both args and kwargs # then we have to first pass args and then kwargs because position,keyword # """ # # """" # # """ # def mul(x,y): # return x*y # # def my_reduce (func,iter,initial=None): # count =0 # for val in iter: # if count==0 and initial == None: # res = val # count+=1 # elif count==0: # res = initial # count+=1 # res = func(res,val) # else: # res =func(res,val) # # # return res # #numbers = [2,2,3,4] # #result = my_reduce(mul, numbers,3) # #print(result) # # def mul(x,y): # return x*y # # # # def my_reduce(func,my_iter,initaliser): # # length = len(my_iter) # # iterable = iter(my_iter) # # element = my_iter # # while length != 0: # # if length == len(my_iter) and initaliser == None: # # element = next(iterable) # # elif length == len(my_iter) and initaliser: # # element = func(next(iterable), initaliser) # # else: # # element = func(next(iterable), element) # # length -= 1 # # return element # # # def my_reduce(func,my_iter,initialise=None): # iterable = iter(my_iter) # # element = my_iter # try: # if element is my_iter and initialise: # element = initialise # element = func(initialise, next(iterable)) if initialise else next(iterable) # # while True: # element = func(element,next(iterable)) # except : # pass # return element # # # numbers = {} # result = my_reduce(mul, numbers, ) # print(result) # # if initialiser: # # x = initialiser # # else: # # # # for i in range(len): # # # # x = func(x,next(iter)) # # # # """ # # # def my_reduce (add,iter,initial_val): # # res = initial_val # for val in iter: # res =add(res,val) # return res # # result = my_reduce(add, numbers,0) # print(result) # """
""" filter remove something and accept something "1 2 3 4 5 6" [1,2,3,4,5,6] numbers =[int(x) for x in input("enter nos").split()] int(x):act as map(for ke phele) numbers =[int(x) for x in input("eneter nos").split()filter if ] filter after for loop """ """ input ="1 2 3 4 5" string list of string even_numbers = [int(x)for x in input("Enter even numbers").split() if int(x)%2 ==0 #filter] print(even_numbers) 1.take list of integers as input and store the power(raise to 2)to each number powers = [int(num)**2for num in input("Enter a number").split()] print(powers) 2.sum of two list in another list first = [1,2,3,4,5] second = [2,4,5,6,7] z = [x+y for x in first for y in second] print (z) 2: words_in_set = set( input("Enter words").split()) words_in_list = input("Enter string").split() result =[x for x in words_in_list if x is not words_in_set] print(result) 3.Input a list of integers and print only odd nos number = [int(num) for num in input("enter odd nos").split()if int(num)%2!=0] print (number) 4.Take nos and do square of even nos and keep odd nos as it is l = [int(x) if int(x)%2!=0 else int(x)**2for x in input("Enter numbers").split()] print(l) 5:Do square of even numbers and discard odd nos l =[ int(x)**2 for x in input("Enter nos").split() if ( True if int(x)%2==0 else False)] print(l) 6:square of even and cube of odd l = [int(x)**3 if int(x)%2!=0 else int(x)**2for x in input("Enter numbers").split()] print(l) 7.vowels in string vowels = "aeiou"//instead of keeping string keep it in set forO(1)searching vowels={a,e,i,o,u} vowels_in_input =[x for x in input("Enter a string") if x in vowels) print(vowels_in_input) Tuple Unpacking x,y,z = val Tuple Packing x """ nums = (int(x) for x in input("Enter nos").split()) #generator generates only when required # GENERATES
main_string = input("Enter string") sub_string = input("ENter string") print(main_string.count(sub_string)) pos = 0 start = 0 count = 0 while pos !=-1: pos = main_string.find(sub_string,start) if(pos!=-1): count+=1 start=pos+len(sub_string) print(count)
initial = int(input("Enter initial range")) final = int(input("Enter final range")) if initial == 1: initial += 1 for i in range(initial,final+1): flag = True for j in range(2, i): if i % j == 0: flag = False break if flag: print(i)
"""z = "abc" dct = {"x":2,"y":4,"z":5} for x in dict.items(): print(x) x is tuple(key,pair) for x in dict: print(x) x would be keys print(dict[x])-->value list = ["hi","ok","Hm"] coll =dict(data) All are collections of length @2 first element becomes the Key Second element becomes the Value INput of dict: raw_data = input("enter data") food = {} for i in range (0,len(raw_data)): food[raw_data[i]] = raw_data[i+1] food = dict(x.split() fox in input("Enter name").split(",")) operations: dict1 = {"camel": 25,"cat:"26"} dict2{"camel":26,"cat":26} dict1.update(dict2) print(dict1) output: {"camel":26,"cat":26} update hojayegi value in dict1 None object can be hasable so can be key and value dict1 = {"None":5,"None":20} so it woill give the updated value {"None":20} setdefault: dict1 = {"camel": 25,"cat:"26"} dict1.setdefault("dog",10} it will add dog dict.fromkey(): animals = ["1","2","3"] animal_age = dict.from key(animals) print(animal_age) op: {"1":None,"2":None} ,m.9 """
x = int(input("Enter 1st positive number")) temp = x sum = 0 product =1 reverse = 0 while temp != 0: d = int( temp % 10) sum += d product *= d reverse = reverse*10+d temp = int(temp/10) print(f'sum of digits {sum}') print("product of dits is", product)
# # # Constructor: # # # # # # # # # # class Sample: # # def __call__(self, *args, **kwargs): # # obj = self.__new__() # # self.__init__(obj) # # return obj # # def __new__(cls, *args, **kwargs): # # print("I am creating that obj") # # return super(Sample, cls).__new__(cls) # # def __init__(self): # # print(" I am good") # # # # # # # # s = Sample() # # print(s) # # print(type(s)) # # # suppose we have memeber variables as name and age and we also write s.coolege it works to stop that we block # # # set attribute is the function which we ca # # # # # # # self is a veriable name # # # # # # class Integer: # # # # def based_on_parameters(integers): # return integers[0] # # class Integer: # def _init_(self, val): # self.val = val # # def __gt__(self, other): # return self.val > other.val # # # # i1 = Integer(3); # i2 = Integer(4); # print(i1.val) # # integers = [Integer(3), Integer(2), Integer(1)] # # # integers.sort() # class Integer: def __init__(self,val): self.val = val def __gt__(self, other): return self.val>other.val integers = [Integer(3),Integer(2),Integer(1)] integers.sort() print(integers[0].__str__())
#!/usr/bin/env python3 # Anagrama # dada una palabra busca anagramas de la misma print('Ingrese una palabra para buscar:') palabra = input() listapalabras = "palabras.txt" f = open(listapalabras, 'r') lines = f.readlines() for line in lines: if sorted(list(line)[:-1]) == sorted(palabra): print(line.replace("\n", " ")) f.close()
import matplotlib.pyplot as plt import numpy as np def f(x): f = eval(function) return f print(''' ######################################################### ######################################################### #### #### #### Método de Secante #### #### Por: Jesús Alfredo Navarro Guzmán #### #### https://github.com/JesusAlfred/MetodosNum #### #### [email protected] #### #### 18/10/2021 #### #### Métodos Numéricos #### #### #### ######################################################### ######################################################### ''') print("f(x) =", end=' ') function = str(input()) print("límiete a =", end=' ') a = int(input()) print("límiete b =", end=' ') b = int(input()) print("Xn =", end=' ') X0 = int(input()) print("Xn+1 =", end=' ') X1 = int(input()) print("iteraciones =", end=' ') lim = int(input()) print("decimales =", end=' ') dec = int(input()) print("n\t Xn\t Xn+1\t f(Xn)\t f(Xn+1)\t Xn+1 - Xn\t B=f(Xn+1)-f(Xn)\t A=f(Xn+1)*(Xn+1-Xn)\t C=A/B\t Xn+2=Xn+1-C") for i in range(lim): print(f"{i+1}\t|{round(X0, dec)}\t|{round(X1,dec)}\t|{round(f(X0), dec)}\t|{round(f(X1), dec)}\t\t|{round(X1-X0, dec)}\t\t|{round(f(X1)-f(X0), dec)}\t\t\t|{round(f(X1)*(X1-X0), dec)}\t\t\t|{round((f(X1)*(X1-X0))/(f(X1)-f(X0)), dec)}\t|{X1-((f(X1)*(X1-X0))/(f(X1)-f(X0)))}") temp = X1-((f(X1)*(X1-X0))/(f(X1)-f(X0))) X0=X1 X1 = temp # Muestra la grafica fun = np.arange(X1-10, X1+10, 0.05) plt.plot(fun, f(fun)) plt.grid() texto1 = plt.text(X1, f(X1)+1, f'( {X1:.{dec}f}, {f(X1):.4f} )', fontsize=14) plt.plot([X1], [f(X1)], 'bo') plt.show()
#!/usr/bin/env python # -*- coding: utf-8 -*- # # fibonacci.py def fib_iter(n): """Wylicza n-ty wyraz ciągu Fibonacciego F(0)= 0 F(1)= 1 F(n)= F(n-2) + F(n-1) """ if n == 0: return 0 elif n == 1: return 1 a, b = (0, 1) print(a) for i in range(1, n): a, b = b, a + b print(a, " ", b, " ", b / a) return b def fib_iter2(n): a, b = (1, 1) for i in range(2, n): a, b = b, a + b print("F({:4d}) / F({:4d}) = {:.5f}".format(b, a, b / a)) return b def main(args): # n = int(input("Podaj nr wyrazu: ")) # assert fib_iter(0) == 1 # assert fib_iter(1) == 1 # assert fib_iter(2) == 1 # assert fib_iter(5) == 5 print("Wyraz {:d} = {:d}". format(20, fib_iter(20))) return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv))
#textprobar import time scale = 51 print ("执行开始".center (scale // 1 , "=")) for i in range (scale) : time.sleep(0.1) str1 = "*" * i str2 = "." * (scale -1 - i) print ("\r{:^3}% [{}->{}]".format (i *2 , str1 , str2) , end = "") print ("\n" + "执行结束".center (20 , "=")) cc = input ("请输入任何字符以结束程序")
import math a=eval(input('请输入第一个边长值')) b=eval(input('请输入第二个边长值')) c=eval(input('请输入两边长的夹角角度值')) third=math.sqrt(math.pow(a,2)+math.pow(b,2)-2*a*b*math.cos(c*math.pi/180)) print('第三边长为:',third)
import sys moves = input() index = 1 for i in moves: if (i == 'A' and index != 3): index = 2 if index == 1 else 1 elif (i == 'B' and index != 1): index = 3 if index == 2 else 2 elif (i == 'C' and index != 2): index = 1 if index == 3 else 3 print(index)
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print 'Original array is:' print a print '\n' print 'Transpose of the original array is:' b = a.T print b print '\n' print 'Sorted in C-style order:' c = b.copy(order = 'C') print c for x in np.nditer(c): print x, print '\n' print 'Sorted in F-style order:' c = b.copy(order = 'F') print c for x in np.nditer(c): print x, import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print 'Original array is:' print a print '\n' print 'Sorted in C-style order:' for x in np.nditer(a, order = 'C'): print x, print '\n' print 'Sorted in F-style order:' for x in np.nditer(a, order = 'F'): print x,
#Creating an empty Tuple Tuple1 = () print("Initial empty Tuple: ") print (Tuple1) #Creatting a Tuple #with the use of string Tuple1 = ('Python', 'For') print("\nTuple with the use of String: ") print(Tuple1) # Creating a Tuple with # the use of list list1 = [1, 2, 4, 5, 6] print("\nTuple using List: ") print(tuple(list1)) #Creating a Tuple #with the use of built-in function Tuple1 = tuple('Everyone') print("\nTuple with the use of function: ") print(Tuple1)
import numpy as np x = np.arange(9.).reshape(3, 3) print 'Our array is:' print x # define a condition condition = np.mod(x,2) == 0 print 'Element-wise value of condition' print condition print 'Extract elements using condition' print np.extract(condition, x)
# Python code to demonstrate the working of isleap() # importing calendar module for calendar operations import calendar year = 2017 # calling isleap() method to verify val = calendar.isleap(year) # checking the condition is True or not if val == True: # print 4th month of given leap year calendar.prmonth(year, 4, 2, 1) # Returned False, year is not a leap else: print("% s is not a leap year" % year)
# Python code to Reverse each word # of a Sentence individually # Function to Reverse words def reverseWordSentence(Sentence): # Splitting the Sentence into list of words. words = Sentence.split(" ") # Reversing each word and creating # a new list of words # List Comprehension Technique newWords = [word[::-1] for word in words] # Joining the new list of words # to for a new Sentence newSentence = " ".join(newWords) return newSentence # Driver's Code Sentence = "Python is a good language to learn" # Calling the reverseWordSentence # Function to get the newSentence print(reverseWordSentence(Sentence))
# Calenndar Module # First Weekday # Calendar.firstweekday() # Returns the current setting for the weekday that starts each week. # default is Monday i.e '0' import calendar print(calendar.firstweekday()) # Leap year # calendar.isleap(year) # returns true if the year is ;eap year, else false year = 2020 print("Is 2020 a leap year?" , calendar.isleap(2020)) # Leap days # calendar leapdays(y1. y2) # Returns the total number of leap days within range [y1,y2] y1 = 2020 y2 = 2021 print("No. of leap days this year:" , calendar.leapdays(y1,y2)) # Calendar of month # calendar.month(year,month,w,l) # Retruns multiline stirng of the calendar for Month # w is width of chars of each date, l is lines for each week year = 2020 month = 5 calendar.month(year,month,w=2, l =1)
# filter the selection by # using the "WHERE" statement import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() sql = "SELECT * FROM customers WHERE address ='Park Lane 38'" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult: print(x) # Select records where # the address contains the word "way" import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() sql = "SELECT * FROM customers WHERE address LIKE '%way%'" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult: print(x)
# Python program to # demonstrate time class from datetime import time # calling the constructor my_time = time(13, 24, 56) print("Entered time", my_time) # calling constructor with 1 # argument my_time = time(minute = 12) print("\nTime with one argument", my_time) # Calling constructor with # 0 argument my_time = time() print("\nTime without argument", my_time) # Uncommenting time(hour = 26) # will rase an ValueError as # it is out of range # uncommenting time(hour ='23') # will raise TypeError as # string is passed instead of int
import numpy as np a = np.array([10,100,1000]) print 'Our array is:' print a print '\n' print 'Applying power function:' print np.power(a,2) print '\n' print 'Second array:' b = np.array([1,2,3]) print b print '\n' print 'Applying power function again:' print np.power(a,b)
''' Online Python Compiler. Code, Compile, Run and Debug python program online. Write your code in this editor and press "Run" button to execute it. ''' def pairSum(n,input_array): input_array.sort() if input_array[0]>n: print("no such elements") else: for i in range(len(input_array)): j = 1 for j in range(len(input_array)): if input_array[i]+input_array[j] == n: print(input_array[i],input_array[j]) j = j+1 n = int(input()) input_array = [] for i in range(5): array_element = int(input()) input_array.append(array_element) pairSum(n,input_array)
class Problema(object): def __init__(self, inicio, objetivo=None, acao=None): self.inicio = inicio self.objetivo = objetivo self.acao = acao def test_objetivo(self, estadoNo): return estadoNo == self.objetivo def acoes(self,estadoNo): return list(self.acao[estadoNo]) class No(object): def __init__(self, estado, pais=None, acao=None, custo_caminho=0, valor=None): self.estado = estado self.pais = pais if pais: self.acao = pais.estado + "->" + estado self.custo_caminho = custo_caminho self.valor = valor self.profundidade = 0 if pais: self.profundidade = pais.profundidade + 1 # def solucao(self): # return [no.acao for no in self.caminho()[1:]] # def caminho(self): # no, caminho_volta = self, [] # while no: # caminho_volta.append(no) # no = no.pais # return list(reversed(caminho_volta)) # def no_filho(self, problema, acao): # prox_estado = # def expandir(self, problema): def __repr__(self): return self.estado + ", " + self.acao