text
stringlengths
37
1.41M
import requests from bs4 import BeautifulSoup # Task 1------------------------------------------------------------------------- url = input("Enter wiki url: ") # for easy testing #url= 'https://de.wikipedia.org/wiki/Pietro_Antonio_Lorenzoni' def scraping_webpage(url): # web scraping function page = requests.get(url) # getting the text and parsing it soup = BeautifulSoup(page.text, 'html.parser') # The Wiki page Text text = [] text_body = soup.find_all(class_='mw-body') for item in text_body: text.append(item.text) # Clean version of the text string = ' '.join([str(item) for item in text]) return string my_fun = scraping_webpage(url) print(my_fun)
import time, sys indent = 0 indent_increasing = True try: while True: print(' ' * indent, end = '')#{end = ''} = print('********') time.sleep(0.1) #pause for 1/10 of a second if indent_increasing: #increase the number of spaces indent += 1 if indent == 10: #when indent increas to 10 ,trun indent_increasing into False indent_increasing = False else: #decrease the number of spaces indent -= 1 if indent == 0: #when indent decreas to 0 ,trun indent_increasing into True indent_increasing = True except KeyboardInterrupt: #let KeyboardInterrupt error dispear sys.exit
opcion = "" def obtener_valores(diccionario): arreglo_numeros = [] valores_diccionario = diccionario.values() for valor in valores_diccionario: tipo = type(valor) lista = isinstance(valor, list) == True tupla = isinstance(valor, tuple) == True es_lista = isinstance(valor, list) == True es_tupla = isinstance(valor, tuple) == True if(es_lista or es_tupla): for valor_arreglo in valor: arreglo_numeros.append(valor_arreglo) else: arreglo_numeros.append(valor) return arreglo_numeros def obtener_longitud(diccionario): arreglo_numeros = [] valores_diccionario = diccionario.values() for valor in valores_diccionario: tipo = type(valor) es_lista = isinstance(valor, list) == True es_tupla = isinstance(valor, tuple) == True if(es_lista or es_tupla): for valor_arreglo in valor: arreglo_numeros.append(valor_arreglo) else: arreglo_numeros.append(valor) return len(arreglo_numeros) while opcion != "2": opcion = input (""" Seleccione una de las opciones (Ej: 1): 1) Demostración del cálculo de valores altos y bajos en diccionarios. 2) Salir """) if(opcion == "1"): dic_uno = {"Raul":34,"Paula":19,"Jorge":43,"Richard":10,"Diana":3,"Isabel":76,"Gustavo":12,"Diego":37} longitud_dic_uno = obtener_longitud(dic_uno) dic_dos = {"tplA":(4,-12,56,-34,98,102),"tplB":(9,0,1,10,-3,14),"tlpC":(87,12,56,987,-61)} longitud_dic_dos = obtener_longitud(dic_dos) dic_tres = {"val1":-12.5,"val2":12.5,"val3":83,"val4":2.1,"val5":23,"val6":100,"val7":13.4,"val8":92} longitud_dic_tres = obtener_longitud(dic_tres) dic_cuatro = {"lst1":[4,6,-12,56,-9,5.7,33,100],"lst2":[9,0,81,-2,-56,],"lst3":[12,31,87,1,0,4,-11]} longitud_dic_cuatro = obtener_longitud(dic_cuatro) opcion_diccionario = input(""" Elija un diccionario para la demostración: 1) {Raul:34,Paula:19,Jorge:43,Richard:10,Diana:3,Isabel:76,Gustavo:12,Diego:37} 2) {tplA:(4,-12,56,-34,98,102),tplB:(9,0,1,10,-3,14),tlpC:(87,12,56,987,-61)} 3) {val1:-12.5,val2:12.5,val3:83,val4:2.1,val5:23,val6:100,val7:13.4,val8:92} 4) {lst1:[4,6,-12,56,-9,5.7,33,100],lst2:[9,0,81,-2,-56,],lst3:[12,31,87,1,0,4,-11]} """) if(opcion_diccionario == "1" or opcion_diccionario == "2" or opcion_diccionario == "3" or opcion_diccionario == "4"): longitud_maxima = 0 if(opcion_diccionario == "1"): longitud_maxima = longitud_dic_uno if(opcion_diccionario == "2"): longitud_maxima = longitud_dic_dos if(opcion_diccionario == "3"): longitud_maxima = longitud_dic_tres if(opcion_diccionario == "4"): longitud_maxima = longitud_dic_cuatro numero_altos = int(input(f"Ingrese el numero de valores altos entre 0 y {longitud_maxima}: ")) numero_bajos = int(input(f"Ingrese el numero de valores bajos entre 0 y {longitud_maxima}: ")) if(numero_altos > longitud_maxima or numero_altos < 0 or numero_bajos > longitud_maxima or numero_bajos < 0): print("El numero de bajos o altos fue seleccionado fuera del rango") else: lista_valores = [] if(opcion_diccionario == "1"): lista_valores = obtener_valores(dic_uno) if(opcion_diccionario == "2"): lista_valores = obtener_valores(dic_dos) if(opcion_diccionario == "3"): lista_valores = obtener_valores(dic_tres) if(opcion_diccionario == "4"): lista_valores = obtener_valores(dic_cuatro) lista_valores.sort() print("MENORES") print("Lista menores tupla") print(tuple(lista_valores[:numero_bajos])) print("Lista menores lista") print(lista_valores[:numero_bajos]) print("MAYORES") print("Lista mayores tupla") print(tuple(lista_valores[-1 * (numero_altos):])) print("Lista mayores lista") print(lista_valores[-1 * (numero_altos):]) else: print("No selecciono una opcion de diccionario correcto") else: if(opcion != "2"): print("Seleccione una opcion correcta")
import os import csv print("\nFinancial Analysis") print("--------------------------------------------------") # Relative path for input file csvPath = os.path.join('Resources', 'budget_data.csv') # Relative path for output file output_path = os.path.join('analysis', 'py_bank_output.txt') # List for all the dates in the dataset months = [] # Varible for the number of months in the dataset num_months = 0 # Variable for net total amount of profit/losses net_total = 0 # List to hold profits and losses profit_loss = [] # Variable for change change = 0 # Variable for average change avg_change = 0 # Variable for greatest profit increase amount greatest_increase = 0 # Variable for greatest profit decrease amount greatest_decrease = 0 with open(csvPath) as csvFileStream: # CSV reader specifies delimiter and variable that holds contents csv_reader = csv.reader(csvFileStream, delimiter =',') # Read the header row first csv_header = next(csv_reader) # For each row after the header... for row in csv_reader: # Add each date to the months list months.append(row[0]) # Calculate net total of profits/losses over the entire period net_total += int(row[1]) # Add each profit/loss to the profit_loss list profit_loss.append(int(row[1])) # Getting the total number of months in the dataset num_months = len(months) # List comprehension to calculate successive difference in order to later calculate average change change = [profit_loss[i+1] - profit_loss[i] for i in range (len(profit_loss)-1)] # Calculating average change avg_change = sum(change) / len(change) # Formatting average change to print to two decimal places avg_change = "{:.2f}".format(avg_change) # Getting greatest increase in profits amount from change list greatest_increase = max(change) # Getting the month with the greatest increase in profits greatest_increase_month = change.index(max(change)) + 1 # Getting greatest decrease in profits amount from change list greatest_decrease = min(change) # Getting the month with the greatest decrease in profits greatest_decrease_month = change.index(min(change)) + 1 # Printing outputs to terminal print(f"Total Months: {num_months}") print(f"Total: ${net_total}") print(f"Average Change: (${avg_change})") print(f"Greatest Increase in Profits: {months[greatest_increase_month]} (${greatest_increase})") print(f"Greatest Decrease in Profits: {months[greatest_decrease_month]} (${greatest_decrease})\n") # Writing output to the text file with open(output_path, 'w') as txt_file: txt_file.write("Financial Analysis\n") txt_file.write("---------------------------------------\n") txt_file.write(f"Total Months: {num_months}\n") txt_file.write(f"Total: ${net_total}\n") txt_file.write(f"Average Change: (${avg_change})\n") txt_file.write(f"Greatest Increase in Profits: {months[greatest_increase_month]} (${greatest_increase})\n") txt_file.write(f"Greatest Decrease in Profits: {months[greatest_decrease_month]} (${greatest_decrease})") # Closing text file after writing output is complete txt_file.close()
import unittest #Importing the unittest module from user import User class TestUser(unittest.TestCase): ''' Test class that defines test cases for the User class behaviors Arg: unittest.Testcase: A TestCase class that helps in creating test case classes ''' def setUp(self): ''' Set up method to run before each test case ''' self.new_User = User("Rix", "Mike", "[email protected]", "ragnarok19") def test_init(self): ''' test case to test if the object has been properly initialized ''' self.assertEqual(self.new_User.first_name,"Rix") self.assertEqual(self.new_User.last_name,"Mike") self.assertEqual(self.new_User.user_email,"[email protected]") self.assertEqual(self.new_User.user_password,"ragnarok19") if __name__ == '__main__': unittest.main()
""" This module contains the connect four game board and it's operations. """ from datetime import datetime class ConnectFourGame: """ A game of connect four played by the twitter bot. """ def __init__(self, game_id, user1, user2, last_tweet, last_active, boardstring, num_turns, user1_is_playing, game_won): """ Create a game instance with given values. :param game_id: The unique game identifier. :type game_id: int :param user1: The screen name of user 1. :type user1: str :param user2: The screen name of user 2. :type user2: str :param last_tweet: The ID of the last tweet in the thread. :type last_tweet: int :param last_active: Date the game was last active. :type last_active: datetime :param boardstring: board values in top-to-bottom & left-to-right, column-by-column fashion. :type boardstring: str :param num_turns: Number of moves played on game so far. :type num_turns: int :param user1_is_playing: Indicates whose turn it is. 0 = false, 1 = true. :type user1_is_playing: int :param game_won: Indicates if game is over. 0 = false, 1 = true. :type game_won: int """ self.game_ID = game_id self.user1 = user1 self.user2 = user2 self.last_tweet = last_tweet self.last_active = last_active self.board = self.board_from_string(boardstring) self.num_turns = num_turns self.user1_is_playing = user1_is_playing self.game_won = game_won @staticmethod def board_from_string(boardstring): """ Given a string representation of a connect four board, create a 2D int array. :param boardstring: a string representation of the connect four board. :type boardstring: str :return: a 2D int array representing the 7x6 connect four board. :rtype: int[][] """ board = [] for c in range(7): col = [] for d in range(6): char = boardstring[c * 6 + d] col.append(int(char)) board.append(col) return board @staticmethod def new_game(id, user1, user2, last_tweet): """Creates a new game. :param id: The unique ID of this game. :type id: int :param user1: The username of the first user. :type user1: str :param user2: The username of the first user. :type user2: str :param last_tweet: The ID of the most recent tweet in the game. :type last_tweet: int :return: A fresh connect four game. :rtype: ConnectFourGame """ boardstring = "000000000000000000000000000000000000000000" game = ConnectFourGame(id, user1, user2, last_tweet, datetime.now(), boardstring, 0, 0, 0) return game @staticmethod def game_from_string(gamestring): """ Instantiate a game with parameters encoded in a string. :param gamestring: Encodes the parameters of the game. :type gamestring: str :return: A game with specified parameters, or None if gamestring lacks paramaters. :rtype: ConnectFourGame """ tokens = gamestring.split(",") if len(tokens) >= 8: datetime_object = datetime.strptime(tokens[4], '%Y-%m-%d %H:%M:%S.%f') game = ConnectFourGame(int(tokens[0]), tokens[1], tokens[2], int(tokens[3]), datetime_object, tokens[5], int(tokens[6]), int(tokens[7]), int(tokens[8])) return game def game_to_string(self): """ Generate a single line string representation of the ConnectFourGame. :return: a string representation of the ConnectFourGame. :rtype: str """ out = str(self.game_ID) + "," + self.user1 + "," + self.user2 + "," out = out + str(self.last_tweet) + "," + str(self.last_active) + "," for c in range(7): for d in range(6): out = out + str(self.get_val(c, d)) out = out + "," + str(self.num_turns) + "," + str(self.user1_is_playing) + "," + str(self.game_won) return out def get_val(self, c, d): """ Get the value of a specific game board space. :param c: The column being accessed. Zero-indexed. :type c: int :param d: The depth being accessed. Zero-indexed. :type d: int :return: The value of the game board space. :rtype: int """ if (-1 < c < 7) & (-1 < d < 6): col = self.board[c] return int(col[d]) def can_play(self, col): """ Check that game and column can be played on. :param col: The column being accessed. 1-indexed. :type col: int :return: Whether user can play on this game in column. :rtype: Boolean """ return self.game_won == 0 and self.num_turns < 42 \ and self.get_val(col-1, 0) == 0 def asemoji(self): """ Output the game in an emojiful tweet-friendly representation. :return: Tweetable representation of the board game. :rtype: str """ out = "@" if self.user1_is_playing == 1: out = out + self.user2 else: out = out + self.user1 out = out + "\n" if self.game_won: out = out + " GAME WON\n" out = out + "\n" for d in range(6): for c in range(7): x = self.get_val(c, d) if x == 1: out = out + ":red_circle:" if x == 2: out = out + ":blue_circle:" if (x != 1) & (x != 2): out = out + ":white_circle:" out = out + "\n" out = out + "\n@" + self.user1 + " :red_circle:" if self.user1_is_playing == 1: out = out + " :UP!_button:" out = out + "\n" + "@" + self.user2 + " :blue_circle:" if self.user1_is_playing != 1: out = out + " :UP!_button:" return out def play_turn(self, tweet_id, col): """ Modify the ConnectFourGame to play a turn. :param tweet_id: The ID of the tweet that made a play. :type tweet_id: int :param col: The column number to be played. 1-indexed. :type col: int :rtype: None """ if self.can_play(col): self.last_active = datetime.now() self.last_tweet = tweet_id user = 2 if self.user1_is_playing == 1: user = 1 self.place_piece(user, col) self.check_win() if self.user1_is_playing == 1: self.user1_is_playing = 0 else: self.user1_is_playing = 1 self.num_turns += 1 def place_piece(self, user, column): """ Put a game piece in a specific column on the game board. :param user: The number of the user playing. 1 = red user A, 2 = blue user B. :type user: int :param column: The column number to be played in. 1-indexed. :type column: int """ if 0 < column < 8: col = self.board[column - 1] if col[0] == 0: # if top space in column empty, piece_depth = 0 # enter column for i in range(5): # max five sink actions if col[piece_depth + 1] < 1: # if space below empty, piece_depth += 1 # sink col[piece_depth] = user # place piece def check_win(self): """ Check to see if there are any lines of 4 pieces on the board. :return: Whether or not the game has been won. :rtype: bool """ win = (self.vert_win() | self.hor_win() | self.l_win() | self.r_win()) if win: self.game_won = 1 return win def vert_win(self): """ Check for vertical line of four same-coloured pieces. :return: Whether or not a vertical line of four same-coloured pieces exists on the board. :rtype: bool """ for c in range(7): col = self.board[c] count = 0 piece = 0 for d in range(6): if count < 4: if col[d] > 0: if piece == col[d]: count += 1 else: count = 1 else: count = 0 piece = col[d] if count > 3: return True return False def hor_win(self): """ Check for horizontal line of four same-coloured pieces. :return: Whether or not a horizontal line of four same-coloured pieces exists on the board. :rtype: bool """ for d in range(6): count = 0 piece = 0 for c in range(7): if count < 4: col = self.board[c] if col[d] > 0: if piece == col[d]: count += 1 else: count = 1 else: count = 0 piece = col[d] if count > 3: return True return False def l_win(self): """ Check for left-leaning diagonal line of four same-coloured pieces. :return: Whether or not a left-leaning diagonal line of four same-coloured pieces exists on the board. :rtype: bool """ for start_row in range(3): for start_col in range(4): count = 0 piece = 0 for i in range(4): if count < 4: col = self.board[start_col + i] x = col[start_row + i] if x > 0: if piece == x: count += 1 else: count = 1 else: count = 0 piece = x if count > 3: return True return False def r_win(self): """ Check for right-leaning diagonal line of four same-coloured pieces. :return: Whether or not a right-leaning diagonal line of four same-coloured pieces exists on the board. :rtype: bool """ for sr in range(3): for sc in range(3, 7): count = 0 piece = 0 for i in range(4): if count < 4: col = self.board[sc - i] x = col[sr + i] if x > 0: if piece == x: count += 1 else: count = 1 else: count = 0 piece = x if count > 3: return True return False
# -*- coding: utf-8 -*- """ Created on Tue Jul 10 20:51:38 2018 @author: yinjiang """ # quick sort in a unsorted array # step 1: convert txt file into array l = [] filename = 'QuickSort.txt' with open(filename, 'r') as f: for item in f.readlines(): l.append(int(item.strip())) # step 2: quick sort helper function def QsortHelper(A, left, right): # as long as left < right, keep go deeper, if left=right, no need to sort if left < right: # keep track of comparison times c = right - left global count count = count + c # choose pivot on last item # in order to utilize same partition function, we need to swap array # manipulation temp = A[right] A[right] = A[left] A[left] = temp # partition based on pivot boundary = partition(A, left, right) # two recursive calls QsortHelper(A, left, boundary-1) QsortHelper(A, boundary+1, right) # do not need return anything, after swapping, A will be sorted def partition(A, left, right): p = A[left] i = left+1 for j in range(left+1,right+1): if A[j] < p: # smaller element needs swap temp = A[i] A[i] = A[j] A[j] = temp i = i+1 # swap pivot to correct (i-1)th position # now i point to 1st item > p temp = A[i-1] A[i-1] = A[left] A[left] = temp # return the correct pivot position return i-1 def Qsort(l): global count count=0 length = len(l) QsortHelper(l, 0, length-1) return count total = Qsort(l) print l print total #test = l[:9] #print test #total = Qsort(test) #print total #def partition(A, left, right, result): # # keep track of comparison times # c = right - left # result.append(c) # # choose pivot, always choose last item # p = A[right] # i = left # for j in range(left, right): # if A[j] < p: # temp = A[i] # A[i] = A[j] # A[j] = temp # i = i+1 # temp = A[i] # A[i] = A[right] # A[right] = temp # return i
r=1 while r < 8: print(r) if r==5: break r+=1
""" Interpolates the temperature data over height (1D) and then over a surface to try to understand the three dimensional temperature distribution """ import pickle import numpy as np from scipy import interpolate import matplotlib.pyplot as plt import pandas as pd # upload the processed and corrected data file_address = "Temperatures_Processed_Uncorrected.pkl" with open(file_address, "rb") as handle: all_data = pickle.load(handle) # dictionaries to contain additional data extra_data = {} # plotting parameters colors = ["royalblue", "darkgreen", "firebrick", "blueviolet", "darkorange", "cyan", "black"]*3 linestyles = ["-", "--", "-.", ":"]*4 location_plot = {"TXX": (0,1), "T13": (1,0), "T23": (1,1), "T33": (1,2), "T12": (2,0), "T22": (2,1), "T32": (2,2), "T11": (3,0), "T21": (3,1), "T31": (3,2), "TDD": (4,1)} for test_name in all_data: print(test_name) df = all_data[test_name] extra_data[test_name] = {} # extract all the TC_trees names TC_trees_names = [] for col in df.columns: if col == "testing_time": pass else: TC_tree_name = col.split("-")[0] TC_trees_names.append(TC_tree_name) # retain only the unique TC_trees names TC_trees = list(set(TC_trees_names)) # iterates over each TC_tree for tc_tree in TC_trees: thermocouples = [] thermocouples_heights = [] extra_data[test_name][tc_tree] = {} # obtaines a list of all the columns associated to a given tc_tree and also its respective heights for col in df.columns: if tc_tree in col: thermocouples.append(col) thermocouples_heights.append(col.split("-")[1]) # convert list of heights from a list of integers to a list of thermocouples_heights = [int(x) for x in thermocouples_heights] # at every time step, find the maximum and minimum tempeartures and also the height at which that occurrs df.loc[:, f"{tc_tree}_max"] = df.loc[:, thermocouples].apply(lambda x: x.values.max(), axis = 1) df.loc[:, f"{tc_tree}_height_max"] = df.loc[:, thermocouples].apply( lambda x: thermocouples_heights[x.values.argmax()], axis = 1) df.loc[:, f"{tc_tree}_min"] = df.loc[:, thermocouples].apply(lambda x: x.values.min(), axis = 1) df.loc[:, f"{tc_tree}_height_min"] = df.loc[:, thermocouples].apply( lambda x: thermocouples_heights[x.values.argmin()], axis = 1) # also for every tc_tree, I will add the considered heights as well as the maximum and minimum heights extra_data[test_name][tc_tree]["all_tcs"] = thermocouples # for every TC_tree, create a function that interpolates temperature as a function of height x = thermocouples_heights df.loc[:, f"f_TempvsHeight_{tc_tree}"] = df.loc[:, thermocouples].apply( lambda y: interpolate.interp1d(x, y.values), axis = 1) # # First, find a temperature value that is within the interpolating range of ALL trees # max_column_list = [] # min_column_list = [] # for col in df.columns: # if "max" in col: # if "height" in col: # pass # else: # max_column_list.append(col) # elif "min" in col: # if "height" in col: # pass # else: # min_column_list.append(col) # # # at every time step, determine the temperature range that ALL TC_trees can cover # # now, calculate at every time step the temperature at which we will estimate the height per TC tree # min_maximum_temperature = df.loc[:, max_column_list].min(axis = 1) # max_minimum_temperature = df.loc[:, min_column_list].max(axis = 1) # ## tracked_temperature = np.round(pd.concat( ## [min_maximum_temperature, max_minimum_temperature], axis = 1).mean(axis = 1)) # # tracked_temperature = np.ceil(min_maximum_temperature) # # # calculate the corresponding height at which tracked_temperature is attained for every TC_tree # interp_func_list = [x for x in df.columns if "HeightvsTemp" in x] # for col in interp_func_list: # TC_tree = col.split("_")[2] # # # very slow implementation but I haven't figured out how to do it with .apply() # height_tracked_temperature = np.zeros(len(df)) # for i,temperature in enumerate(tracked_temperature): # print(temperature) # height_tracked_temperature[i] = df.loc[i, col](temperature) # # ## df.loc[:, f"{TC_tree}_height_tracked_temperature"] = df.loc[:, col].apply(lambda x: print(tracked_temperature)) break # ----------- # plot maximum and minimum temperature # ----------- # fig, ax = plt.subplots(5,3,figsize = (11,11), sharex = True, sharey = True) # fig.subplots_adjust(top = 0.9, left = 0.1, bottom = 0.1, # hspace = 0.2, wspace = 0.075) # fig.suptitle(test_name, fontsize = 14) # # # format plots # for j,axis in enumerate(ax.flatten()): # axis.grid(True, color = "gainsboro", linestyle = "--", linewidth = 0.75) # axis.set_title(["","TXX_CentreWall","", # "T13_LeftFar","T23_CentreFar","T33_RightFar", # "T12_LeftMid","T22_CentreMid","T32_RightMid", # "T11_LeftNear","T21_CentreNear","T31_RightNear", # "", "TDD_Door", ""][j], # fontsize = 12) # # format the axis # for axis in [ax[0,1], ax[1,0], ax[2,0], ax[3,0], ax[4,1]]: # axis.set_ylabel("Temperature [$^\circ$C]", fontsize = 10) # axis.set_ylim([0,1400]) # axis.set_yticks(np.linspace(0,1400,5)) # for axis in [ax[3,0], ax[4,1], ax[3,2]]: # axis.set_xlabel("Time [min]", fontsize = 10) # axis.set_xlim([0,60]) # axis.set_xticks(np.linspace(0,60,5)) # for axis in [ax[0,0], ax[0,2], ax[4,0], ax[4,2]]: # axis.axis("off") # # # iterate over all the TC_trees in this test # for j,tc_tree in enumerate(TC_trees): # # # extract the name of hte TC tree # location = location_plot[tc_tree] # # axis = ax[location[0], [location[1]]][0] # y_max = df.loc[:, f"{tc_tree}_max"] # y_min = df.loc[:, f"{tc_tree}_min"] # x = df.loc[:, "testing_time"]/60 # # axis.plot(x, # y_max, # color = "steelblue", # linewidth = 2, # linestyle = "-", # label = "max_temperature") # # axis.plot(x, # y_min, # color = "crimson", # linewidth = 2, # linestyle = "-", # label = "min_temperature") # # axis.fill_between(x, # y_max, # y_min, # color = "grey", # alpha = 0.75) # # axis.legend(fancybox = True, loc = "lower right", # fontsize = 6, ncol = 3) # # # add a text that indicates which TCs are avaialable # ax[0,0].text(x = 5, y = 1300, # s = "Working TCs per TC tree:",fontsize = 6) # # # text_string = " ".join([x.split('-')[1] for x in tc_columns]) # text_string = f"{tc_tree}:\n{text_string}" # ax[0,0].text(x = 5, y = 1200 - j*150, # s = text_string,fontsize = 6) # # # save and close # fig.savefig(f"{test_name}_temperatures_maxANDmin_uncorrected.png", dpi = 300) # plt.close(fig) # # # ----------- # # plot height at which the maximum and minimum temperatures are achieved # # ----------- # fig, ax = plt.subplots(5,3,figsize = (11,11), sharex = True, sharey = True) # fig.subplots_adjust(top = 0.9, left = 0.1, bottom = 0.1, # hspace = 0.2, wspace = 0.075) # fig.suptitle(test_name, fontsize = 14) # # # format plots # for j,axis in enumerate(ax.flatten()): # axis.grid(True, color = "gainsboro", linestyle = "--", linewidth = 0.75) # axis.set_title(["","TXX_CentreWall","", # "T13_LeftFar","T23_CentreFar","T33_RightFar", # "T12_LeftMid","T22_CentreMid","T32_RightMid", # "T11_LeftNear","T21_CentreNear","T31_RightNear", # "", "TDD_Door", ""][j], # fontsize = 12) # # format the axis # for axis in [ax[0,1], ax[1,0], ax[2,0], ax[3,0], ax[4,1]]: # axis.set_ylabel("Height [mm]", fontsize = 8) # axis.set_ylim([0,320]) # axis.set_yticks(np.linspace(20,280,14)) # for axis in [ax[3,0], ax[4,1], ax[3,2]]: # axis.set_xlabel("Time [min]", fontsize = 10) # axis.set_xlim([0,60]) # axis.set_xticks(np.linspace(0,60,5)) # for axis in [ax[0,0], ax[0,2], ax[4,0], ax[4,2]]: # axis.axis("off") # # # iterate over all the TC_trees in this test # for tc_tree in TC_trees: # # # extract the name of hte TC tree # location = location_plot[tc_tree] # # axis = ax[location[0], [location[1]]][0] # y_max = df.loc[:, f"{tc_tree}_height_max"] # y_min = df.loc[:, f"{tc_tree}_height_min"] # x = df.loc[:, "testing_time"]/60 # # axis.plot(x, # y_max, # color = "steelblue", # linewidth = 1, # linestyle = "-", # label = "height_max_temperature") # # axis.plot(x, # y_min, # color = "crimson", # linewidth = 1, # linestyle = "-", # label = "height_min_temperature") # # axis.legend(fancybox = True, loc = "upper right", # fontsize = 5, ncol = 3) # # # save and close # fig.savefig(f"{test_name}_heights_maxANDmin_uncorrected.png", dpi = 300) # plt.close(fig)
def dongmachine(dongamount): dongamount=int(dongamount) for x in range(1,dongamount): print("dong") dongamount=input("Hi how much do you like dongs?") dongmachine(dongamount)
class MyLinkedList: def __init__(self): """ Initialize your data structure here. """ self.val = None self.next=None def get(self, index: int) -> int: """ Get the value of the index-th node in the linked list. If the index is invalid, return -1. """ if self.val == None: return -1 j=self i=0 while j!=None: if i == index: return j.val j=j.next i+=1 return -1 def addAtHead(self, val: int) -> None: """ Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. """ if self.val==None: self.val=val else: j=self.val n=self.next self.val=val self.next=MyLinkedList() self.next.val=j self.next.next=n def addAtTail(self, val: int) -> None: """ Append a node of value val to the last element of the linked list. """ if self.val==None: self.val=val elif self.val!=None: j=self i=0 while j.next!=None: j=j.next i+=1 j.next=MyLinkedList() j.next.val=val def addAtIndex(self, index: int, val: int) -> None:#在第幾項插入值 """ Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. """ i=0 t=0 j=self index=index-1 while i<index: i+=1 if j.next!=None: j=j.next n=j else: t+=1 if index<=-1: self.addAtHead(val) elif t==0 and j.next!=None: n=j.next j.next=MyLinkedList() j.next.val=val j.next.next=n elif t<=1 and j.val!=None: self.addAtTail(val) def deleteAtIndex(self, index: int) -> None: """ Delete the index-th node in the linked list, if the index is valid. """ i=0 j=self t=0 while i<index: i+=1 if j.next!=None: n=j j=j.next else: t+=1 if index==0 and j.next==None: j.val=None elif index>=0 and t==0 and j.next!=None: j.val=j.next.val j.next=j.next.next elif index>0 and t==0 and j.val!=None: n.next=None else: return # Your MyLinkedList object will be instantiated and called as such: # obj = MyLinkedList() # param_1 = obj.get(index) # obj.addAtHead(val) # obj.addAtTail(val) # obj.addAtIndex(index,val) # obj.deleteAtIndex(index)
import sys import argparse parser = argparse.ArgumentParser(description='Give me oracle file.') parser.add_argument('-p', type=str, help='oracle file') args = parser.parse_args() count = 0 for test_line in open(args.p): if test_line.startswith("#"): count = 1 else: if count > 0: count=count + 1 if count == 3: print(test_line[:-1])
def convert(number): # initialize flags such that we start with no factors factor3 = False factor5 = False factor7 = False # initialize the output as type string string_output = '' # evaluate the moduli for each division, checking for zeroes if (number%3 == 0): factor3 = True if (number%5 == 0): factor5 = True if (number%7 == 0): factor7 = True if factor3 or factor5 or factor7 is True: if factor3 is True: string_output = string_output + 'Pling' if factor5 is True: string_output = string_output + 'Plang' if factor7 is True: string_output = string_output + 'Plong' else: string_output = string_output + str(number) return(string_output)
''' 该文件简单的创建了Card, Deck, Player, Game类,Game类中auto_play函数使用了1个MonteCarloAI和3个相同的规则策略完成了13回合的游戏 @author: pipixiu @time: 2018.9.30 @city: Nanjing ''' from encapsule import MonteCarloPlay import random import collections Card = collections.namedtuple('Card', ['point', 'suit']) ''' 使用namedtuple创建Card类型,包含point,suit两个属性 point: 纸牌点数, 2-14, 11为J, 12为Q, 13为K,14为A suit: 纸牌花色,梅花:0, 方块:1, 黑桃:2, 红桃:3 使用:spadeQ: Card(12,2) ''' def card2chinese(card): ''' 将某张牌类转换为中文可读 __input: card: Card类型 __output: str类型,牌的中文名称 ''' ranks = [str(n) for n in range(2, 11)] + list('JQKA') suits = '梅花 方块 黑桃 红桃'.split() return suits[card.suit] + ranks[card.point - 2] class Deck: #牌堆类,一堆52张牌 def __init__(self): # 建立牌堆 card = [] for i in range(4): for j in range(13): card.append(Card(j + 2, i)) self.card = card def shuffle(self): # 洗牌 random.shuffle(self.card) def deal(self, n=4): # 发牌,分四份 if not len(self.card): print('no cards') return [[] * n] p = [] for i in range(n): p.append((self.card[len(self.card) // n * i:len(self.card) // n * (i + 1)])) return p class Player: # 玩家类 def __init__(self, player_id, hand=[]): self.player_id = player_id self.hand = hand # 玩家手牌 def sortHand(self): # 整理,排序手发到的牌 self.hand.sort(key=lambda x: (x.suit, x.point)) def sortSuit(self): # 将剩余的牌按花色分类,便于后续的出牌的判断 club = [] diamond = [] spade = [] heart = [] for i in range(len(self.hand)): if self.hand[i].suit == 0: club.append(i) elif self.hand[i].suit == 1: diamond.append(i) elif self.hand[i].suit == 2: spade.append(i) elif self.hand[i].suit == 3: heart.append(i) return [club, diamond, spade, heart] class Game: # 游戏类,该类中封装了一个规则玩牌函数PlayCards,和传牌函数TransferThreeCards # find_first, choose_card, split_by_suit都是上述两函数用到的 # getScoreFromGame是从游戏记录中history_P0以及history中统计得分情况 # auto_play为一局13个回合的游戏函数,游戏过程将会打印出来 def __init__(self): self.deck = Deck() self.players = [None]*4 self.history = [[], [], [], []] # 四个玩家已经出的牌 self.history_P0 = [] # 每轮先出的玩家的index self.deck.shuffle() # 先洗牌 for player_id, one_deck in enumerate(self.deck.deal()): self.players[player_id] = Player(player_id, one_deck) # 发牌 self.players[0].sortHand() self.players[1].sortHand() self.players[2].sortHand() self.players[3].sortHand() # 排序手中的牌 def find_first(self): ''' 从已出牌中判断该谁先出牌 ''' first_id = 0 if not self.history_P0: # 如果还未出牌,则有梅花2的先出 for player_id in range(4): if self.players[player_id].hand[0] == Card(2, 0): first_id = player_id else: # 找到上回合得到出牌权的玩家 last_first = self.history_P0[-1] card_max = self.history[last_first][-1] for i in range(4): now_card = self.history[(last_first + i) % 4][-1] if now_card.suit == card_max.suit and now_card.point > card_max.point: card_max = now_card first_id = (last_first + i) % 4 return first_id def choose_card(self, suitsDeck, flag): ''' 传入待选择的几个花色,选出最大的值或者最小的值。(此时应可任选花色) suitsDeck: 不同花色牌的列表 flag: 0,选最大; 1,选最小 ''' k = flag * 15 m, pos = None, None for oneSuitDeck in suitsDeck: if len(oneSuitDeck) == 0: continue else: if flag == 1: if oneSuitDeck[0].point <= k: # 跨花色最最小的牌 pos = oneSuitDeck[0] # 出最小 k = oneSuitDeck[0].point m = oneSuitDeck elif flag == 0: if oneSuitDeck[-1].point >= k: # 跨花色选最大的牌 pos = oneSuitDeck[-1] k = oneSuitDeck[-1].point m = oneSuitDeck if m: m.remove(pos) return pos else: return None def split_by_suit(self, deck): ''' 将一摞牌按花色分摞 ''' a, b, c, d = [], [], [], [] suitsDeck = [a, b, c, d] for card in deck: suitsDeck[card.suit].append(card) return suitsDeck # -------------传牌---出牌函数------------------------------ def TransferThreeCards(self, deck): ''' input: deck: 列表,当前玩家手中的13张牌,如: deck = [Card(point=7, suit=0),Card(point=10, suit=3),Card(point=11, suit=3),...] output: transferCards:应当传出的三张牌 transferCards = [Card(point=7, suit=0),Card(point=10, suit=3),Card(point=11, suit=3)] ''' deck = sorted(deck, key=lambda x: x.suit * 10 + x.point) kinds = self.split_by_suit(deck) select = [] for i in range(3): # 先选大于黑桃Q的AKQ if len(kinds[2]) != 0: # 若有黑桃 if kinds[2][-1].point >= 10: # select.append(kinds[2].pop()) else: # break for i in range(4): # 再选红桃大于J的AKQJ if len(kinds[3]) != 0: if kinds[3][-1].point >= 9: select.append(kinds[3].pop()) else: break while len(select) < 3: # 还不足三个的话,在梅花,方块里选最大的 select.append(self.choose_card(kinds, 0)) transferCards = [select[0], select[1], select[2]] return transferCards def PlayCards(self, deck, history_self, history_A, history_B, history_C, history_P0, REPLAY=False): ''' 输入一摞牌,选出最应该出的牌 规则打牌的判断机制,对于自己第几个出,自己出牌前已经打出的牌,红桃牌,黑桃Q的打出情况, 以及应该打出大小点等各类情况都进行判断,从而选出应当打出的最适合的牌。 input: deck: 列表,当前玩家手中的牌,如: deck = [Card(point=7, suit=0),Card(point=10, suit=3),Card(point=11, suit=3)] history_self: 同deck列表,当前玩家已出的牌 history_A: 同deck列表,玩家A已出的牌 history_B: 同deck列表,玩家B已出的牌 history_C: 同deck列表,玩家C已出的牌 history_P0: 列表,每个回合第一个发牌的人的index。当前玩家:0, A:1, B:2, C:3 如:history_P0 = [0,1,1]表示第一回合是当前玩家先出的牌,第二回合玩家1先出的牌,第三回合还是玩家1先出的牌 REPLAY如果出牌不符合要求,则重新出牌 output: pos: Card类型,选出的最优的牌 ''' deck = sorted(deck, key=lambda x: x.suit * 10 + x.point) history = [history_self, history_A, history_B, history_C] # 从输入参数中计算每轮出的牌 allTurnsCard = [] for i, j in enumerate(history_P0): tmp = [] for k in range(4): now = history[(j + k) % 4] if len(now) > i: tmp.append([(j + k) % 4, now[i]]) allTurnsCard.append(tmp) thisTurnOutCard = allTurnsCard[-1] if allTurnsCard and len(allTurnsCard[-1]) != 4 else [] if thisTurnOutCard: maxCard = \ max([i for i in thisTurnOutCard if i[1].suit == thisTurnOutCard[0][1].suit], key=lambda x: x[1].point)[1] print(maxCard) # outQueen = True if Card(12,2) in allTurnsCard else False outQueen = True if [outCard for turn in allTurnsCard for outCard in turn if outCard[1] == Card(12, 2)] else False outHeart = True if [j for i in allTurnsCard for j in i if j[1].suit == 3] else False nowSuit = thisTurnOutCard[0][1].suit if thisTurnOutCard else None # print('queen:',outQueen,'heart:',outHeart) # 各花色已出牌数统计 suit_numbers = list(map(lambda x: x.suit, sum(self.history, []))) suit_count_dict = {i: suit_numbers.count(i) for i in set(suit_numbers)} # print('thisTurn',thisTurnOutCard) kinds = self.split_by_suit(deck) # 按花色分成四类排序 if len(thisTurnOutCard) == 0: # 如果是第一个出牌的 if len(deck) == 13: # 因为是第一回合且第一个出牌,最小的肯定是梅花2 pos = deck[0] else: if (outHeart == False) and (deck[0].suit != 3): # 如果红桃还没出,且当前最小值不是红桃 del kinds[3] # 不能出红桃类 if outQueen == False: if (len(kinds[2]) == 0) or (kinds[2][-1].point >= 12): # 没有黑桃或者黑桃最大值大于Q pos = self.choose_card(kinds, 1) else: # 如果有小黑桃 pos = kinds[2][0] # 出黑桃最小牌,拱猪 else: # 如果黑桃Q已出 pos = self.choose_card(kinds, 1) elif len(thisTurnOutCard) < 3: # 如果电脑不是最后一个出的 maxCard = 0 for outCard in thisTurnOutCard: # 对于每个出牌 card = outCard[1] if card.suit == nowSuit: # 找到这一轮花色的最大值 if card.point > maxCard: maxCard = card.point if len(kinds[nowSuit]) == 0: # 如果没有该花色,优先黑桃Q hasPig = False for spadeCard in kinds[2]: # 黑桃中每个牌 if spadeCard.point == 12: # 如果有黑桃Q pos = spadeCard # 打黑Q HasPig = True break if not hasPig: # 如果没有黑Q del kinds[nowSuit] # 不出黑桃 pos = self.choose_card(kinds, 0) # 在剩余的几个花色里选择最优的 if len(deck) == 13: # 如果是第一次出牌 while (pos.suit == 2 and pos.point == 12) or (pos.suit == 3): # 如果是黑Q或红桃,一直再找最优 pos = self.choose_card(kinds, 0) # flag是0,选最大值 # card = per.hand[pos] else: # 如果有该花色 if len(deck) == 13: # 如果是第一轮出牌 pos = kinds[0][-1] # 第一轮出最大的牌,第一轮肯定是梅花,故suit0 else: bigpos = [] smallpos = [] for card in kinds[nowSuit]: # 分为比当前回合最大牌大和比它小的两摞 if card.point > maxCard: bigpos.append(card) else: smallpos.append(card) if len(smallpos) != 0: # 如果有小的 pos = smallpos[-1] # 就出小的里面最大的 else: pos = bigpos[0] # 大牌里面最小的 if pos.suit == 2 and pos.point == 12 and len(bigpos) >= 2: pos = kinds[nowSuit][1] # 如果没有小的,如果大的里面最小的是黑桃Q且大的有两张牌以上,选择比最小的大一的 elif len(thisTurnOutCard) == 3: # 如果该玩家最后一个出牌 maxCard = 0 # 该花色最大的牌 for outCard in thisTurnOutCard: card = outCard[1] # 每个人出的牌 if card.suit == nowSuit: if card.point > maxCard: maxCard = card.point if len(kinds[nowSuit]) == 0: # 无该花色的牌 hasPig = False for spadeCard in kinds[2]: # 找黑桃Q if spadeCard.point == 12: pos = spadeCard hasPig = True break if not hasPig: del kinds[nowSuit] # 如果没黑桃Q,在除了该花色以外的里面选最优 pos = self.choose_card(kinds, 0) if len(deck) == 13: # 如果是第一次出牌 while (pos.suit == 2 and pos.point == 12) or (pos.suit == 3): # 找到的最优不能是黑桃Q或者红桃 pos = self.choose_card(kinds, 0) else: # 有该花色的牌 if len(deck) == 13: # 第一轮出该花色最大的牌 pos = kinds[0][-1] else: # 其他轮小心猪和红桃 hasScoreCard = False # 看出的牌里是否有猪和红桃 for outCard in thisTurnOutCard: card = outCard[1] if (card.suit == 2 and card.point == 12) or (card.suit == 3): hasScoreCard = True break if not hasScoreCard: # 如果没有分 pos = kinds[nowSuit][-1] # 出最大的,最大的是猪的话出黑桃里小一点的。 if pos.suit == 2 and pos.point == 12 and len(kinds[nowSuit]) >= 2: pos = kinds[nowSuit][-2] # (如果黑桃只有一张Q了,就只能出去了) else: # 如果出现了分 bigpos = [] smallpos = [] for card in kinds[nowSuit]: if card.point > maxCard: bigpos.append(card) else: smallpos.append(card) if len(smallpos) != 0: # 有小牌, 就出比当前最大的小一的牌 pos = smallpos[-1] else: # 没有小牌,就只能拿分了,用最大的牌来拿分,如果最大的牌是黑Q尽量避免黑Q,选用黑小,无黑小则只能用黑Q了 pos = bigpos[-1] if pos.suit == 2 and pos.point == 12 and len(bigpos) >= 2: pos = bigpos[-2] if REPLAY == True: deck = [i for i in deck if i.suit != pos.suit] kinds = self.split_by_suit(deck) # 按花色分成四类排序 if len(thisTurnOutCard) == 0: # 如果是第一个出牌的 if len(deck) == 13: # 因为是第一回合且第一个出牌,最小的肯定是梅花2 pos = deck[0] else: if (outHeart == False) and (deck[0].suit != 3): # 如果红桃还没出,且当前最小值不是红桃 del kinds[3] # 不能出红桃类 if outQueen == False: if (len(kinds[2]) == 0) or (kinds[2][-1].point >= 12): # 没有黑桃或者黑桃最大值大于Q pos = self.choose_card(kinds, 1) else: # 如果有小黑桃 pos = kinds[2][0] # 出黑桃最小牌,拱猪 else: # 如果黑桃Q已出 pos = self.choose_card(kinds, 1) elif len(thisTurnOutCard) < 3: # 如果电脑不是最后一个出的 maxCard = 0 for outCard in thisTurnOutCard: # 对于每个出牌 card = outCard[1] if card.suit == nowSuit: # 找到这一轮花色的最大值 if card.point > maxCard: maxCard = card.point if len(kinds[nowSuit]) == 0: # 如果没有该花色,优先黑桃Q hasPig = False for spadeCard in kinds[2]: # 黑桃中每个牌 if spadeCard.point == 12: # 如果有黑桃Q pos = spadeCard # 打黑Q HasPig = True break if not hasPig: # 如果没有黑Q del kinds[nowSuit] # 不出黑桃 pos = self.choose_card(kinds, 0) # 在剩余的几个花色里选择最优的 if len(deck) == 13: # 如果是第一次出牌 while (pos.suit == 2 and pos.point == 12) or (pos.suit == 3): # 如果是黑Q或红桃,一直再找最优 pos = self.choose_card(kinds, 0) # flag是0,选最大值 # card = per.hand[pos] else: # 如果有该花色 if len(deck) == 13: # 如果是第一轮出牌 pos = kinds[0][-1] # 第一轮出最大的牌,第一轮肯定是梅花,故suit0 else: bigpos = [] smallpos = [] for card in kinds[nowSuit]: # 分为比当前回合最大牌大和比它小的两摞 if card.point > maxCard: bigpos.append(card) else: smallpos.append(card) if len(smallpos) != 0: # 如果有小的 pos = smallpos[-1] # 就出小的里面最大的 else: pos = bigpos[0] # 大牌里面最小的 if pos.suit == 2 and pos.point == 12 and len(bigpos) >= 2: pos = kinds[nowSuit][1] # 如果没有小的,如果大的里面最小的是黑桃Q且大的有两张牌以上,选择比最小的大一的 elif len(thisTurnOutCard) == 3: # 如果该玩家最后一个出牌 maxCard = 0 # 该花色最大的牌 for outCard in thisTurnOutCard: card = outCard[1] # 每个人出的牌 if card.suit == nowSuit: if card.point > maxCard: maxCard = card.point if len(kinds[nowSuit]) == 0: # 无该花色的牌 hasPig = False for spadeCard in kinds[2]: # 找黑桃Q if spadeCard.point == 12: pos = spadeCard hasPig = True break if not hasPig: del kinds[nowSuit] # 如果没黑桃Q,在除了该花色以外的里面选最优 pos = self.choose_card(kinds, 0) if len(deck) == 13: # 如果是第一次出牌 while (pos.suit == 2 and pos.point == 12) or (pos.suit == 3): # 找到的最优不能是黑桃Q或者红桃 pos = self.choose_card(kinds, 0) else: # 有该花色的牌 if len(deck) == 13: # 第一轮出该花色最大的牌 pos = kinds[0][-1] else: # 其他轮小心猪和红桃 hasScoreCard = False # 看出的牌里是否有猪和红桃 for outCard in thisTurnOutCard: card = outCard[1] if (card.suit == 2 and card.point == 12) or (card.suit == 3): hasScoreCard = True break if not hasScoreCard: # 如果没有分 pos = kinds[nowSuit][-1] # 出最大的,最大的是猪的话出黑桃里小一点的。 if pos.suit == 2 and pos.point == 12 and len(kinds[nowSuit]) >= 2: pos = kinds[nowSuit][-2] # (如果黑桃只有一张Q了,就只能出去了) else: # 如果出现了分 bigpos = [] smallpos = [] for card in kinds[nowSuit]: if card.point > maxCard: bigpos.append(card) else: smallpos.append(card) if len(smallpos) != 0: # 有小牌, 就出比当前最大的小一的牌 pos = smallpos[-1] else: # 没有小牌,就只能拿分了,用最大的牌来拿分,如果最大的牌是黑Q尽量避免黑Q,选用黑小,无黑小则只能用黑Q了 pos = bigpos[-1] if pos.suit == 2 and pos.point == 12 and len(bigpos) >= 2: pos = bigpos[-2] return pos def getScoreFromGame(self): ''' 从游戏状态中获得得分情况 ''' allTurnsCard = [] # 每个回合的出牌情况,总共三层,第一层为玩家i,出牌c,第二层为4个玩家,第三层为出了几个回合[[[1,Card(2,3)],[2,Card(3,3)],[],[]]] for i, j in enumerate(self.history_P0): tmp = [] for k in range(4): now = self.history[(j + k) % 4] if len(now) > i: tmp.append([(j + k) % 4, now[i]]) allTurnsCard.append(tmp) score = {i: 0 for i in range(4)} for turn in allTurnsCard: maximum = 0 turnSuit = turn[0][1].suit s = 0 for c in turn: if c[1].suit == 3: s += 1 if c[1] == Card(12, 2): s += 13 if c[1].suit == turnSuit and c[1].point > maximum: maximum = c[0] score[maximum] += s if 26 in score.values(): # 是否有人收全红 for i,j in score.items(): if j == 26: score[i] = 0 else: score[i]=26 return score def AutoPlay(self): ''' 玩牌函数,玩家0使用了MonteCarloPlay,其他玩家使用规则PlayCards 返回四个玩家得分字典 ''' for turn_index in range(13): first_id = self.find_first() print(f'第{turn_index+1}回合___从玩家{first_id}开始' + '_' * 100) self.history_P0.append(first_id) for i in range(4): out_index = (first_id + i) % 4 print('玩家', out_index) before_hand = self.players[out_index].hand now_p0 = [(p0 + 4 - out_index) % 4 for p0 in self.history_P0] # 此处history_P0需做转换,对于不同的玩家,每个玩家都认为自己是玩家0,玩家0,1,2,3只是相对的指出各个玩家的顺序 if out_index == 0: # 使用MonteCarlo out_card = MonteCarloPlay(self.players[out_index].hand, self.history[(out_index) % 4], self.history[(out_index + 1) % 4], self.history[(out_index + 2) % 4], self.history[(out_index + 3) % 4], now_p0) else: # 使用规则 out_card = self.PlayCards(self.players[out_index].hand, self.history[(out_index) % 4], self.history[(out_index + 1) % 4], self.history[(out_index + 2) % 4], self.history[(out_index + 3) % 4], now_p0) print('hand:', [card2chinese(i) for i in before_hand]) print('out_card:', card2chinese(out_card)) self.players[out_index].hand.remove(out_card) self.history[out_index].append(out_card) print('------------------------------------------') score = self.getScoreFromGame() for i, j in score.items(): print(f'玩家{i}最终得分:{j}') return score if __name__ == '__main__': scores = [] ''' 进行n次游戏,统计得分情况 ''' NUM_GAME = 1 for _ in range(NUM_GAME): game = Game() score = game.AutoPlay() scores.append(score) print(score)
# Variables are information stored in Memory # snake_case # Start with lowercase or underscore # Case sensitive # Don't override keywords iq = 190 # (Here iq is the variable). We are binding 190 to the variable (iq) name = ('Abhishek kabi') course = ('CPython') _intrest_ = ('ML') my_IQ = ('190') # Case sensitive int = 190 # Data Types can also be used in Variables future_age = 80 user_age = future_age - 55 # Method 1 future_age = 80 my_age = future_age - 55 # Method 2 a = my_age print(iq) print(name) print(course) print(_intrest_) print(my_IQ) print(int) print(user_age) print(my_age) # Constants PI = 3.14 print(PI) # Quick way to assign Variables a,b,c = 1,2,3 # Method 1 print(a,b,c) a,b,c = 1,2,3 # Method 2 print(a) print(b) print(c)
#max and min num of array arr={10,20,30,40,50} a=0 #MAX for i in arr: if i>a: a=i print(a) #MIN a for i in arr: if i<a: a=i print(a)
n=int(input("Enter The number : ")) i=1 while i<=n : print(i) #i=i+1
# Write a program to do arithmatic operation using function def sumnum(a, b): ans = a + b print("Addition is :", ans) def subtraction(a, b): ans = a - b print("Subtraction is :", ans) def division(a, b): ans = a / b print("Division is :", ans) def multiply(a, b): ans = a * b print("Multiplication is :", ans) while True: a = float(input("Enter Your First Number: ")) b = float(input("Enter Your Second Number: ")) ch = input("Enter Your Choice: \n 1: Addition \n 2: Subtraction \n 3: Multiplication \n 4: Division") if ch == '1': sumnum(a, b) elif ch == '2': subtraction(a, b) elif ch == '3': multiply(a, b) elif ch == '4': division(a, b) else: print("Please Enter a Valid Choice") cont = input("Do You wish to Continue?(Y/N) : ") if cont == 'n' or cont == 'N': break
def day5(text): steps = 0 num_list = [] with open(text) as f: for line in f: num_list.append(int(line)) x = 0 while x >= 0 and x < len(num_list): steps += 1 old = x x += num_list[x] num_list[old] += 1 print steps def day5b(text): steps = 0 num_list = [] with open(text) as f: for line in f: num_list.append(int(line)) x = 0 while x >= 0 and x < len(num_list): steps += 1 old = x x += num_list[x] if num_list[old] >= 3: num_list[old] -= 1 else: num_list[old] += 1 print steps if __name__ == '__main__': day5('day5test') day5('day5input.txt') day5b('day5input.txt')
number=1 while True: if number<11: print(number) number=number+1 else: break
# Rock paper scissors from chapter 2 import random, sys print('ROCK, PAPER, SCISSORS') #these variables keep track of the number of wins, losses and ties. wins=0 losses=0 ties=0 while True: print('%s Wins, %s Losses, %s Ties' % (wins, losses, ties)) while True: # The player input loop print('Enter your move: (r)ock, (p)aper, (s)cissors, or (q)uit') playerMove=input() if playerMove=='q': print('Thanks for playing') sys.exit() #quits the program if playerMove=='r' or playerMove=='p'or playerMove=='s': break #breaks out of player input loop print('Type one of r, p, s, or q.') #Display what the player chose if playerMove=='r': print('ROCK versus...') elif playerMove=='p': print('PAPER versus...') elif playerMove=='s': print('SCISSORS versus...') #Display what the computer chose randomNumber=random.randint(1,3) if randomNumber==1: computerMove='r' print('ROCK') elif randomNumber==2: computerMove='p' print('PAPER') elif randomNumber==3: computerMove='s' print('SCISSORS') #Display and record the wins/losses/ties: if playerMove==computerMove: print('It is a tie!') ties=ties+1 elif playerMove=='r' and computerMove=='s': print('You win!') wins=wins+1 elif playerMove=='p' and computerMove=='r': print('You win!') wins=wins+1 elif playerMove=='s' and computerMove=='p': print('You win!') wins=wins+1 elif playerMove=='r' and computerMove=='p': print('You lose!') losses=losses+1 elif playerMove=='p' and computerMove=='s': print('You lose!') losses=losses+1 elif playerMove=='s' and computerMove=='r': print('You lose!') losses=losses+1
def discounted(price, discount): price = abs(float(price)) discount = abs(float(discount)) if discount >= 100: price_with_discount = price else: price_with_discount = price - (price * discount / 100) return price_with_discount price1 = -100 discount1 = 10 discounted(price1, discount1) def get_summ(one, two, delimiter='&'): print(f'{one}{delimiter}{two}') L = 'Learn' P = 'Python' get_summ(L, P) def format_price(price): price = int(float(price)) return f'Цена: {price} руб.' price2 = input('Введи цену:') intprice = format_price(price2) print(intprice)
import statistics def mmmv(): i = [int(x) for x in input('Enter your numbers(seperate by spaces" "): ').split()] print('Mean:',statistics.mean(i)) print('Median:',statistics.median(i)) print('Variance:',statistics.variance(i)) try: print('Mode:',statistics.mode(i)) except statistics.StatisticsError as e: print(e) mmmv() ''' mean median mode variance '''
n=int(input("enter n value:")) i=1 sum=0 while i<n: if i%2==0: sum+=i i=i+1 print("sum of even numbers",sum)
list[] print("enter the digits in list") x=int(input()) for i in range(0,x) y=int(input()) list.append(y) if y>1 for y in range(2,y) if(num%i)==0: print(y,"it is not a prime number") else: print(y,"it is a prime number") else: print(y,"it is not a prime number") print list
import heapq def do_math(medians, num): # print(num) max_medians = (num + medians) % 10000 return max_medians def _heappush_max(heap, num): heapq.heappush(heap, -num) def _pushpop_max(heap, num): popped = heapq.heappushpop(heap, -num) return -popped def peek_max_heap(heap): return -heap[0] with open("Median.txt", "r") as text_file: data = text_file.readlines() # data = ['3','1','7'] min_heap = [] max_heap = [-int(data[0])] medians = int(data[0]) for line in data[1:]: num = int(line) if ((len(min_heap) + len(max_heap)) % 2) == 0: if num < peek_max_heap(max_heap): _heappush_max(max_heap, num) else: banana = heapq.heappushpop(min_heap, num) _heappush_max(max_heap, banana) else: if num < peek_max_heap(max_heap): banana = _pushpop_max(max_heap, num) heapq.heappush(min_heap, banana) else: heapq.heappush(min_heap, num) medians = do_math(medians, peek_max_heap(max_heap)) print(medians)
# coding: UTF-8 # # 条件分岐 # ### if # 条件分岐のブロックの中はインデントの深さで判断しています print "---- if ----" int = 50 if int > 20: print "true" if int > 20 and int < 60: print "true" if 20 < int < 60: print "true" if int < 50: print "if" elif int < 60: print "elif" else: print "else" # 変わった書き方 print "true" if int < 50 else "false"
#This program calculates the body mass of a person. #It asks for height in meters and provides weight in kg print("This program calculates your Body Mass Index (BMI) and its classification") weight = float ( input("Type your Weight in Kg (example 80): ") ) height = float ( input("Type your Height in Meters (example 1.80): ") ) bmi = weight / (height ** 2) print("Your BMI is: ", round(bmi, 2)) if (bmi <= 18.5): classification = "Underweight" elif (bmi > 18.5 and bmi <= 24.9): classification = "Normal Weight" elif (bmi > 24.9 and bmi <= 29.9): classification = "Overweight" else: classification = "Obese" print("The classification of your BMI is: ", classification)
grade1 = float ( input("Type the grade of your first test: ") ) grade2 = float(input("Type the grade of your second test: ")) absences = int(input("Type many times have you been absent: ")) total_classes = int(input("Type the total number of classes: ")) avg_grade = (grade1 + grade2) / 2 attendance = (total_classes - absences) / total_classes print("Average grade: ", round(avg_grade, 2)) print("Attendance: ", str(round((attendance * 100),2))+"%") if (avg_grade>= 6): if (attendance>= 0.8): print("You passed!") else: print("You failed because you attended less than 80% of lectures!") elif (attendance>= 0.8): print ("You failed because your score average is less than 6 out of 10") else: print("You failed because you got less than 6 and attended less than 80% of the lectures!")
# coding: utf-8 # # Heaps # ## Overview # # For this assignment you will start by modifying the heap data stucture implemented in class to allow it to keep its elements sorted by an arbitrary priority (identified by a `key` function), then use the augmented heap to efficiently compute the running median of a set of numbers. # ## 1. Augmenting the Heap with a `key` function # # The heap implementation covered in class is for a so-called "max-heap" — i.e., one where elements are organized such that the one with the maximum value can be efficiently extracted. # # This limits our usage of the data structure, however. Our heap can currently only accommodate elements that have a natural ordering (i.e., they can be compared using the '`>`' and '`<`' operators as used in the implementation), and there's no way to order elements based on some partial or computed property. # # To make our heap more flexible, you'll update it to allow a `key` function to be passed to its initializer. This function will be used to extract a value from each element added to the heap; these values, in turn, will be used to order the elements. # # We can now easily create heaps with different semantics, e.g., # # - `Heap(len)` will prioritize elements based on their length (e.g., applicable to strings, sequences, etc.) # - `Heap(lambda x: -x)` can function as a *min-heap* for numbers # - `Heap(lambda x: x.prop)` will prioritize elements based on their `prop` attribute # # If no `key` function is provided, the default max-heap behavior should be used — the "`lambda x:x`" default value for the `__init__` method does just that. # # You will, at the very least, need to update the `_heapify` and `add` methods, below, to complete this assignment. (Note, also, that `pop_max` has been renamed `pop`, while `max` has been renamed `peek`, to reflect their more general nature.) # In[1]: class Heap: def __init__(self, key=lambda x:x): self.data = [] self.key = key @staticmethod def _parent(idx): return (idx-1)//2 @staticmethod def _left(idx): return idx*2+1 @staticmethod def _right(idx): return idx*2+2 def heapify(self, idx=0): l1=Heap._left(idx) r1=Heap._right(idx) max=idx if l1 <len(self.data) and self.key(self.data[l1]) > self.key(self.data[idx]): max=l1 if r1< len(self.data) and self.key(self.data[r1]) > self.key(self.data[max]): max =r1 if (max != idx): temp=self.data[idx] self.data[idx]=self.data[max] self.data[max]=temp self.heapify(max) def add(self, x): self.data.append(x) n=len(self.data)-1 while n >0 and self.key(self.data[self._parent(n)]) < self.key(self.data[n]): temporary=self.data[n] self.data[n]=self.data[self._parent(n)] self.data[self._parent(n)]=temporary n=self._parent(n) def peek(self): return self.data[0] def pop(self): ret = self.data[0] self.data[0] = self.data[len(self.data)-1] del self.data[len(self.data)-1] self.heapify() return ret def __bool__(self): return len(self.data) > 0 def __len__(self): return len(self.data) def __repr__(self): return repr(self.data) # In[2]: # (1 point) from unittest import TestCase import random tc = TestCase() h = Heap() random.seed(0) for _ in range(10): h.add(random.randrange(100)) tc.assertEqual(h.data, [97, 61, 65, 49, 51, 53, 62, 5, 38, 33]) # In[3]: # (1 point) from unittest import TestCase import random tc = TestCase() h = Heap(lambda x:-x) random.seed(0) for _ in range(10): h.add(random.randrange(100)) tc.assertEqual(h.data, [5, 33, 53, 38, 49, 65, 62, 97, 51, 61]) # In[4]: # (2 points) from unittest import TestCase import random tc = TestCase() h = Heap(lambda s:len(s)) h.add('hello') h.add('hi') h.add('abracadabra') h.add('supercalifragilisticexpialidocious') h.add('0') tc.assertEqual(h.data, ['supercalifragilisticexpialidocious', 'abracadabra', 'hello', 'hi', '0']) # In[5]: # (2 points) from unittest import TestCase import random tc = TestCase() h = Heap() random.seed(0) lst = list(range(-1000, 1000)) random.shuffle(lst) for x in lst: h.add(x) for x in range(999, -1000, -1): tc.assertEqual(x, h.pop()) # In[6]: # (2 points) from unittest import TestCase import random tc = TestCase() h = Heap(key=lambda x:abs(x)) random.seed(0) lst = list(range(-1000, 1000, 3)) random.shuffle(lst) for x in lst: h.add(x) for x in reversed(sorted(range(-1000, 1000, 3), key=lambda x:abs(x))): tc.assertEqual(x, h.pop()) # ## 2. Computing the Running Median # # The median of a series of numbers is simply the middle term if ordered by magnitude, or, if there is no middle term, the average of the two middle terms. E.g., the median of the series [3, 1, 9, 25, 12] is **9**, and the median of the series [8, 4, 11, 18] is **9.5**. # # If we are in the process of accumulating numerical data, it is useful to be able to compute the *running median* — where, as each new data point is encountered, an updated median is computed. This should be done, of course, as efficiently as possible. # # The following function demonstrates a naive way of computing the running medians based on the series passed in as an iterable. # In[7]: def running_medians_naive(iterable): values = [] medians = [] for i, x in enumerate(iterable): values.append(x) values.sort() if i%2 == 0: medians.append(values[i//2]) else: medians.append((values[i//2] + values[i//2+1]) / 2) return medians # In[8]: running_medians_naive([3, 1, 9, 25, 12]) # In[9]: running_medians_naive([8, 4, 11, 18]) # Note that the function keeps track of all the values encountered during the iteration and uses them to compute the running medians, which are returned at the end as a list. The final running median, naturally, is simply the median of the entire series. # # Unfortunately, because the function sorts the list of values during every iteration it is incredibly inefficient. Your job is to implement a version that computes each running median in O(log N) time using, of course, the heap data structure! # # ### Hints # # - You will need to use two heaps for your solution: one min-heap, and one max-heap. # - The min-heap should be used to keep track of all values *greater than* the most recent running median, and the max-heap for all values *less than* the most recent running median — this way, the median will lie between the minimum value on the min-heap and the maximum value on the max-heap (both of which can be efficiently extracted) # - In addition, the difference between the number of values stored in the min-heap and max-heap must never exceed 1 (to ensure the median is being computed). This can be taken care of by intelligently `pop`-ping/`add`-ing elements between the two heaps. # In[10]: def running_medians(iterable): # YOUR CODE HERE #raise NotImplementedError() min_heap=Heap(lambda x:-x) max_heap=Heap() median=[] current_median=0 for i, x in enumerate(iterable): if x>= current_median: min_heap.add(x) else: max_heap.add(x) if (len(min_heap.data)-len(max_heap.data)) >1: pop_val=min_heap.pop() max_heap.add(pop_val) elif (len(max_heap.data) - len(min_heap.data))>1: pop_val=max_heap.pop() min_heap.add(pop_val) if len(min_heap.data) == len(max_heap.data): current_median=(min_heap.peek() + max_heap.peek())/2 elif (len(min_heap.data)-len(max_heap.data))==1: current_median=min_heap.peek() elif (len(max_heap.data) -len(min_heap.data))==1: current_median=max_heap.peek() median.append(current_median) return median # In[11]: # (2 points) from unittest import TestCase tc = TestCase() tc.assertEqual([3, 2.0, 3, 6.0, 9], running_medians([3, 1, 9, 25, 12])) # In[12]: # (2 points) import random from unittest import TestCase tc = TestCase() vals = [random.randrange(10000) for _ in range(1000)] tc.assertEqual(running_medians_naive(vals), running_medians(vals)) # In[13]: # (4 points) MUST COMPLETE IN UNDER 10 seconds! import random from unittest import TestCase tc = TestCase() vals = [random.randrange(100000) for _ in range(100001)] m_mid = sorted(vals[:50001])[50001//2] m_final = sorted(vals)[len(vals)//2] running = running_medians(vals) tc.assertEqual(m_mid, running[50000]) tc.assertEqual(m_final, running[-1])
n1 = int(input("digite o primeiro numero: ")) n2 = int(input("digite o segundo numero: ")) n3 = int(input("digite o terceiro numero: ")) if n1>n2>n3: print ("o maior numero e", n1, "e o maior numero e",n3) if n1>n3>n2: print ("o maior numero e", n1, "e o menor numero e", n2) if n2>n1>n3: print ("o maior numero e", n2, "e o menor numero e", n3) if n2>n3>n1: print ("o maior numero e", n2, "e o menor numero e", n1) if n3>n2>n1: print (" o maior numero e", n3, " e o menor numero e", n1) if n3>n1>n2: print ("O maior numero e", n3, " e o menor c numero e", n1)
import math def dist_between(start,end): return math.sqrt(pow((start[0]-end[0]),2)+pow((start[1]-end[1]),2)) def get_best_f_score(input_set,scoredict): idx = input_set.pop() input_set.add(idx) best = idx bv = scoredict[idx] for idx in input_set: if scoredict[idx] < bv: best = idx bv = scoredict[idx] return best def reconstruct_path(start_node,came_from, current_node): p = [current_node] while current_node != start_node: current_node = came_from[current_node] p.append(current_node) return p[::-1] def shortest_path(M,start,goal): print("shortest path called") intersections = M.intersections roads = M.roads frontierset = set([start]) explorededset = set() came_from = {} g_score = {} h_score = {} f_score = {} g_score[start] = 0 h_score[start] = dist_between(intersections[start],intersections[goal]) f_score[start] = g_score[start] + h_score[start] while frontierset: currentintersection = get_best_f_score(frontierset,f_score) frontierset.remove(currentintersection) explorededset.add(currentintersection) neighborsets = set(roads[currentintersection]) if currentintersection == goal: return reconstruct_path(start,came_from, goal) else: for neighbor in neighborsets: if neighbor not in explorededset: tentative_g_score = g_score[currentintersection] + dist_between(intersections[currentintersection],intersections[neighbor]) if neighbor not in frontierset: frontierset.add(neighbor) h_score[neighbor] = dist_between(intersections[neighbor],intersections[goal]) tentative_is_better = True elif (tentative_g_score < g_score[neighbor]): tentative_is_better = True else: tentative_is_better = False if tentative_is_better == True: came_from[neighbor] = currentintersection g_score[neighbor] = tentative_g_score f_score[neighbor] = g_score[neighbor] + h_score[neighbor] print('can not find the shortest path')
list_num = [] list_num.extend([1, 2]) # extending list elements print(list_num) list_num.extend((3, 4, 5.5, 6.8)) # extending tuple elements print(list_num) list_num.extend('ABC') # extending string elements print(list_num) evens = [2, 4, 6] odds = [1, 3, 5] nums = odds + evens print(nums)
#coding=utf-8 #定义求质数的函数 def getprim(n): #我们从3开始,提升效率,呵呵,微乎其微啦 p=3 x=0 while(x<n): result=True for i in range(2,p-1): if(p%i==0): result=False if result==True: x=x+1 rst=p #注意:这里加2是为了提升效率,因为能被双数肯定不是质数。 p+=2 print(rst) #调用函数 getprim(1000) path=path+.. django path=path+djangoPath
from ListNode import ListNode class Solution: def middleNode(self, head: ListNode) -> ListNode: fast = low = head while fast and fast.next: fast = fast.next.next low = low.next return low
def another_merge_sort(array, start, end): if start >= end: return mid = int((start + end) / 2) print(start, end, mid) another_merge_sort(array, start, mid) another_merge_sort(array, mid + 1, end) i = start j = mid + 1 newarray = [] while(i <= mid and j <= end): if array[i] < array[j]: newarray.append(array[i]) i += 1 else: newarray.append(array[j]) j += 1 while i <= mid: newarray.append(array[i]) i += 1 while j <= end: newarray.append(array[j]) j += 1 index = 0 i = start while i <= end: array[i] = newarray[index] i += 1 index += 1 def merge_sort(array): if len(array) == 1: return array mid = int(len(array) / 2) left_array = merge_sort(array[0: mid]) right_array = merge_sort(array[mid: len(array)]) i = j = index = 0 while(i < len(left_array) and j < len(right_array)): if left_array[i] < right_array[j]: array[index] = left_array[i] i += 1 else: array[index] = right_array[j] j += 1 index += 1 while i < len(left_array): array[index] = left_array[i] i += 1 index += 1 while j < len(right_array): array[index] = right_array[j] j += 1 index += 1 return array # print(merge_sort([0, 19, 19, 48, 1, 5, 38])) array = [0, 19, 19, 48, 1, 5, 38] another_merge_sort(array, 0, len(array) - 1) print(array)
from ListNode import ListNode class Stack: def __init__(self): self.head = None def push(self, item): newnode = ListNode(item) if self.head: newnode.next = head head = newnode else: self.head = newnode def pop(self): if self.head is None: return None else: result = self.head.val self.head = self.head.next return result
from ListNode import ListNode # 回文串单链表实现 def is_palindrome_linked_list(head): left_head = None slow_pointer = head fast_pointer = head is_odd = True while fast_pointer.next is not None: if fast_pointer.next.next is not None: fast_pointer = fast_pointer.next.next else: is_odd = False old_slow_pointer = slow_pointer slow_pointer = slow_pointer.next old_slow_pointer.next = left_head left_head = old_slow_pointer if is_odd == False: break if is_odd: slow_pointer = slow_pointer.next while left_head is not None: if slow_pointer is None: return False if left_head.val != slow_pointer.val: return False left_head = left_head.next slow_pointer = slow_pointer.next if slow_pointer is not None: return False return True def main(): node7 = ListNode('7', None) node6 = ListNode('6', node7) node5 = ListNode('5', node6) # None) node4 = ListNode('4', node5) node3 = ListNode('3', node4) node2 = ListNode('3', node3) node1 = ListNode('4', node2) node0 = ListNode('5', node1) print("is_palindrome", is_palindrome_linked_list(node0)) # node6 = ListNode('6', None) # node5 = ListNode('5', node6) # node4 = ListNode('4', node5) # None) # node3 = ListNode('3', node4) # node2 = ListNode('2', node3) # node1 = ListNode('3', node2) # node0 = ListNode('4', node1) # print("is_palindrome", is_palindrome_linked_list(node0)) main()
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode: self.queue = [] self.inOrder(root) for i in range(len(self.queue)): if self.queue[i] == p: break if i == len(self.queue) - 1: return None else: return self.queue[i + 1] def inOrder(self, node: TreeNode): if node == None: return self.inOrder(node.left) self.queue.append(node) self.inOrder(node.right) class Solution2: def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode: if root is None: return None if p.val >= root.val: return self.inorderSuccessor(root.right, p) else: node = self.inorderSuccessor(root.left, p) if node: return node else: return root
class BetterSolution: def isValid(self, s: str) -> bool: mapping = {"]": "[", "}": "{", ")": "("} first = [] for i in s: if i in mapping.keys(): if len(first) == 0: return False if (mapping.get(i) != first.pop()): return False else: first.append(i) if len(first) == 0: return True return False class Solution: def isValid(self, s: str) -> bool: first = [] for i in s: if i == '(': first.append(1) elif i == ')': if len(first) == 0 or first.pop() != 1: return False elif i == '{': first.append(2) elif i == '}': if len(first) == 0 or first.pop() != 2: return False elif i == '[': first.append(3) elif i == ']': if len(first) == 0 or first.pop() != 3: return False if len(first) == 0: return True return False Solution = Solution() print(Solution.isValid("{]}"))
import random print("Welcome to the fortune telling game!!") ques = "" response = "y" while response == "y": ques = input("You may ask a question\n") choice = random.randrange(1,5) if choice == 1: print("Yes") elif choice == 2: print("Yes, definitely") elif choice == 3: print("No") elif choice == 4: print("Maybe, i guess") response = input("\nWould you like to ask me another question? (y/n): ") print("\nThank you, comeback if you have more questions!!")
NUM_QUESTIONS = 5 questions = ( 'Are Connor and Brendan the same person, moving between two positions so quickly as to trick the eye into believing there are two Fletchalls', 'Does James sleep with his 12-inch MacBook under the pillow', 'Are expletives more than 20% of Chris Deng\'s vocabulary', 'Is Nikita secretly premier of a Soviet Government-in-exile', 'Does Chris Kim secretly not know what Soh-Cah-Toa means, but has been hiding it for years because he\'s embarassed to ask about it at this point', ) answers = [ True ] * NUM_QUESTIONS def parse(response: str) -> bool: return (response.lower()[0] in ('t', 'y')) correct = 0 for q, a in zip(questions, answers): if (parse(input(q + '? (T/F) ')) == a): print('Correct!') correct += 1 else: print('Incorrect!') print(f'Result: {correct}/{NUM_QUESTIONS}')
import random HEADS, TAILS = True, False RED = (HEADS, TAILS) BLUE = (TAILS, HEADS) red_wins = 0 blue_wins = 0 red = None blue = None while True: red_win = False blue_win = False p_red = red p_blue = blue red = random.choice((HEADS, TAILS)) blue = random.choice((HEADS, TAILS)) if RED == (p_red, red): red_win = True if BLUE == (p_blue, blue): blue_win = True if red_win and not blue_win: if red_win: print('Red') elif blue_win and not red_win: else: print('None') red_win, blue_win = False, False
#To design an ATM mock up project # Initialize page import random import validation import database import os import funds def init (): print('Welcome to bank PHP') haveAccount = int(input(""" Do you have an account? 1 for yes 2 for no """)) if haveAccount == 1: print('**********Login**********') print('Welcome to the login page \n') login () elif haveAccount == 2: print('Welcome to the registration page \n') register() # banking operations def bankOperations (username): print('Welcome %s' % username) bankOperations2 () def bankOperations2 (): userOptionSelected = int(input(''' Pls what would you like to do 1 for deposit 2 for withdrawal 3 for Account Balance Check 4 for logout 5 to exit ''')) if userOptionSelected == 1: deposit () elif userOptionSelected == 2: withdrawal () elif userOptionSelected == 3: accountBalanceCheck () elif userOptionSelected == 4: login () elif userOptionSelected == 5: exit () else: bankOperations2 () #Bank Operations3 def bankOperations3 (): userOption = int(input(''' What else woould you like to do? select 1 for deposit 2 for withdrawal 3 to check account balance 4 to logout 5 to exit ''')) if userOption == 1: deposit() elif userOption == 2: withdrawal() elif userOption == 3: accountBalanceCheck() elif userOption == 4: login() elif userOption == 5: exit () else: print('You have not selceted a valid option! ') bankOperations3() # register function def register (): useremail = input('What is your email? \n') email_validation = validation.useremail_validation(useremail) if email_validation: firstName = input('What is your first name? \n') lastName = input('What is your last name? \n') userPassword = input('What is your password \n') # Validate the user input for password is_valid_password = validation.password_validation(userPassword) if is_valid_password: username = firstName + lastName accountNumber = accountNumberGenerator() available_amount = funds.create_available_amount(accountNumber) database.create_user(accountNumber, str([firstName , lastName, useremail, userPassword, username])) funds.create_user_funds(accountNumber, available_amount) print(available_amount) print('Your account has been created... ') print("Here's your username " + username) print("Here's your account number %d make sure to keep it safe" % accountNumber ) login () else: register() else: register() # login function def login (): userAccountNumber = input("What is your account number? \n") is_account_valid = validation.account_number_validation(userAccountNumber) if is_account_valid: is_login_valid = validation.login_validation(userAccountNumber) if is_login_valid: user_password = input("What is your password? ") is_password_valid = validation.password_validation(user_password) if is_password_valid: bankOperations2() else: login() else: login() else: print('Account Number is not valid') login() # Account number generator def accountNumberGenerator (): num = random.randrange(1111111111,9999999999) return num # Account Balance Check def accountBalanceCheck(): print('You have %d in your account. ' % availableAmount) bankOperations3() # deposit def deposit (): global availableAmount depositAmount = int(input("How much would you like to deposit? \n")) print('Current balance: %d' % depositAmount) availableAmount =+ depositAmount print('You have %s in your account' % availableAmount) bankOperations3 () # withdrawal def withdrawal (): withdrawalAmount = int(input('How much would like to withdraw? \n')) print('You have withdrawn %d' % withdrawalAmount) print('Amount remaining: %d' % availableAmount - withdrawalAmount) # def check_balance(): #account_number = input('What is your account number? ') #account_balance = funds.read_available_amount(account_number) #print(account_balance) init()
#Original Author: u/gonano4 print("Unknown:Hello, welcome to the fantastic world of Ksea,what is your name?") name=input() print(name+",","a great name for and adventurer,i am Valder, The Master of the fire") import time time.sleep(2) print("Valder:as you are new to Ksea i´ll ask you a question") time.sleep(2) print("Valder:Are you familiar with magic, yes or no?") var=input() time.sleep(.5) if var == "yes": print("Valder:great so you can have this spellbook, it´s about flames") else: print("Valder:then have this iron sword, it will keep you safe") time.sleep(1) print("Valder:folow me") time.sleep(5) print("||Valder and",name,"enter on a pine forest||") time.sleep(3) print("||the forest isstrange at all but bot of them keep going||") print("||suddenly an orc comes out of the woods with a battle axe and an assassin look||") time.sleep(1) found=False if var =="yes": while(found == False): print("*what do you use?*") var99=input() src_str = var99 sub_index = src_str.find('flames') if sub_index > -1 : print("the flames were efective and the orc is now ash") found = True else: found = False print("try again") if var =="no": while(found == False): print("*what do you use?*") var100=input() src_str = var100 sub_index = src_str.find('sword') if sub_index > -1 : print("the sword was effective and the orc lies beheaded on the ground") found = True else: foud = False print("try again") if found==True: time.sleep(5) print("Valder:well done, not all the pople can say they killed an orc") time.sleep(2) print("Valder:come on, we have a long journey until the next village") time.sleep(4) import os os.system("cls") print("||travelling...||") time.sleep(15) print("||you arrive at Sanctur||") time.sleep(2) os.system("cls") print("Valder:here you have 100 coins for saving me today choose wisely where to spend them") coins = 100 time.sleep(2) if var == "yes": print("||you get into a library, you can buy a)sparks spell, b)freeze spell, or c)wolf spell, what do you buy?||") var3=input() else: print("||You arrive at the blacksmith, can buy a) better sword, b)mace or c)axe, what do you buy?||") var4=input() if var3 == "a": print("Mage:congrats! sparks is an awsome spell") if var3 == "b": print("Mage:congrats! freeze is an awsome spell") if var3 == "c": print("Mage:congrats! invocated wolf is an awsome spell") time.sleep(2) print("you have 25 coins left") if var4 == "a": print("Mage:congrats! you purchased a steel sword") if var4 == "b": print("Mage:congrats! you purchased a steel axe") if var4 == "c": print("Mage:congrats! you purchased steel mace") time.sleep(2) coins = coins-75 print("you have",coins, "coins left") time.sleep(5) print("Valder:lets go to sleep") os.system("cls") print("||sleeping...||") time.sleep(15) print("You awake full recovered")
def login(name,password): print ("logged in") def register(name,password): print ("registered") def begin(): print("Welcome to Password Generator login") option = input("login or registor (login,reg): ") if(option!="login" and option!="reg"): option = begin() return option #opt = begin() def GetInfo(opt): if(opt=="login"): name = input("Enter your name: ") password = input("Enter your password: ") login(name,password) else: print("Enter your name and password to register") name = input("Enter your name: ") password = input("Enter your password: ") register(name,password) """ file.close() if(success): print("Login Successful!!!") else: print("Wrong Username or password")"""
def Fibonacci(n): # write code here f1 = 0 f2 = 1 if n == 0: return f1 elif n == 1: return f2 for _ in range(n-1): f2, f1 = f1+f2, f2 return f2 print(Fibonacci(3)) # ⷨ class Solution: def Fibonacci(self, n): # write code here res = [0, 1, 1, 2] while len(res) <= n: res.append(res[-1] + res[-2]) return res[n]
# -*- coding:utf-8 -*- def DFS(matrix, row, col, path, visited): if row < 0 or row >= len(matrix) or col < 0 or col >= len(matrix[0]) or (row, col) in visited: return False if path[0] == matrix[row][col]: if len(path) == 1: return True return DFS(matrix, row+1, col, path[1:], visited| {(row, col)}) or \ DFS(matrix, row-1, col, path[1:], visited| {(row, col)}) or \ DFS(matrix, row, col-1, path[1:], visited| {(row, col)}) or \ DFS(matrix, row, col+1, path[1:], visited| {(row, col)}) class Solution: def hasPath(self, matrix, rows, cols, path): # write code here array = list(matrix) array = [array[i*cols:(i+1)*cols] for i in range(rows)] for i in range(rows): for j in range(cols): visited = set() if DFS(array, i, j, list(path), visited): return True return False print(Solution().hasPath("ABCESFCSADEE",3,4,"BCCED")) print(Solution().hasPath("ABCEHJIGSFCSLOPQADEEMNOEADIDEJFMVCEIFGGS",5,8,"SLHECCEIDEJFGGFIE")) print(Solution().hasPath("AAAAAAAAAAAA",3,4,"AAAAAAAAAAAA")) # ⷨ # -*- coding:utf-8 -*- class Solution: def hasPath(self, matrix, rows, cols, path): # write code here if not matrix: return False if not path: return True curMatrix = [list(matrix[cols*i:cols*i+cols]) for i in range(rows)] for i in range(rows): for j in range(cols): if self.dfs(curMatrix, i, j, path): return True return False def dfs(self, matrix, i, j, p): if matrix[i][j] == p[0]: if not p[1:]: return True matrix[i][j] = '' if i > 0 and self.dfs(matrix, i-1, j, p[1:]): return True if i < len(matrix)-1 and self.dfs(matrix, i+1, j ,p[1:]): return True if j > 0 and self.dfs(matrix, i, j-1, p[1:]): return True if j < len(matrix[0])-1 and self.dfs(matrix, i, j+1, p[1:]): return True matrix[i][j] = p[0] return False else: return False
class TreeLinkNode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None class Solution: def GetNext(self, pNode): # write code here if not pNode: return None p = pNode if pNode.right: # 有右子树 p = pNode.right while p.left: p = p.left return p # 没有右子树但是有父亲节点 while pNode.next and pNode.next.right == pNode: pNode = pNode.next return pNode.next # 解法二 # -*- coding:utf-8 -*- # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: def GetNext(self, pNode): # write code here #1.二叉树为空 if not pNode: return None #2.如果该节点存在右孩子,则它的下一个节点是找到其右孩子并沿着右孩子的左孩子一路向下找,找到最左边的节点 if pNode.right: res = pNode.right while res.left: res = res.left return res #3.如果该节点不存在右孩子,若它是其父亲节点的左孩子,则下一个节点是其父节点;否则,继续向上遍历父节点的父节点,重复上述判断,并返回结果 while pNode.next: temp = pNode.next if temp.left == pNode: return temp pNode = temp return None
### IOT Course 4 Week 3 ### while True: numbers = [1,2,3] i = 0 while i < 3: numbers[i] = input("Enter a number: ") print ("") i += 1 numbers.sort(key=int) print (', '.join(map(str, numbers))) print ("") again = input("Would you like to play again? Type Y or N. ") if again == 'n' or again == 'N': break else: print ("")
x = 0; for x in range (1,100, 10): print (x) if x>50: break y = 10; while y<100: print(y) y+=1 age = 27 if (age<10): print("You are baby") elif (age>10) and (age<20): print ("you are teenager") else: print("you are old")
import urllib2 import json url = "https://questions.aloc.ng/api/q/7?subject=chemistry" json_obj = urllib2.urlopen(url) data = json.load(json_obj) num =0 score =0 for item in data[u'data']: num +=1 print str(num)+')',item[u'question'] print ' a)'+item[u'option'][u'a']+'.\n b)'+item[u'option'][u'b']+'.\n c)'+item[u'option'][u'c']+'.\n d)'+item[u'option'][u'd']+'.' user_answer = raw_input('enter your choice:') if user_answer ==item[u'answer']: print 'correct' score +=1 else: print 'wrong' print 'correct answer is '+item[u'answer'] print 'your total marks are '+ str(score)+'/'+ str(num)
authou='zhenyu' product_list=[ ('iphone',5800), ('Sunsung s7',5688), ('Watch',199), ('Coffee',32), ('Mac Pro',9800), ('Bicycle',1200), ] shopping_list=[] salary=int(input("input your salary: ")) while True: for index,item in enumerate(product_list): print(index,item) user_choise=input("选择要买的商品>>>: ") if user_choise.isdigit(): user_choise=int(user_choise) if user_choise<len(product_list)and user_choise>=0: p_item=product_list[user_choise] if p_item[1]<=int(salary): shopping_list.append(p_item) salary-=p_item[1] print("Added %s into shopping_cart your current balance is %s" %(p_item,salary)) else: print("\033[32;1m你的余额还有[%s]\033[0m" %salary) else: print("product code [%s] is not exist!" % user_choise) elif user_choise=='q': print("-------shopping list-------") for p in shopping_list: print(p) print("your current balance: ",salary)
# --------------------------------------------------------------------- # # File : week3_q2.py # Created : 04/10/2021 16:05 # Authort : Lukasz S. # Version : v1.0.0 # Licencing : (C) 2021 Lukasz S. # # Description : Week 3 question 2 # --------------------------------------------------------------------- book_1 = "The Godfather - Mario Puzo" book_2 = "The Sicilian - Mario Puzo" book_3 = "The Last Don - - Mario Puzo" book_4 = "The Storyteller - Dave Grohl" book_5 = "And Awaye - Bob Mortimer" price_book_1 = 6.99 price_book_2 = 9.99 price_book_3 = 5.25 price_book_4 = 6.75 price_book_5 = 8.95 print("{0:<32} {1:6}".format("Title", "Price")) print("") print("{0:<30} {1:6.2f}".format(book_1, price_book_1)) print("{0:<30} {1:6.2f}".format(book_2, price_book_2)) print("{0:<30} {1:6.2f}".format(book_3, price_book_3)) print("{0:<30} {1:6.2f}".format(book_4, price_book_4)) print("{0:<30} {1:6.2f}".format(book_5, price_book_5)) print("_"*37) print("{0:<30} {1:6.2f}".format("Total", float(price_book_1)+float(price_book_2)+float(price_book_3)+float(price_book_4)+float(price_book_5)))
import random random_list = [random.randrange(-100,100) for i in range(30)] print("\nRandom list of numbers from -100 to 100 is: ", random_list) maxNumber = max(random_list) maxNumberId = 1 + random_list.index(maxNumber) print("\nMax number:", maxNumber, "\nMax number id:", maxNumberId, "\n\n") for i in range(29): if random_list[i] < 0 and random_list[i+1] < 0: print(random_list[i], random_list[i+1], "\n")
import random symbol_wall = '|' symbol_floor = ' ' num_columns = 50 num_lines = 20 my_labyrinth = [] def create_tile(num_columns, num_lines, column_number, line_number): random_even = [symbol_wall] * 6 + [symbol_floor] * 6 random_odd = [symbol_wall] * 4 + [symbol_floor] * 4 if line_number == 0 or column_number == 0 \ or column_number == num_columns - 1 or line_number == num_lines - 1: tile = symbol_wall else: if (line_number % 2 == 0 or column_number % 2 == 0): tile = random.choice(random_even) else: tile = random.choice(random_odd) return tile def create_line(num_columns, num_lines, line_number): curr_line = [] for i in range(num_columns): curr_line.extend(create_tile(num_columns, num_lines, i, line_number)) return curr_line def create_labyrinth(num_columns, num_lines): for i in range(num_lines): my_labyrinth.append(create_line(num_columns, num_lines, i)) return my_labyrinth
coordinates = (1, 2, 3) x, y, z = coordinates #shorthand for applying tuple values to variables! print(x * z) #can be done with a normal list as well.
# import unittest # unittest.main('test_wrap_nicely') import unittest import wrap_nicely class TestWrapNicely(unittest.TestCase): def test_wrap_nicely(self): """ test text wraps properly """ # Setup string = 'A string of text to test to see if it wraps nicely' max_chars = 10 # Calls the_lines = wrap_nicely.wrap_nicely(string, max_chars) # Asserts self.assertEqual(the_lines, [ 'A string', 'of text to', 'test to', 'see if it', 'wraps', 'nicely' ])
# Create 3 dictionaries (dict1, dict2, dict3) with 3 elements each. Perform following operations dict1 = {"Name": "Kapil", "LastName": "Yadava", "Age": 30} dict2 = {'CompanyID': 39, "Name": "Wipro", "Location": "Bangalore"} dict3 = {'AssetID': 12, 'Name': 'Mac Laptop', 'Age': 2} # a) Compare dictionaries to determine the biggest. print(max(dict1.items())) print(max(dict2.items())) print(max(dict3.items())) # b) Add new elements in to the dictionaries dict1, dict2 dict1['YOB'] = 1989 dict2['YOB'] = 1991 dict3['Buy'] = 2017 print(dict1) print(dict2) print(dict3) # c) print the length of dict1, dict2, dict3. print(len(dict3)) print(len(dict1)) print(len(dict2)) # d) Convert dict1, dict2, and dict3 dictionaries as string and concatenate all strings together. dictAll = {} dictAll.update(dict1) dictAll.update(dict2) dictAll.update(dict3) print(dictAll)
# Using the built-in functions on Numbers perform following operations import math import random number = 1.780838373 # a) Round of the given floating point number. Example: # n=0.543 then round it next decimal number, i.e n=1.0 Use round() function print(round(number)) # b) Find out the square root of a given number. (Use sqrt(x) function) print(math.sqrt(number)) # c) Generate random number between 0, and 1 ( use random() function) for i in range(10): print(random.random(), end=" ") print("\n") print("*" * 100) # d) Generate random number between 10 and 500. (Use uniform() function) for i in range(10): print(random.uniform(10, 500), end=" ") print("\n") print("*" * 100) # e) Explore all Math and Random module functions on a given number/List. print(math.ceil(number)) print(math.floor(number)) print(math.factorial(4)) print(math.exp(2)) print(math.sin(45)) print(random.randint(1, 100)) random.seed(7) print(random.random()) random.seed(9) print(random.random()) random.seed(7) print(random.random()) random.seed(9) print(random.random()) li = [1, 4, 5, 10, 2] print(li) random.shuffle(li) print(li)
import sys import time import datetime def vraag23(): print("de politie bied jou een verblijfsverguning aan.") print("ze geven je ook gelijk een plekje om te verblijven met je vrienden") time.sleep(1) print("neem je het aan of niet") print("A : ja je neemt het aan!") print("B : nee je neemt niet aan") antwoord23 = input() if antwoord23.lower() == "a": print("ja natuurlijk je woont nu veilig met je vrienden in Nederland!") sys.exit() elif antwoord23.lower() == "b": print("dit is niet zo slim van je!") print(vraag1()) else: print("kies a,b") def vraag22(): print("de politie bied jou een verblijfsverguning aan.") print("ze geven je ook gelijk een plekje om te verblijven met je famillie") time.sleep(1) print("neem je het aan of niet") print("A : ja je neemt het aan!") print("B : nee je neemt niet aan") antwoord22 = input() if antwoord22.lower() == "a": print("ja natuurlijk je woont nu veilig met je famillie in Nederland!") sys.exit() elif antwoord22.lower() == "b": print("dit is niet zo slim van je!") print(vraag1()) else: print("kies a,b") print(vraag20()) def vraag21(): print("je bent aangekomen in Nederland met je familie.") print("je ziet de politie en je vraagt hun wat je moet doen") time.sleep(1) print("ze vragen jou of je met je famillie mee wil naar het asiel") print("A : ga je mee?") print("B : ga je niet mee?") antwoord21 = input() if antwoord21.lower() == "a": print("ja natuurlijk !") print(vraag22()) elif antwoord21.lower() == "b": print("je gaat niet mee dat is niet slim!") print(vraag1()) else: print("kies a,b") print(vraag21()) def vraag20(): print("je bent aangekomen in Nederland met je vrienden.") print("je ziet de politie en je vraagt hun wat je moet doen") time.sleep(1) print("ze vragen jou of je met vrienden mee wil naar het asiel") print("A : ga je mee?") print("B : ga je niet mee?") antwoord20 = input() if antwoord20.lower() == "a": print("ja natuurlijk !") print(vraag23()) elif antwoord20.lower() == "b": print("je gaat niet mee dat is niet slim!") print(vraag1()) else: print("kies a,b") print(vraag20()) def vraag19(): print("je rent met je familie uit het land en je ziet een smokelaar.") print("hij vraagt jullie 100 euro om jullie naar nederland te brengen") time.sleep(1) print("je hebt in totaal 100 euro bij je met je famillie ga je mee of niet?") print("A : ja natuurlijk") print("B : je gaat niet mee") antwoord19 = input() if antwoord19.lower() == "a": print("je gaat mee met de smokelaar!") print(vraag21()) elif antwoord19.lower() == "b": print("je gaat niet mee dat is niet slim!") print(vraag1()) else: print("kies a,b") print(vraag19()) def vraag18(): print("je rent met je vrienden uit het land en je ziet een smokelaar.") print("hij vraagt jullie 100 euro om jullie naar nederland te brengen") time.sleep(1) print("je hebt in totaal 100 euro bij je met je vrienden ga je mee of niet?") print("A : ja natuurlijk") print("B : je gaat niet mee") antwoord18 = input() if antwoord18.lower() == "a": print("je gaat mee met de smokelaar!") print(vraag20()) elif antwoord18.lower() == "b": print("je gaat niet mee dat is niet slim!") print(vraag1()) else: print("kies a,b") print(vraag18()) def vraag17(): print("je bent aangekomen bij de grens.") print("je wil over de grens") time.sleep(1) print("hoe ga je er langs ?") print("A : rustig aan de politie vragen of jij en je vrienden er langs mogen") print("B : je gaat mee met de andere vluchtelingen") antwoord17 = input() if antwoord17.lower() == "a": print("de politie neemt je mee naar een gevangenis vanwege die vraag die je hem stelt!") print(vraag1()) elif antwoord17.lower() == "b": print("je rent zo snel mogelijk met je vrienden mee met de andere!") print(vraag18()) else: print("kies a,b") print(vraag17()) def vraag16(): print("je bent aangekomen bij de grens.") print("je wil over de grens") time.sleep(1) print("hoe ga je er langs ?") print("A : rustig aan de politie vragen of jij en je familie er langs mogen") print("B : je gaat mee met de andere vluchtelingen") antwoord16 = input() if antwoord16.lower() == "a": print("de politie neemt je mee naar een gevangenis vanwege die vraag die je hem stelt!") print(vraag1()) elif antwoord16.lower() == "b": print("je rent zo snel mogelijk met je familie mee met de andere!") print(vraag19()) else: print("kies a,b") print(vraag16()) def vraag15(): print("je hebt ervoor gekozen om door te lopen met je vrienden .") print("jullie zijn heel moe en willen uitrusten") time.sleep(1) print("ga je zitten of blijven lopen?") print("A : je gaat zitten met je vrienden") print("B : je gaat doorlopen ") antwoord15 = input() if antwoord15.lower() == "a": print("je zit en de kans die je hebt om dood te gaan is te groot om te gaan rusten!!") print(vraag1()) elif antwoord15.lower() == "b": print("je gaat lopen want je kan niet stoppen goeie keus!") print(vraag17()) else: print("kies a,b") print(vraag15()) def vraag14(): print("je bent aangekomen bij de grens.") print("je wil over de grens") time.sleep(1) print("hoe ga je er langs ?") print("A : rustig aan de politie vragen of jij en je vrienden er langs mogen") print("B : je gaat mee met de andere vluchtelingen") antwoord14 = input() if antwoord14.lower() == "a": print("de politie neemt je mee naar een gevangenis vanwege die vraag die je hem stelt!") print(vraag1()) elif antwoord14.lower() == "b": print("je rent zo snel mogelijk met je vrienden mee met de andere!") print(vraag18()) else: print("kies a,b") print(vraag14()) def vraag13(): print("je koos ervoor doortelopen.") print("je begint heel moe te raken met je familie ") time.sleep(1) print("je ziet verderop een plekje waar je kan zitten ga je eventjes rusten met je famillie of blijf je lopen ?") print("A : je blijft lopen") print("B : je gaat ziiten") antwoord13 = input() if antwoord13.lower() == "a": print("je gaat lopen want je kan niet stoppen goeie keus!") print(vraag16()) elif antwoord13.lower() == "b": print("je zit en de kans die je hebt om dood te gaan is te groot om te gaan rusten!") print(vraag1()) else: print("kies a,b") print(vraag13()) def vraag12(): print("je koos ervoor om een rit te zoeken.") print("je ziet een man en hij zegt 30 euro om jullie allemaal naar de grens te brengen van syrie") time.sleep(1) print("ga je mee of blijf je zoeken ?") print("A : je gaat mee") print("B : je gaat door met zoeken") antwoord12 = input() if antwoord12.lower() == "a": print("je stapt in met je famillie dat is een hele goeie keus!") print(vraag16()) elif antwoord12.lower() == "b": print("je gaat door met zoeken dat is niet een goede keus!") print(vraag1()) else: print("kies a,b") print(vraag12()) def vraag11(): print("je koos ervoor doortelopen.") print("je begint heel moe te raken met je vrienden ") time.sleep(1) print("je ziet verderop een plekje waar je kan zitten ga je eventjes rusten met je vrienden of blijf je lopen ?") print("A : je gaat blijft lopen") print("B : je gaat ziiten") antwoord11 = input() if antwoord11.lower() == "a": print("je gaat lopen en je stopt niet goeie keus!") print(vraag15()) elif antwoord11.lower() == "b": print("je zit en de kans die je hebt om dood te gaan is te groot om te gaan rusten!") print(vraag1()) else: print("kies a,b") print(vraag11()) def vraag10(): print("je koos ervoor om een rit te zoeken.") print("je ziet een man en hij zegt 30 euro om jullie allemaal naar de grens te brengen van syrie") time.sleep(1) print("ga je mee of blijf je zoeken ?") print("A : je gaat mee") print("B : je gaat door met zoeken") antwoord10 = input() if antwoord10.lower() == "b": print("je blijft zoeken dat is niet goed!") print(vraag1()) elif antwoord10.lower() == "a": print("je stapt in met je vrienden dat is een hele goeie keus!") print(vraag14()) else: print("kies a,b") print(vraag10()) def vraag9(): print("je koos ervoor om het eten van de man aantenemen.") print("jullie zijn helemaal klaar voor jullie reis hoe gaan jullie verder") time.sleep(1) print(" lopend of ga je zoeken naar een rit?") print("A : lopend") print("B : je gaat iemand zoeken") antwoord9 = input() if antwoord9.lower() == "a": print("je blijft doorlopen!") print(vraag13()) elif antwoord9.lower() == "b": print("je gaat op zoek naar een rit!") print(vraag12()) else: print("kies a,b") print(vraag9()) def vraag8(): print("je koos ervoor om het broodje aannemen.") print("jullie zijn helemaal klaar voor jullie reis hoe gaan jullie verder") time.sleep(1) print("lopend of iemand vragen voor een rit?") print("A : door lopen") print("B : iemand vragen") antwoord8 = input() if antwoord8.lower() == "a": print("je gaat doorlopen!") print(vraag11()) elif antwoord8.lower() == "b": print("je gaat zoeken naar een rit !") print(vraag10()) else: print("kies a,b") print(vraag8()) def vraag7(): print("je koos voor om door te lopen.") print("er komt nu een man naar je toe en hij vraagt of jullie eten nodig hebben") time.sleep(1) print("wat doe je ?") print("A : je zegt ja") print("B : je zegt nee") antwoord7 = input() if antwoord7.lower() == "a": print("ja natuurlijk moet je het aanemen !") print(vraag9()) elif antwoord7.lower() == "b": print("je zegt nee en je verhongerd uiteindelijk!") print(vraag1()) else: print("kies a,b") print(vraag7()) def vraag6(): print("je koos voor om lopend te gaan na paar uur komt er een man naar jullie en vraagt of je een broodje.") time.sleep(1) print("wat doe je ?") print("A : broodje aanemen") print("B : je blijft doorlopen") antwoord6 = input() if antwoord6.lower() == "a": print("ja natuurlijk moet het aanemen !") print(vraag8()) elif antwoord6.lower() == "b": print("je blijft doorlopen dat is niet goed je moet altijd eten aanemen!") print(vraag1()) else: print("kies a,b") print(vraag6()) def vraag5(): print("je loopt al paar uren lang en jullie hebben honger.") print("wat doe je?") print("A : jullie gaan opzoek naar eten") print("B : je blijft doorlopen") antwoord5 = input() if antwoord5.lower() == "a": print("jullie gaan samen opzoek naar eten dat is niet goed want anders verhongeren jullie terwijl je de hele tijd zit te zoeken !") print(vraag1()) elif antwoord5.lower() == "b": print("je blijft doorlopen want je vind dat je zo snel mogelijk moet vluchten uit het land!") print(vraag7()) else: print("kies a,b") print(vraag5()) def vraag4(): print("je zoekt naar je vrienden en je komt ze tegen in de hoofstad jullie zijn van plan om te gaan vluchten.") time.sleep(1) print("hoe ga je?") print("A : met de auto van een vriend") print("B : lopend") antwoord4 = input() if antwoord4.lower() == "a": print("je gaat met de auto niet zo verstandig want er komen alleen maar bommen uit de lucht vallen!") print(vraag1()) elif antwoord4.lower() == "b": print("je gaat lopend goeie keus want je kan dan zien of er een bom op jullie valt!") print(vraag6()) else: print("kies a,b") print(vraag4()) def vraag3(): print("je ziet je familie tijdens de oorlog en bent van plan om met hun het land uit te gaan.") time.sleep(1) print("hoe ga je?") print("A : lopend ") print("B : je vraagt de politie om hulp") antwoord3 = input() if antwoord3.lower() == "a": print("Je gaat lopend dat is een goeie keuze, want de politie zou jou en je familie gelijk meenemen naar de cel.") print(vraag5()) elif antwoord3.lower() == "b": print("je bent niet slim bezig ze nemen jou en je familie mee naar de cel waar je mischien ook wel dood kan gaan !") print(vraag1()) else: print("kies a,b") print(vraag3()) def vraag2(): print ("ik moet het land uit voor mijn eigen veiligheid, omdat er een grote burgeroorlog is..") time.sleep(1) print ("met wie moet ik het land proberen uit te gaan met mijn familie of vrienden?") print("A : familie") print("B : vrienden") antwoord2 = input() if antwoord2.lower() == "a": print("je gaat met je famillie de land uit goeie keus!") print(vraag3()) elif antwoord2.lower() == "b": print("je gaat met vrienden het land uit!") print(vraag4()) else: print("kies a,b") print(vraag2()) def vraag1(): print ("waarom vlucht ik uit syrië ?") print("a : voor mijn eigen veiligheid") print("b : omdat ik het zelf wou") antwoord1 = input() if antwoord1.lower() == "a": print("ja dat klopt!") print(vraag2()) elif antwoord1.lower() == "b": print("nee dat klopt niet") print(vraag1()) else: print("kies a,b") print(vraag1()) print(vraag1())
import itertools import functools32 as functools import networkx as nx import utilities def preprocess(tree, root): """Compute the expected distance of all possible equivalence classes in the tree Parameters ---------- tree : networkx.Graph() an undirected tree root : integer the non-leaf node at which we root the tree to run the algorithm Returns ------ directed : networkx.Graph() a directed tree with the following attributes - 'dists': dictionary, distances in the (undirected) tree - 'root': integer, the non-leaf node at which we root the tree to run the algorithm - 'exp dist': dictionary of dictionaries, associates to a node and a tuple of neighbors the expected distance of the corresponding equivalence class. The parent of the node, if present, is always the first element in the tuple Moreover, every node has the following attributes: - 'size': integer, size of the subtree rooted at the node - 'sum_below': integer, sum of the distances from the node to all nodes in the subtree - 'sum_above': integer, sum of the distances from the node to all nodes NOT in the subtree """ assert root in tree.nodes() assert nx.is_tree(tree) directed = nx.dfs_tree(tree, source=root) #dir DFS tree from source directed.graph['dists'] = nx.all_pairs_dijkstra_path_length(tree) directed.graph['root'] = root size = {} sum_above = {} sum_below = {} exp_dist = {u: {} for u in directed} #SUBTREES SIZES for x in directed: size[x] = utilities.size_subtree(directed, x) utilities.size_subtree.cache_clear() #attach subtree size to nodes for x in directed: directed.node[x]['size'] = size[x] #SUM DISTANCES FROM NODE TO NODES BELOW for x in directed: sum_below[x] = sum_dist_below(directed, x) sum_dist_below.cache_clear() #attach sum dists below to nodes for x in directed: directed.node[x]['sum_below'] = sum_below[x] #SUM DISTANCES FROM NODE TO NODES ABOVE for x in directed: sum_above[x] = sum_dist_above(directed, x) sum_dist_above.cache_clear() #attach sum dists above to nodes for x in directed: directed.node[x]['sum_above'] = sum_above[x] #ORDERED TUPLES OF CHILDREN FOER EVERY NODE ordered_tuples = {} for x in directed: ordered_tuples[x] = ordered_tuples_children(directed, x) #EXP DISTANCE FOR NODE AND SUBSET OF CHILDREN for x in directed: for sel_children in ordered_tuples[x]: exp_dist[x][sel_children] =\ exp_distance(directed, x, sel_children) exp_distance.cache_clear() #attach exp_dist to the graph directed.graph['exp_dist'] = exp_dist #SIZES OF EQUIVALENCE CLASSES size_classes = {x: {} for x in directed} for x in directed: for sel_tuple in ordered_tuples[x]: size_classes[x][sel_tuple] = 0 for c in sel_tuple: size_classes[x][sel_tuple] += directed.node[c]['size'] if size_classes[x][sel_tuple]: #add node x itself size_classes[x][sel_tuple] += 1 if x != directed.graph['root']: p = directed.predecessors(x)[0] #the class is composed by all nodes above and x (if no children #are in the class) or all nodes above and the class computed #before for the set of selected children size_classes[x][(p, ) + sel_tuple] = len(directed) -\ directed.node[x]['size'] +\ max(size_classes[x][sel_tuple], 1) #NORMALIZED EXP DISTANCE FOR NODE AND SUBSET OF CHILDREN INCLUDING PART OF THE TREE #ABOVE for x in directed: if x == directed.graph['root']: for sel_children in ordered_tuples[x][1:]: exp_dist[x][sel_children] =\ exp_distance_parent(directed, x, sel_children)/float(size_classes[x][sel_children]) else: p = directed.predecessors(x)[0] for sel_children in ordered_tuples[x]: exp_dist[x][(p, ) + sel_children] =\ exp_distance_parent(directed, x, sel_children)/float(size_classes[x][(p, ) + sel_children]) #also normalize the expected distance of the class without #nodes above (if it is not empty) if sel_children: exp_dist[x][sel_children] = exp_dist[x][sel_children]\ /float(size_classes[x][sel_children]) exp_distance_parent.cache_clear() #update exp_dist as an attribute to the graph directed.graph['exp_dist'] = exp_dist return directed @functools.lru_cache(maxsize=None) def exp_distance(tree, u, sel_children): """Computes the expected distance of a class composed by a vertex and a subset of its children recursively tree: networkx.Graph() a directed tree u: integer the vertex which is the 'center' of the quivalence class sel_children: tuple subtrees of T_u whose nodes are equivalent to u """ exp_dist = 0 #base case: if u is a leaf if tree.degree(u)==1 or len(sel_children)==0: return exp_dist #compute the total number of nodes below u size_below = sum(tree.node[c]['size'] for c in sel_children) for c in sel_children: ordered_successors = tuple(sorted(tree.successors(c))) exp_dist += exp_distance(tree, c, ordered_successors) #between subtrees terms for c in sel_children: exp_dist += 2*(tree.node[c]['sum_below'] + tree.graph['dists'][u][c]* \ tree.node[c]['size'])*(size_below - tree.node[c]['size']) #add distances from u to all nodes in the selected subtrees for c in sel_children: exp_dist += 2*(tree.node[c]['sum_below'] + tree.graph['dists'][u][c]*\ tree.node[c]['size']) return exp_dist @functools.lru_cache(maxsize=None) def exp_distance_parent(tree, u, sel_children): """Computes the expected distance above a node and in a subset of the children recursively tree: networkx.Graph() a directed tree u: integer the vertex which is the 'center' of the quivalence class sel_children: tuple subtrees of T_u whose nodes are equivalent to u """ #initialize with the expected distance inside the selected children exp_dist_par = tree.graph['exp_dist'][u][sel_children] #if u is the root there is nothing above, this is the base case if u == tree.graph['root']: return exp_dist_par parent = tree.predecessors(u)[0] #other children of parent, different from u other_children = tuple(sorted(filter(lambda x: x != u, tree.successors(parent)))) #add the expected distance of nodes above the parent and in all other #subtrees rooted at the father exp_dist_par += exp_distance_parent(tree, parent, other_children) #Now distances from nodes in sel_children and u to all nodes above and viceversa #first compute the sum of distances from u to the nodes in the selected #children sum_below_sel = sum(tree.node[c]['sum_below'] + tree.graph['dists'][u][c]\ *(tree.node[c]['size']) for c in sel_children) #number of nodes above, excluding u size_above = len(tree) - tree.node[u]['size'] #number of nodes below, counting also u size_below = sum(tree.node[c]['size'] for c in sel_children) + 1 exp_dist_par += 2* (sum_below_sel * (size_above) +tree.node[u]['sum_above']*\ size_below) return exp_dist_par @functools.lru_cache(maxsize=None) def sum_dist_below(tree, u): """Computes the sum of distances from u to all nodes below recursively tree: networkx.Graph() a directed tree size: dictionary associates each node to the size of the subtree rooted at it u: integer identifies the node from which we want to compute distances below """ #base case: if u is a leaf if not tree.successors(u): return 0 sum_below = 0 for c in tree.successors(u): sum_below += sum_dist_below(tree, c) + tree.graph['dists'][u][c] *\ tree.node[c]['size'] return sum_below @functools.lru_cache(maxsize=None) def sum_dist_above(tree, u): """Computes the sum of distances from u to all nodes that are not in the subtree rooted at u tree: networkx.Graph() a directed tree size: dictionary associates each node to the size of the subtree rooted at it u: integer identifies the node from which I want to compute distances below """ #base_case: if u is the root if u == tree.graph['root']: return 0 p = tree.predecessors(u)[0] above_predecessor = sum_dist_above(tree, p) other_children_p = tree.node[p]['sum_below'] - tree.node[u]['sum_below'] -\ tree.graph['dists'][u][p] * tree.node[u]['size'] from_u_to_p = tree.graph['dists'][u][p] * (len(tree) - tree.node[u]['size']) sum_above = above_predecessor + other_children_p + from_u_to_p return sum_above def ordered_tuples_children(tree, x): """generate all possible subsets of children as a list of tuples tree: networkx.Graph() a directed tree u: the nodes for which compute all possible tuples of children """ children = sorted(tree.successors(x)) tuples = [] #generate all possible words on "01" with length len(children) combinations = [''.join(i) for i in itertools.product("01", repeat=len(children))] for comb in combinations: t = tuple() for i in range(len(children)): if comb[i] == '1': t += (children[i],) tuples.append(t) assert len(tuples[0]) == 0 return tuples
# -*- coding:utf-8 -*- # This is the sample about the walk function in OS module # @author Tang Ling # @email [email protected] import sys import os,stat import argparse def rmdir(path): """Recrusivly delete all files in the given directory Arguments: - `path`: """ if os.path.exists(path): for root,dirs,file_names in os.walk(path,topdown=False): for file_name in file_names: del_path(os.path.join(root,file_name)) for dir_name in dirs: del_path(os.path.join(root,dir_name)) os.rmdir(path) def del_path(path): """Delete the given file or folder Arguments: - `path`: """ if check_path(path): if os.path.isdir(path): os.rmdir(path) else: os.remove(path) def check_path(path): """Check the given path is read-only, if that then change it to rw Arguments: - `path`: """ exist = os.path.exists(path) if exist: os.chmod(full_path,stat.S_IWRITE) return exist if __name__=='__main__': parser = argparse.ArgumentParser(description='Remove directory') parser.add_argument('-rm', help='The directory path you want to remove',required=True) args = parser.parse_args() if args.rm and len(args.rm) > 0: print args.rm from time import clock start = clock() rmdir(args.rm) end = clock() print 'Spend times(sec) ', (end-start)/1000000
# Imports from sense_hat import SenseHat # Global variables sense = SenseHat() # Functions def celsius_to_fahrenheit(celsius): """ Return fahrenheit as an integer. """ fahrenheit = 1.8 * celsius + 32 return int(fahrenheit) def decimal_to_binary(num): """ Convert a decimal integer to a list of bits. """ pow2 = 128 binary_list = [] while pow2 >= 1: if (num // pow2) == 1: binary_list.append(num // pow2) num = num - pow2 else: binary_list.append(num // pow2) pow2 = pow2 // 2 return binary_list def display(bit_list): """ Given a list of bits, turn the LED matrix white (0) and blue (1) to display the binary. """ blue = (0,0,255) white = (255,255,255) row = 3 column = 0 while column < 8: if bit_list[column] == 0: sense.set_pixel(column, row, white) else: sense.set_pixel(column, row, blue) column = column + 1 # Main code while True: temp_C = sense.get_temperature() temp_F = celsius_to_fahrenheit(temp_C) temp_bin = decimal_to_binary(temp_F) display(temp_bin)
import collections def flatten(l): """ Flatten a list of lists, even if they are irregular. Original Code from https://stackoverflow.com/a/2158532/1950432 """ for el in l: if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)): yield from flatten(el) else: yield el
num=int(input()) carct=1 simb=1 a=1 while a<=num: if simb%2!=0: value='#' elif simb%2==0: value='%' print(str(carct)+'-'+str(value)) carct=carct+1 simb=simb+1 a=a+1
#!/usr/bin/env python3 import sys from argparse import ArgumentParser from pathlib import Path from deeplator import Translator, SOURCE_LANGS if __name__ == "__main__": parser = ArgumentParser( description="Deeplator is an application enabling translation via the DeepL translator." ) parser.add_argument("-l", "--lang", dest="lang", type=str, help="""The translation code used for translation. Use the format AA-BB where AA is the source language and BB is the output language. Example: EN-DE to translate from English to German.""") parser.add_argument("-f", "--file", dest="path", type=Path, help="Read input from specified file.") parser.add_argument("-s", "--silent", dest="silent", action='store_true', help="Print only the translation.") args = parser.parse_args() if args.lang: lang = args.lang.split("-") if len(lang) != 2: raise Exception("Invalid translation Code.") else: langs = ",".join(SOURCE_LANGS) print("You did not specify a translation code.") print("Available languages are {}.".format(langs)) lang = [] lang_tmp = str(input("Source language: ")) lang.append(lang_tmp) lang_tmp = str(input("Output language: ")) lang.append(lang_tmp) t = Translator(lang[0], lang[1]) if args.path: with open(args.path, "r") as src_file: text = src_file.read() else: if not args.silent: print("Enter the text to be translated. Use Ctrl+D to exit.", file=sys.stderr) lines = sys.stdin.readlines() text = "".join(lines) if not args.silent: print("-" * 16, file=sys.stderr) sentences = t.split_into_sentences(text) translations = t.translate_sentences(sentences) for sentence in translations: print(sentence)
def air_condition(troom, tcond, mode) -> int: if mode == 'fan': return troom elif mode == 'auto': return tcond elif mode == 'heat': return troom if troom > tcond else tcond elif mode == 'freeze': return troom if tcond > troom else tcond def main(): troom, tcond = list(map(int, input().split())) mode = input() print(air_condition(troom, tcond, mode)) # print(air_condition(10, 20, 'heat')) # print(air_condition(10, 20, 'freeze')) # print(air_condition(10, 20, 'auto')) # print(air_condition(10, 20, 'fan')) if __name__ == '__main__': main()
from collections import Counter import re def get_the_most_frequent_word(c, d, text, n): is_digit_first = True if d == 'yes' else False is_case_sensitive = True if c == 'yes' else False text_counter = Counter() key_words = set() if n: for line in text[:n]: line = line.strip() if len(line) > 50: continue key_words.add( line if is_case_sensitive else line.lower()) start = 0 if not n else n for line in text[start:]: if not is_case_sensitive: line = line.lower() line = re.sub(r'[^a-zA-Z0-9_]', ' ', line) for word in line.split(): if word in key_words: continue if word[0].isdigit(): if not is_digit_first: continue if is_digit_first and not (any(map(str.isalpha, word)) or "_" in word): continue text_counter[word] += 1 result = '' if not text_counter else text_counter.most_common(1)[0][0] return result with open('input.txt') as file: lines = file.readlines() n, c, d = lines[0].split() n = int(n) text = [line.strip() for line in lines[1:]] with open('output.txt', 'w') as file: file.write(str(get_the_most_frequent_word(c, d, text, n)))
def get_table_size( a1, b1, a2, b2): tables = [ [a1+a2, max(b1, b2)], [a1+b2, max(b1, a2)], [b1+b2, max(a1, a2)], [b1+a2, max(a1, b2)], ] min_table = tables[0] min_square = min_table[0]*min_table[1] for table in tables: if min_table is table: continue current_square = table[0]*table[1] if current_square < min_square: min_table = table min_square = current_square return min_table with open('input.txt') as file: a1, b1, a2, b2 = map( int, file.read().split()) with open('output.txt', 'w') as file: file.write(' '.join(map(str, get_table_size(a1, b1, a2, b2))))
class Node: def __init__(self, data=None): self.data = data self.out_edges = [] self.in_edges = [] def outgoing_edges(self): return self.out_edges def incoming_edges(self): return self.in_edges def edges(self): return self.out_edges + self.in_edges def link(self, node, incoming=True): if incoming: edge = (node, self) self.in_edges.append(edge) node.out_edges.append(edge) else: edge = (self, node) self.out_edges.append(edge) node.in_edges.append(edge) return edge def connects_to(self, node): for e in self.edges(): if e[0] == node or e[1]==node: return True def __str__(self): return 'Node({})'.format(self.data)
""" Tugas UAS Viky Ardiansyah 171011400218 07TPLE004 Image Processing menggunakan OpenCV untuk mendeteksi objek sederhana IDE: Pycharm """ import os from ShapeClassifier import ShapeClassifier import argparse # handle Command Line Arguments parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--images_path', default='./images', type=str, help='path to the directory containing images') parser.add_argument('--verbose', type=int, default=1, help='verbosity to how visualize results') args = parser.parse_args() # raise an error if wrong arguments are passed assert args.verbose in [0, 1], "verbose be 0 or 1" assert os.path.exists(args.images_path), "path doesn't exists" if __name__ == "__main__": classifier = ShapeClassifier(verbose=args.verbose) # run the classifier on all images present in the directory for _path, _dirs, _images in os.walk(args.images_path): for img in _images: classifier.predict_shape(os.path.join(_path, img)) """ Some comments !!! This Detector has been tested on 35 images containing cropped road signs with 7 different shapes: 1. Square 2. Horizontal Rectangle 3. Vertical Rectangle 4. Diamond 5. Octagon 6. Pentagon 7. Circle The detector classifier all 35 images with 100% accuracy. With OpenCV functions e.g. cv2.inRange(), cv2.contours(), cv2.erode() etc. are pretty fast. Instead of training a deep learning model, simple image processing does a great job with high speed. """
class PriceBasedAllocator(): ''' 1) Resources are grouped based on regions, since each region has different price per hour for its instances 2) Alogrithm adds each resource mutliple times so that total price doesnot exceed the given cap. 3) Since the total price of each subset should not be more than given cap. Resources will be added even if it is less than the given cap 4) This algorithm make sures that two selected set doesnot have the same prefix by using path_added flag 5) Selected resource combinations are sorted based on no of cpus in desc order 6) Each resource is then formatted as mentioned in the main documentation ''' def __init__(self, price, hours, resources): self.hours = hours # Price is divided by total no of given hours. As we are going to use price per hour in the algo self.price = price / float(self.hours) self.resources_dict = resources self.output = [] self.tmp_storage = [] def get_costs(self): for region, resources in self.resources_dict.iteritems(): self.rec_fun(resources, 0, len(resources)) self.output.sort(key = lambda x: x['total_cpus'], reverse = True ) self.preformat_output() return self.output def preformat_output(self): for entry in self.output: # We again multiply with total no of hours entry['total_cost'] = "$" + str(entry['total_cost'] * self.hours) entry['servers'] = entry['servers'].items() def rec_fun(self, resources, start, end): path_added = False while(start < end): self.tmp_storage.append(resources[start]) self.price -= resources[start].price_per_hour if(self.price == 0): self.output.append(self.compute_total_cost_cpus_server_count()) path_added = True elif(self.price < 0): self.tmp_storage.pop() self.price += resources[start].price_per_hour if(len(self.tmp_storage) > 0 and not path_added): self.output.append(self.compute_total_cost_cpus_server_count()) return True else: path_added = self.rec_fun(resources, start, end) self.price += resources[start].price_per_hour self.tmp_storage.pop() start += 1 return path_added def calculate_sum_and_count(self, collector, resource): collector['total_cost'] += resource.price_per_hour collector['total_cpus'] += resource.cpus if(not collector['servers'].get(resource.server_type)): collector['servers'][resource.server_type] = 0 collector['servers'][resource.server_type] += 1 return collector def compute_total_cost_cpus_server_count(self): collector = {"total_cost": 0, "total_cpus": 0, "servers": {}, "region": self.tmp_storage[0].region} return reduce(self.calculate_sum_and_count, self.tmp_storage, collector)
#! /usr/bin/python # quick sort import time def partition(myList, start, end): print "Called. start:%d end:%d List:" %(start, end) print myList[start:end+1] pivot = myList[start] left = start+1 # Start outside the area to be partitioned right = end done = False while not done: sleft = left sright = right while left <= right and myList[left] <= pivot: left = left + 1 #print "left moved from %d to %d" % (sleft,left) while myList[right] > pivot and right >= left: right = right -1 #print "right moved from %d to %d" %(sright, right) if right < left: done= True else: # swap places temp=myList[left] myList[left]=myList[right] myList[right]=temp # swap start with myList[right] temp=myList[start] myList[start]=myList[right] myList[right]=temp print "Result of my sort pivot-position:%d List:" %right print myList[start:end+1] return right def quicksort(myList, start, end): if start < end: # partition the list split = partition(myList, start, end) # sort both halves print "start:%d split:%d end:%d" %(start, split, end) quicksort(myList, start, split-1) quicksort(myList, split+1, end) return myList def main(): myList = [6, 2, 6, 1, 5245, 1, 2, 45, 23, 423, 4214, 412, 3, 6] #[7,2,5,1,29,1,6,4,19,11] #myList = [1,2,1,2] sortedList = quicksort(myList,0,len(myList)-1) print(sortedList) main()
#! /usr/bin/python import utils import sys import logging import sortClass class QuickSort (sortClass.SortClass): @staticmethod def basicSort(myList): # If the length is one or zero # Nothing more to do. # List is already sorted. size = len(myList) if size <= 1: return myList; # Simplest implementation generally choses first element # as pivot (not efficient for pre-sorted lists) # Choose mid point as pivot (helps in pre-sorted lists) # Note: Python 3 returns float on integer division. # Would cause a problem if size is odd. median = size/2 pivot = myList.pop(median); # No conservation of space/memory. # Create two lists # listLessEqual -> holds elements that are <= pivot # listMore -> holds elements that are > pivot listLessEqual = [] listMore = [] # Go through the main list and copy elements # over to the other two lists. for x in myList: if (x.compareKeys(pivot) != 1): listLessEqual.append(x); else: listMore.append(x); # Recursively sort the other two lists listLessEqual = QuickSort.basicSort(listLessEqual); listMore = QuickSort.basicSort(listMore); # Combine the three lists. ''' Common mistake. It is important to add back the pivot element. ''' listLessEqual.append(pivot) final = listLessEqual + listMore; return final #end if __name__ == "__main__": sys.setrecursionlimit(10000) sizes = [5,100] for size in sizes: myList = utils.createInputArray(size) print myList myList = QuickSort.inplaceQuickSort(myList) print myList
p = float(input("what's the principle ")) r = float(input("what's the rate ")) n = int(input("how many periods ")) t = int(input('how many payments per period ')) pv = p * (pow((1 + r/100/n),n*t)) print(pv) def compound_interest(p,r,n,t): balance = p * (pow((1 + r/100/n),n*t)) ci = balance - p print('balance at teh end of the period ', round(balance,2)) print("Interest earned is ", round(ci,2)) compound_interest(5000,10,12,5)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ def recurseTree(node, remainSum, pathNodes, pathList): if not node: return pathNodes.append(node.val) if remainSum == node.val and not node.left and not node.right: pathList.append(list(pathNodes)) else: recurseTree(node.left, remainSum - node.val, pathNodes, pathList) recurseTree(node.right, remainSum - node.val, pathNodes, pathList) pathNodes.pop() pathsList = [] recurseTree(root, sum, [], pathsList) return pathsList
import sqlite3 # The location of the database.sqlite file, used when accessing the database. _sqlite_file = "../../data/database.sqlite" # The papers we have imported as an object. papers = [] # A set of paper ids. paper_ids = set() # A mapping from paper id to paper. paper_id_to_paper = {} # The authors we have imported as an object. authors = [] # A set of author ids. author_ids = set() # A mapping from author id to author. author_id_to_author = {} # A flag so that we don't import twice and override our cleaned data. has_imported = False class Author: """ Class for the authors in the database. """ def __init__(self, author_data): self.id = author_data[0] self.name = author_data[1] self.papers = [] class PaperAuthors: """ Class for the authors in the database. """ def __init__(self, paper_author_data): self.id = paper_author_data[0] self.paper_id = paper_author_data[1] self.author_id = paper_author_data[2] class Paper: """ Class for the papers in the database. """ def __init__(self, paper_data): self.id = paper_data[0] self.year = paper_data[1] self.title = paper_data[2] self.event_type = paper_data[3] self.pdf_name = paper_data[4] self.abstract = paper_data[5] self.paper_text = paper_data[6] self.authors = [] self.stored_title = paper_data[2] def _import_template(table, expression, where = ""): """ Generic database table to object list conversion. @:type table: string @:param table: The name of the table to take the data from. @:type expression: lambda. @:param expression: lambda expression that converts a database object to a class object. @:rtype: list @:return: a list of objects as specified by the lambda expression. """ # Variable that will contain the list of objects. object_list = [] # Connect to the sqlite database, and select all in the specified table. with sqlite3.connect(_sqlite_file) as connection: c = connection.cursor() c.execute('SELECT * FROM "' + table + '" ' + where) for e in c.fetchall(): paper = expression(e) object_list.append(paper) # Finally, return the list of objects. return object_list def _import_authors(): # Convert the authors table to a list of Author class objects. global authors global author_id_to_author global author_ids authors = _import_template('authors', lambda e: Author(e)) author_id_to_author = {author.id: author for author in authors} author_ids = set(author_id_to_author.keys()) return _import_template('authors', lambda e: Author(e)) def _import_papers(): # Convert the papers table to a list of Paper class objects. global papers global paper_id_to_paper global paper_ids papers = _import_template('papers', lambda e: Paper(e), "WHERE NOT (id == 5820 OR id == 6178)") paper_id_to_paper = {paper.id: paper for paper in papers} paper_ids = set(paper_id_to_paper.keys()) return papers def import_data(): global has_imported if has_imported: print("Already imported the database!") return # First import the papers and authors. _import_authors() _import_papers() # Now import the connection between authors and papers locally, as we don't need to store it. paper_to_author_table = _import_template('paper_authors', lambda e: PaperAuthors(e), "WHERE NOT (paper_id == 5820 OR paper_id == 6178)") # Now add the information to both the paper and author objects. for paper_author in paper_to_author_table: paper = paper_id_to_paper[paper_author.paper_id] author = author_id_to_author[paper_author.author_id] paper.authors.append(author.id) author.papers.append(paper.id) has_imported = True # Make sure that the id to paper pointers are correct after importing existing data. def recalculate_paper_pointers(): global paper_id_to_paper paper_id_to_paper = {paper.id: paper for paper in papers}
''' * Python program to use contours to crop the objects in an image. * * usage: python ContourCrop.py <filename> <threshold> ''' import cv2, sys, numpy as np # read command-line arguments filename = sys.argv[1] t = int(sys.argv[2]) # read original image img = cv2.imread(filename) # create binary image gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (5, 5), 0) (t, binary) = cv2.threshold(blur, t, 255, cv2.THRESH_BINARY) # find contours (_, contours, _) = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # create all-black mask image mask = np.zeros(img.shape, dtype="uint8") # draw white rectangles for each object's bounding box for c in contours: (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(mask, (x, y), (x + w, y + h), (255, 255, 255), -1) # apply mask to the original image img = cv2.bitwise_and(img, mask) # display masked image cv2.namedWindow("output", cv2.WINDOW_NORMAL) cv2.imshow("output", img) cv2.waitKey(0)
def factorial(n): i = 1 a = 1 while i <= n: a = a * i i = i + 1 return a b = int(input()) print(b,"! =", factorial(b))
#to randomly select a word import random as rd #to implement GUI import tkinter as tk #create main window main_window = tk.Tk() #window size main_window.geometry("250x250") icon = tk.PhotoImage(file="hangman_icon.png") main_window.iconphoto(False,icon) main_window.title("Hangman!") main_frame = tk.Frame(main_window) canvas = tk.Canvas(main_frame,height=100,width=100) canvas.grid(row=1) #global variable declaration maxAttempts = 4 attemptsCount = 0 word = "" secret = "" hidden = [] game_started = False #tkinter variables attempt_var = tk.StringVar() info_var = tk.StringVar() word_var = tk.StringVar() guess_btn_var =tk.StringVar() #string variables attempt_text = "You have "+str(maxAttempts-attemptsCount)+" attempts remaining..." info_text = "Enter a character and press Guess to check!" enter_word_text = "Enter a character: " welcome_text = "Welcome to Hangman!" start_text = "Start!" guess_text = "Guess!" play_again_text = "Play Again!" you_lost_text = "Game over! You lost! Play again?" victory_text = "You got it! You Won! Play again?" exit_text = "Exit!" blank_text = "" #tkinter variable initialization attempt_var.set(blank_text) info_var.set(info_text) guess_btn_var.set(guess_text) #frames to add multiple elements in same grid frame_one = tk.Frame(main_frame) frame_two = tk.Frame(main_frame) #labels to show information in window attempt_label = tk.Label(main_frame,textvariable=attempt_var).grid(row=0) #matrix_label = tk.Label(main_frame,textvariable=matrix_text_var).grid(row=1) info_label = tk.Label(main_frame,textvariable=info_var).grid(row=3) enter_word_label = tk.Label(frame_one,text=enter_word_text) #text box enter_word_entry = tk.Entry(frame_one,width=5) #packing frames and button in grids frame_one.grid(row=4) exit_btn = tk.Button(frame_two,text=exit_text,height=1,width=12,command=main_frame.quit) frame_two.grid(row=5) exit_btn.pack(side='left') # method to get random word def get_word(): random_no = rd.randrange(44) with open('words.txt') as f: lines= f.readlines() word= lines[random_no] return word # method checks if game is started or not. #(called when button "play again" or "guess" button is pressed) def check(): if not game_started: play() else: guess() #method conatains: #first time intialization of some labels in window #variables intialization def play(): #use of global variables global game_started global attemptsCount global hidden global attempt_text global word global secret #clear text box on mthod call enter_word_entry.delete(0,"end") #variables intialization game_started = True guess = "" attempt_text = "You have "+str(maxAttempts-attemptsCount)+" attempts remaining..." hidden = [] attemptsCount = 0 #label text change attempt_var.set(attempt_text) #get a random word word = get_word() secret = word[:-1] #create a hidden word of same size for char in word: hidden.append('_') #remove last element in line(carriage return) hidden.pop() #display text box enter_word_label.pack(side='left') enter_word_entry.pack(side='left') #display hidden string hiddenString = ' '.join(hidden) word_text = "Word : "+hiddenString word_var.set(word_text) #display hangman matrix draw_hangman(0) #shows basic information info_var.set(info_text) guess_btn_var.set(guess_text) #shows hidden word in window word_label = tk.Label(main_frame,textvariable=word_var).grid(row=2) #updates hangman matrix when called based on attempts def draw_hangman(attempts): global canvas if(attempts==0): #clear cnavas canvas.delete("all") #stand canvas.create_line(10,90,90,90,fill="black") canvas.create_line(25,90,25,10,fill="black") canvas.create_line(25,15,80,15,fill="black") canvas.create_line(25,35,45,15,fill="black") #rope canvas.create_line(70,15,70,30,fill="black") if(attempts==1): #clear cnavas canvas.delete("all") #stand canvas.create_line(10,90,90,90,fill="black") canvas.create_line(25,90,25,10,fill="black") canvas.create_line(25,15,80,15,fill="black") canvas.create_line(25,35,45,15,fill="black") #rope canvas.create_line(70,15,70,30,fill="black") #face canvas.create_oval(65,30,75,40,outline="black") if(attempts==2): #clear cnavas canvas.delete("all") #stand canvas.create_line(10,90,90,90,fill="black") canvas.create_line(25,90,25,10,fill="black") canvas.create_line(25,15,80,15,fill="black") canvas.create_line(25,35,45,15,fill="black") #rope canvas.create_line(70,15,70,30,fill="black") #face canvas.create_oval(65,30,75,40,outline="black") #neck canvas.create_line(70,40,70,43,fill="black") #stomach canvas.create_oval(64,42,76,60,outline="black") if(attempts==3): #clear cnavas canvas.delete("all") #stand canvas.create_line(10,90,90,90,fill="black") canvas.create_line(25,90,25,10,fill="black") canvas.create_line(25,15,80,15,fill="black") canvas.create_line(25,35,45,15,fill="black") #rope canvas.create_line(70,15,70,30,fill="black") #face canvas.create_oval(65,30,75,40,outline="black") #neck canvas.create_line(70,40,70,43,fill="black") #stomach canvas.create_oval(64,42,76,60,outline="black") #hands canvas.create_line(66,44,60,60,fill="black") canvas.create_line(74,44,80,60,fill="black") if(attempts==4): #clear cnavas canvas.delete("all") #stand canvas.create_line(10,90,90,90,fill="black") canvas.create_line(25,90,25,10,fill="black") canvas.create_line(25,15,80,15,fill="black") canvas.create_line(25,35,45,15,fill="black") #rope canvas.create_line(70,15,70,30,fill="black") #face canvas.create_oval(65,30,75,40,outline="black") #neck canvas.create_line(70,40,70,43,fill="black") #stomach canvas.create_oval(64,42,76,60,outline="black") #hands canvas.create_line(66,44,60,60,fill="black") canvas.create_line(74,44,80,60,fill="black") #legs canvas.create_line(66,60,65,75,fill="black") canvas.create_line(74,60,75,75,fill="black") #initilizes variables to play again when player wins def victory(): global attemptsCount global game_started attemptsCount = 0 info_var.set(victory_text) game_started = False draw_hangman(attemptsCount) guess_btn_var.set(play_again_text) #method called when guess button is pressed def guess(): #use of global variables global attemptsCount global game_started global attempt_text global word global hidden #create list of word as strings are immutable word_list = list(word) #shows updated attempt count on window attempt_text = "You have "+str(maxAttempts-attemptsCount)+" attempts remaining..." attempt_var.set(attempt_text) #updates hangaman matrix draw_hangman(attemptsCount) #get text box text in variable and clear text in text box entered_str= str(enter_word_entry.get()) enter_word_entry.delete(0,"end") #if text box is blank show info if(len(entered_str)==0): info_var.set("Please Enter any character.") #if text box contains more than one character if(len(entered_str)>1): info_var.set("Enter ONE Character only!") #panelty! attemptsCount+=1 #update ateempt count and hangman matrix attempt_text = "You have "+str(maxAttempts-attemptsCount)+" attempts remaining..." attempt_var.set(attempt_text) draw_hangman(attemptsCount) #if text box contains one char exact else: #if guess is correct if entered_str in word: #loop to every alphabet of word for i in range(len(word)): #store it in temp variable char = word[i] #if temp matches in word if char == entered_str: #update hidden string and word using word list(string immutable) hidden[i] = word[i] word_list[i] = '_' word = ''.join(word_list) #show updated word in window hiddenString = ' '.join(hidden) word_text = "Word : "+hiddenString info_var.set("Yeah! '"+entered_str+"' is the correct guess!") word_var.set(word_text) #if there are no blanks in the hidden word player wins if '_' not in hidden: #call victory victory() #if guess is incorrect else: #panelty! attemptsCount+=1 #update information on window attempt_text = "You have "+str(maxAttempts-attemptsCount)+" attempts remaining..." attempt_var.set(attempt_text) info_var.set("Wrong! '"+entered_str+"' is not in the word!") #update hangman matrix draw_hangman(attemptsCount) #max attempts reached if(attemptsCount>=4): game_started = False draw_hangman(attemptsCount) attemptsCount=0 guess_btn_var.set(play_again_text) info_var.set(you_lost_text) word_text = "Word : "+secret word_var.set(word_text) #program entry (main) if __name__ == "__main__": #show welcome text on first time starting the game guess_btn_var.set(start_text) info_var.set(welcome_text) guess_playAgain_btn = tk.Button(frame_two,textvariable=guess_btn_var,height=1,width=12,command=check) guess_playAgain_btn.pack(side='left') draw_hangman(4) #lets main window loop until closed main_frame.pack() main_window.mainloop()
import matplotlib.pyplot as plt import numpy as np def line(w, th=0): w2 = w[2] + .001 if w[2] == 0 else w[2] return lambda x: (th - w[1] * x - w[0]) / w2 def plot(fs, s, t): x = np.arange(-2, 3) col = 'ro', 'bo' for c, v in enumerate(np.unique(t)): p = s[np.where(t == v)] plt.plot(p[:, 1], p[:, 2], col[c]) for f in fs: plt.plot(x, f(x)) plt.axis([-2, 2, -2, 2]) plt.show()
''' Created on Sep 17, 2010 @author: ashwin Licensed to Ashwin Panchapakesan under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Ashwin licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' def resolve(n): """The input n is an integer. This function will returns a tuple. If n is expressible as the sum of two cubes, the returned tuple will contain the two integers, the sum of whose cubes is n. If no two such integers exist, then an empty tuple is returned""" for i in range(n): j = -1 sum = i**3 while sum < n: j += 1 sum = (i**3) + (j**3) if sum == n: return (i, j) return () def run(n): answer = resolve(n) if answer: print "%d can be expressed as the sum of the cubes of %d and %d" %(n, answer[0], answer[1]) else: print "%d cannot be expressed as the sum of two cubes" %n if __name__ == "__main__": while True: try: input = int(raw_input("Enter a number: ")) run(input) except ValueError: print "Your input was not a number. Try again."
''' Created on Sep 24, 2010 @@author: ashwin Licensed to Ashwin Panchapakesan under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Ashwin licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from math import sqrt def primeNumbers(n): """ return a list of prime numbers such that all numbers in the list are at most n 1 is a prime number""" answer = [] if n <= 2: answer.append(n) else: for i in range(3, n+1, 2): prime = True for p in answer: if i%p == 0: prime = False break if prime: answer.append(i) return answer def generate(n): """ Yield the first n prime numbers""" primes = [2] curr = 2 for _ in range(n-1): p = next(curr, primes) primes.append(p) curr = p yield p def next(n, primes=[]): """ Return a number p such that 1. p is co-prime to every number in primes 2. p>n and p-n is as small as possible""" if primes: curr = n+1 while 1: if isPrime(curr, primes): return curr else: curr += 1 else: primes = [2] for i in range(3, n+1, 2): if isPrime(i, primes): primes.append(i) curr = n+1 while not isPrime(curr): curr += 1 return curr def sumOfTwoPrimes(n): """Express n>3 as the sum of two primes or print that it's not possible to do so""" primes = primeNumbers(n) for p in primes: if n-p in primes: return (p, n-p) return () def isPrime(n, primes=[]): """ Return True iff n is a prime number. If primes is non-empty, return true iff n is co-prime to every number in primes. """ if not len(primes): if n <= 2: return True elif n%2 == 0: return False else: # prime = True # for i in range(3, n, 2): # if n%i == 0: # prime = False # if prime: # return True for i in range(3, int(sqrt(n))+1, 2): if not n%i: return False return True else: for p in primes: if not n%p: return False return True if __name__ == "__main__": import timeit # for i in range(4, 20): # doable = sumOfTwoPrimes(i) # if doable: # print "%d can be represented as the sum of two primes: %d and %d:" %(i, doable[0], doable[1]) # else: # print "%d cannot be represented as the sum of two primes" %i # for i in generate(9976): print i # nums = [2,3,10,32,85,31,104491] # for i in nums: # print i, ["C","P"][int(isPrime(i))] # # t = timeit.Timer("for i in generate(9976): print i", "from __main__ import generate") # print t.timeit(1) print next(104491)
import random while True: try: usernumber = int(input("Guess a number, 1 through 100... ")) while usernumber != random.randrange(1,101): print(int(input("Try again: "))) else: print("Congratulations, You've guessed correctly!") input() except ValueError: print("Invalid Input")
########################################################################### ##temperatures = [60,65,73,54,78,75] ## ##def avg(x): ## return sum(x) / len(x) ## ##i = 0 ##while i < len(temperatures): ## print(temperatures[i], "Degress Fahrenheit") ## i += 1 ## ##print("The average of all the temperatures is: " + str(avg(temperatures)) + " Degrees Fahrenheit") ########################################################################### ###binItems = [5, 12, 14, 18, 129, 200, 397, 408, 500, 550, 600] ## ##max = float('-inf') ## ##for i in binItems: ## if i > max: ## max = i ## ##print(i) ########################################################################### def rug_cost(l, w, c): return l * w / c print(rug_cost(30, 20, 7.00))
import sys while True: def grade(x): if x > 100: print("Error") elif x >= 90 and x <= 100: print("A") elif x >= 80 and x <= 89: print("B") elif x >= 70 and x <= 79: print("C") elif x >= 60 and x <= 69: print("D") elif x <= 59: print("F") x = int(input("Enter your grade percentage: " + "%")) grade(x)
def fib_standard(n): if n < 2: return 1 else: return fib(n-1)+fib(n-2) def fib_dynamic_programming_aux(n,F): if n < 2: return 1 else: if not F[n-1]: F[n-1] = fib_dynamic_programming_aux(n-1,F) if not F[n-2]: F[n-2] = fib_dynamic_programming_aux(n-2,F) return F[n-1]+F[n-2] def fib_dynamic_programming(n): F = [None for x in range(n)] return fib_dynamic_programming_aux(n,F)
# Time: O(nlog(n) + mlog(m)), time for sorting first and second array # Time for iteration ( which is O(max(n, m)) ) is dominated by time for sorting # Space: O(1) def smallestDiff(arrayOne, arrayTwo): arrayOne.sort() arrayTwo.sort() i = 0 j = 0 smallest = float("inf") current = 0 pairs = [] while i < len(arrayOne) and j < len(arrayTwo): firstNum = arrayOne[i] secondNum = arrayTwo[j] if firstNum < secondNum: current = secondNum - firstNum i += 1 elif firstNum > secondNum: current = firstNum - secondNum j += 1 else: return [firstNum, secondNum] if smallest > current: smallest = current pairs = [firstNum, secondNum] return pairs x = [8, 14, 19, 36, 9] y = [81, 27, 33, 43, 11] print(smallestDiff(x, y))
# Time: O(log(n)) and space: O(log(n)) def binarySearch(array, target): binarySearchHelper(array, target, 0, len(array) - 1) def binarySearchHelper(array, target, left, right): if left > right: return -1 middle = (left + right) // 2 if target == array[middle]: return middle elif target < array[middle]: return binarySearchHelper(array, target, left, middle - 1) else: return binarySearchHelper(array, target, middle + 1, right) # Iterative way # Time: O(log(n)) and space: O(1) def binarySearch(array, target): binarySearchHelper(array, target, 0, len(array) - 1) def binarySearchHelper(array, target, left, right): while left < right: middle = (left + right) // 2 if target == array[middle]: return middle elif target < array[middle]: right = middle - 1 else: left = middle + 1 return -1 # ======================================================================================================= ''' Modularizing code for reusability for different problems based on binary search ''' class BinarySearch: def search(self, array, key, ascending = True): start = 0 end = len(array) - 1 while start <= end: mid = start + (end - start) // 2 if array[mid] == key: return mid elif key < array[mid]: if ascending: end = mid - 1 else: start = mid + 1 else: if ascending: start = mid + 1 else: end = mid - 1 return -1 def firstOccuerence(self, array, key, first = True): # if first = True, i.e first occurence else last occurence start = 0 end = len(array) - 1 firstIdx = -1 lastIdx = -1 while start <= end: mid = start + (end - start) // 2 if array[mid] == key: if first: firstIdx = mid # once the key is found, we don't know whether it is first occuerence or not so # move to the left side again end = mid - 1 else: lastIdx = mid # once the key is found, we don't know whether it is last occuerence or not so # move to the right side again start = mid + 1 elif key < array[mid]: end = mid - 1 else: start = mid + 1 return firstIdx if first else lastIdx def countOfElement(self, array, key): # since the array is sorted, the repeated key will always be together, therefore the window length # of that repeated key = count of key. # e.g [1, 2, 2, 2, 5], count = indexOfLastOccurence - indexOfFirstOccurence + 1 -> (3 - 1) + 1 = 3 firstIdx = self.firstOccuerence(array, key, first = True) lastIdx = self.firstOccuerence(array, key, first = False) if firstIdx == -1 and lastIdx == -1: return 0 return (lastIdx - firstIdx) + 1 def countSortedArrayIsRotated(self, array): ''' when sorted array is rotated, then number of times it is rotated = indexOfMinElement. And min element is the only element in sorted rotated array, which is smaller than it's previous element as well as next element. ''' lenArr = len(array) if lenArr == 0: return -1 if lenArr == 1: return 0 start = 0 end = lenArr - 1 while start <= end: mid = start + (end - start) // 2 # checking for the prev in circular way prev = (mid - 1 + lenArr) % lenArr # checking for next in circular way nextToMid = (mid + 1) % lenArr if array[mid] <= array[prev] and array[mid] <= array[nextToMid]: return mid # if mid > start, i.e left subarray is sorted, we need to go to right, where minimum will be present # in unsorted array if array[mid] > array[start]: start = mid + 1 # i.e right subarray is sorted we need to go to left elif array[mid] <= array[end]: end = mid - 1 return -1 def searchInRotatedSortedArray(self, array, key): minIdx = self.countSortedArrayIsRotated(array) # Now we know the index of minimum element, now as the key must be greater than min element # and as sorted array is rotated, we have to apply binary search on (start to minIdx) and (minIdx to end) # if both return -1, then key is not present in array, else return index of key left = self.search(array[ 0:minIdx ], key) # ... + minIdx because, consider this [7, 11, 12, 5, 6], minIdx = 3, then when we will do binary search # on [minIdx: len(array)], it will return 1, but in input array it's # index will be 3 (minIdx) + 1(search result of bs on [minIdx:end]) right = self.search(array[ minIdx:len(array) ], key) + minIdx # instead of these 3 lines, we know one of them will be -1, therefore we can return max(left, right) # if both are -1, then -1 will be returned else index of key will be returned if left == -1 and right == -1: return -1 return left if left != -1 else right def searchElementInNearlySortedArray(self, array, key): # nearly sorted array means, element at index i will be at index (i - 1) OR at i OR at (i + 1) in sorted array # handling edge cases in starting only if array[0] == key: return 0 if array[-1] == key: return len(array) - 1 start = 1 end = len(array) - 2 while start <= end: mid = start + (end - start) // 2 if array[mid] == key: return mid elif mid > 0 and array[mid - 1] == key: return (mid - 1) elif mid < (len(array) - 1) and array[mid + 1] == key: return (mid + 1) # since now we have compared key with mid-1, now comparing with mid-2 if key < array[mid - 2]: end = mid - 2 elif key > array[mid + 2]: start = mid + 2 return -1 def findFloorAndCeil(self, array, key): # floor means, the closest element which is <= key # ceil means the closest element which is >= key # if parameter floor = False, then we will find ceil start = 0 end = len(array) - 1 floor = -1 ceil = -1 while start <= end: mid = start + (end - start) // 2 # i.e if we have key present in the array then this is only floor and ceil if array[mid] == key: return mid # i.e for floor we want the key to be greater than array[mid] | array[mid], ..., key # for ceil, we want the key to be less than array[mid], key, ..., array[mid] (then only it will be potential ceil) elif key < array[mid]: ceil = mid end = mid - 1 # i.e key > array[mid], i.e array[mid] < key then it is possible candidate for floor else: floor = mid start = mid + 1 return floor, ceil array = [7, 11, 12, 5, 6] bs = BinarySearch() # if array is right rotated print(len(array) - bs.countSortedArrayIsRotated(array)) # if array is left rotated print(bs.countSortedArrayIsRotated(array)) ''' Since in this case, the array is infinite, we don't know the end of the array, so we start with start=0 and assume that end=1. ''' def searchInInfiniteSortedArray(arr, x): start = 0 end = 1 # while the end element is less than the x, update the start=end and double the end. # e.g say arr=[1,2,3,4,....] say element to be searched is 5. initially start=0, end=1 # since arr[end]<x, then we know the x will never be present before end index, i.e x=5 will never be present before index 1 as array is sorted. # therefore update the start=end first and then double the range for end. while arr[end] < x: start = end end = end * 2 # after the above loop, the x will be bounded by the start and end, such that arr[start] < x < arr[end] while start <= end: mid = start + (end - start) // 2 if arr[mid] == x: return mid elif x < arr[mid]: end = mid - 1 else: start = mid + 1 return -1 ''' The array is unsorted, and we have to find the peek element. Peek element is basically element at index at index i which is greater than element at i-1 and also i+1. There can be multiple peek elements and you can return any of the peek element. Also for the elements at index 0 and index n-1, for index 0, it is also peek element if it is greater than element at index 1 (even though it does not have its i-1 element). Similarly for the element at n-1, if it is greater than n-2, then it is also peek element (even though it does not have right element) ''' def peekElement(arr): start = 0 end = len(arr) - 1 n = len(arr) while start <= end: mid = start + (end - start) // 2 if mid > 0 and mid < n-1: if (arr[mid] > arr[mid - 1]) and (arr[mid] > arr[mid + 1]): return mid if arr[mid - 1] > arr[mid]: end = mid - 1 elif arr[mid + 1] > arr[mid]: start = mid + 1 elif mid == 0: if arr[0] > a[1]: return 0 else: return 1 elif mid == n-1: if arr[n-1] > arr[n-2]: return n-1 else: return n-2 return -1 arr = [5, 10, 20, 15] print( peekElement(arr) ) ''' arr: each index i is one book and arr[i] represents number of pages in book. k: number of students we have to allocate books to student but with few restrictions: 1) one student have to read the entire book, it is not allowed that one student reads half book and other student reads remaining half. 2)Each student should have atleast one book. 3) Books should be alloted in the contionous manner, e.g we have arr = [10, 20, 30, 40] and k=2, then student1 can get (10) and student2 can get (20, 30, 40) OR student1 (10, 20) and student2 (30, 40) OR student1 (10, 20, 30) and student2 (40). 3) we have to minimize the maximum number of pages one student should read, e.g in the first case max number of pages one student can read is 90, in case2 it is 70 and in case3 it is 60. So we have to return 60. ''' def isMidValid(arr, mid, k): pagesRead = 0 students = 1 # this will keep count of number of students, initially we have one student only for pages in arr: pagesRead += pages # if at any time number of pages read > mid (max capacity for every student) if pagesRead > mid: # then we have introduce new student and set it's number of pages read=pages of current # book students += 1 pagesRead = pages # if at any time number of students (having the capacity=mid) > then the given k # therefore this capacity is invalid, inorder to have only k students, we have to # increase the capacity, therefore start=mid+1 is there if students > k: return False # if we have not reached return False, then it means number of students=k, and therefore # the mid (capacity of student) is valid, therefore return True return True def bookAllocation(arr, k): # if number of students given is greater than number of books, then we cannot allocate each student # one book, therefore return -1 if k > len(arr): return -1 # here range between start and end represents number of pages that student can read. # since each student should have atleast one book, therefore we start the range with book having # max number of pages start = max(arr) # maximum number of pages that one student can read is sum of all the pages given in array. end = sum(arr) result = float("inf") while start <= end: # this mid represents max number of student and we have to check if this mid is valid. mid = start + (end - start) // 2 if isMidValid(arr, mid, k): result = min( result, mid ) print(result) # now we know the current mid is valid, but we have to find minimum value for mid # in the range, so bring end=mid-1 end = mid - 1 else: # if the mid is invalid then start = mid + 1 return result def medianOfTwoSortedArrays(array1, array2, start_a, end_a, start_b, end_b): # when the number of elements in both the array are 2 if (end_a - start_a == 1) and (end_b - start_b == 1): median = ( max( array1[start_a], array2[start_b] ) + min( array1[end_a] + array2[end_b] ) ) / 2 return median # indices of the medians of two arrays m1 = (start_a + end_a) // 2 m2 = (start_b + end_b) // 2 # if the median of both the arrays are same, then the median of two sorted arrays will also be same if array1[m1] == array2[m2]: return array[m1] # if the median of array1 is less than median of array2 # then, ignore the a1,a2...,m1 (first half of array1) # and ignore second half of array2 elif array1[m1] < array2[m2]: start_a = m1 end_b = m2 else: # median of array2 < median of array1 # then ignore first half of array2 and ignore second half of array1 start_b = m2 end_a = m1 return medianOfTwoSortedArrays(array1, array2, start_a, end_a, start_b, end_b)
''' Idea is, we will use the concept of peeks and valleys, whenever we found valley we will start expnading towards it's left and right, if we are heading to the peek, then continously increase reward. ''' def minRewards(array): n = len(array) # setting the initial reward as 1 for all students rewards = [1] * n for i in range(1, n-1): # if we found the valley if (array[i] < array[i-1]) and (array[i] < array[i+1]): expand(i, array, rewards) return rewards def expand(i, array, rewards): leftIdx = i-1 while leftIdx >= 0 and array[leftIdx] > array[leftIdx+1]: rewards[leftIdx] = max( rewards[leftIdx], rewards[leftIdx+1] + 1 ) leftIdx -= 1 rightIdx = i+1 while rightIdx < len(array) and array[rightIdx] > array[rightIdx-1]: rewards[rightIdx] = max( rewards[rightIdx], rewards[rightIdx-1] + 1 ) rightIdx += 1
# Time: O(n^2) | Space: O(1) def insertionSort(array): for i in range(1, len(array)): j = i while j > 0 and array[j] < array[j - 1]: array[j], array[j - 1] = array[j - 1], array[j] j -= 1 return array print(insertionSort([5, 10, 11, 6, 8]))
# Exercise 1: # Write a WHILEloop that will print the numbers from 1 to 10 on the screen. def printer(): i = 1 while i <= 10: print(i) i = i + 1 # uncomment the function caller to get the output # printer() # Exercise 2: # Write a FOR loop that will print the numbers from 1 to 10 on the screen. def printer2(): for i in range(1,10+1): print(i) # uncomment the function caller to get the output # printer2() # Exercise 3: # Write a FOR loop that will iterate from 0 to 20. For each iteration, it will check if the current number # is even or odd, and report that to the screen (e.g. "1 is odd, 2 is even"). def odd_even(): for i in range(0,20+1): if i == 0 or i % 2 == 0: print("{0} is an even number".format(str(i))) else: print("{0} is an odd number".format(str(i))) # uncomment the function caller to get the output # odd_even() # Exercise 4: # Write a FOR loop that will iterate from 0 to 10. For each iteration of the loop, it will # multiply the number by 9 and print the result (e.g. "2 * 9 = 18"). # Bonus (complete at the end of the class once you are comfortable with loops):Use a nested loop to show # the tables for every multiplier from 1 to 10 (100 results total). def muiltiplier(): for i in range(0, 10+1): for j in range(0, 10+1): print(str(i) + " * " + str(j) + " = " + str(i*j)) # uncomment the function caller to get the output # muiltiplier() # Exercise 5: # Write a program that asks the user for a number and prints the sum of all numbers from 1 to the number they enter. def summing(): number_threshold = int(input("Introduce a number: ")) count = 0 for i in range(1, number_threshold + 1): count = count + i print(count) # uncomment the function caller to get the output # summing() # Exercise 6: # Write a program to calculate and print the factorial of a number using a FOR loop. The factorial of a number is # the product of all integers up to and including that number, so the factorial of 4 is 4*3*2*1= 24 def factorial(): number_threshold = int(input("Introduce a number: ")) count = 1 for i in range(1, number_threshold + 1): count = count * i print(count) # uncomment the function caller to get the output # factorial() # Exercise 7: # Ask the user to enter a number and print it back on the screen. Keep asking for a new number # until they enter a negative number. def negativism(): number = int(input("Introduce a number: ")) while number > 0: print(number) number = int(input("Introduce a number: ")) print(number) # uncomment the function caller to get the output # negativism() # Exercise 8: # Write a program that uses loops to print the triangle below # Hint 1: you will need to use nested loops. # Hint 2: on line 1 we print 1 *, on line 2 we print 2 stars... on line x we print x stars...) def tirangle(): # for i in range(1, 6): # print(" *" * i) # for i in range(1,6): str = "" for j in range(1,i+1): str = str + " *" print(str) # uncomment the function caller to get the output # tirangle() # Exercise 9: # Write a program that uses loops to print the triangle below (hint: you will need to use nested loop) def numeric_triangle(): for i in range(1,6): num = "" for j in range(1,i+1): num = num + " " +str(j) print(num) # uncomment the function caller to get the output # numeric_triangle()
## ## First Lecture ## # Exercise 1: # Write a Python program to ask the user for their name # (e.g. John) and print "Hello John" on the screen name = input("Please insert your name: ") print("Hello {0}".format(name)) # Exercise 2: # Write a Python program to ask the user for their name and age, # and print them on the screen in the format "Hello John, you are 20 years old" name = input("Please insert your name: ") age = input("Please insert your age: ") print("Hello {name}, you are {age} years old".format(name=name, age=age)) # Exercise 3: # Write a Python program to ask the user for width and height of a rectangle and print the area. width = float(input("Please insert width of rectangle (m): ")) height = float(input("Please insert height of rectangle (m): ")) print("The area of the rectangle is:", round(width * height, 4), "m^2") ## ## Second Lecture ## # Exercise 1: Prompt the user to enter a mark between 0 and 100 and to print “This is a pass” # if the mark is 40 or over, and “This is a fail” if the mark is below 40. Hint: use >= mark = int(input("Insert your mark (0-100)")) if mark >= 40: print("This is a pass") else: print("This is a fail") # Exercise 2: # Prompt the user to enter an integer number, and output if the number is even or odd # (Hint: use % to get the remainder of a division, e.g. 5%2 will return 1) number = int(input("Please insert a number (integer): ")) if number % 2 == 0: print("Number is even!") else: print("Number is odd!") # Exercise 3: # Prompt the user to enter two integer numbers, and output if the first is larger, # smaller or equal to the second one. Use if-elif-else. n1 = float(input("Insert one number: ")) n2 = float(input("Insert another number ")) if n1 > n2: print("{0} is bigger than {1}".format(n1,n2)) elif n1 == n2: print("{0} is equal than {1}".format(n1, n2)) else: print("{0} is smaller than {1}".format(n1, n2)) # Exercise 4: # It costs €1 to post a letter to Ireland, €1.70 to Europe and €2.00 to the rest of the world. # Write a program that asks the user where do they want to post the letter to and prints the correct postage. destination = input("Please insert where you want to send this letter (Ireland, Europe, rest of the world): ") if destination.lower() == "ireland": print("cost is 1€") elif destination.lower() == "europe": print("cost is 1.70€") else: print("cost is 2.00€") # Exercise 5: # Parking at a specific area costs €2 per hour, with the first two hours free. # Ask the user for how long will they park for and calculate the amount they need to pay. time_parked = int(input("Please introduce how many hours you will have the car parked")) if time_parked <= 2: print("Parking is free!") else: print("Total amount is",(time_parked-2)*2,"€") # Exercise 6 # Write a small calculator simulator – ask the user to enter two numbers and an operation (+, -, *, /), and either add, # subtract, multiply or divide the numbers, and print the result. n1 = float(input("input first number: ")) n2 = float(input("input second number: ")) operation = input("input the operation: ") if operation.strip() == '+': print(n1 + n2) elif operation.strip() == '-': print(n1 - n2) elif operation.strip() == '*': print(n1 * n2) elif operation.strip() == '/': print(n1 / n2) else: print("operation unknown") # Exercise 7 # Write a Python program to calculate a dog's age in dog's years. # Note: For the first two years, a dog year is equal to 10.5 human years. # After that, each dog year equals 4 human years. age = int(input("Insert dog's age: ")) if age <= 2: print("Dog's age is",10.5*age,"years") else: print("Dog's age is",10.5*2+4*(age-2),"years") # Exercise 8 # Write a Python program to convert month name to a number of days. month_name_selected = input("insert month name") month_names = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] if month_name_selected.lower() in [x.lower() for x in month_names]: if month_name_selected == 'February': print("N. days = 28/29") elif month_name_selected in ("January", "March", "May", "July", "August", "October", "December"): print("N. days = 31") else: print("N. days = 30") else: print("that month does not exist!") ## ## Third Lecture ## # Exercise 1: # Write a WHILEloop that will print the numbers from 1 to 10 on the screen. n = 1 while n <= 10: print(n) n += 1 # Exercise 2: # Write a FOR loop that will print the numbers from 1 to 10 on the screen. for i in range(1,10+1): print(i) # Exercise 3: # Write a FOR loop that will iterate from 0 to 20. For each iteration, it will check if the current number # is even or odd, and report that to the screen (e.g. "1 is odd, 2 is even"). for i in range(0,20+1): if i % 2 == 0: print("{0} is even".format(i)) else: print("{0} is odd".format(i)) # Exercise 4: # Write a FOR loop that will iterate from 0 to 10. For each iteration of the loop, it will # multiply the number by 9 and print the result (e.g. "2 * 9 = 18"). # Bonus (complete at the end of the class once you are comfortable with loops):Use a nested loop to show # the tables for every multiplier from 1 to 10 (100 results total). for i in range(0,10+1): for j in range(0,10+1): print(i,"*",j,"=",i*j) # Exercise 5: # Write a program that asks the user for a number and prints the sum of all numbers from 1 to the number they enter. number = int(input("Insert a number: ")) count = 0 for i in range(1,number + 1): count += i print(count) # Exercise 6: # Write a program to calculate and print the factorial of a number using a FOR loop. The factorial of a number is # the product of all integers up to and including that number, so the factorial of 4 is 4*3*2*1= 24 number = int(input("Insert a number: ")) count = 1 for i in range(1,number + 1): count *= i print(count) # Exercise 7: # Ask the user to enter a number and print it back on the screen. Keep asking for a new number # until they enter a negative number. n = 0 while not n < 0: n = int(input("Please introduce a number: ")) # Exercise 8: # Write a program that uses loops to print the triangle below # Hint 1: you will need to use nested loops. # Hint 2: on line 1 we print 1 *, on line 2 we print 2 stars... on line x we print x stars...) for i in range(1,5+1): print("* "*i) # Exercise 9: # Write a program that uses loops to print the triangle below (hint: you will need to use nested loop) for i in range(1,5+1): for j in range(1,i+1): print(j, end = " ") print(end = "\n") ## ## Fourth Lecture ## # Exercise 1: # Write a program which will finds and prints all numbers between 2000 and 3200 (both included) # which are divisible by 7 but are not a multiple of 5. for i in range(2000,3200+1): if i % 7 == 0 and i % 5 == 0: print(i) # Exercise 2: # Write a Python program that will count how many digits (0-9) are in a string entered by the user. # Hint: To check if a string c represents a digit you can check if c is between ‘0’ and ‘9’Alternative way would be # to use c.isdigit() which returns True if c represents a digit and False otherwise. You’ll need to use a loop to get # every character of the string. user_string = input("Insert string with digits") count_1 = 0 count_2 = 0 for i in user_string: if i.isdigit(): count_1 += 1 elif i.isalpha(): count_2 += 1 print("Total number of digits is {0}, total number of letters is {1}".format(count_1,count_2)) # Exercise 3: # Extend your program from Exercise 2 and write a program to count how many digits (0-9) and how many letters # (a-z or A-Z) are in a sentence entered by the user. # Solution is the same as in exercise 2 # Exercise 4: # Write a Python program to find and print the sum of digits of a number entered by the user. # Hint: There are different ways of approaching this problem. One way would be to read the number as a # string and use a loop to iterate over it to get each digit. # option 1 number = input("Insert a number: ") print(sum(int(digit) for digit in str(number))) # option 2 number = int(input("Insert a number: ")) s = 0 while number: s += number % 10 number //= 10 print(s) # Exercise 5: # Write a Python program to keep asking the user to enter positive numbers and terminates when they # enter a negative. When the program terminates, print how many positive numbers were entered and what # was the smallest number. # Hint: You can use a while-loop to keep asking the user to enter a number, the loop will keep going while # they enter a value >0. Once the loop is working correctly see how you’d add a condition to keep track of # the current smallest value and update it when a smaller value is found n = 0 counter = 0 min = float("inf") while not n < 0: n = int(input("Insert a number")) if n > 0: counter += 1 if n < min and not n < 0: min = n print("Negative number introduced {0}, the count of total positive numbers is {1} and the minimum number was {2}" .format(str(n),str(counter),str(min))) ## ## Fifth Lecture ## # Exercose 1: # Write a Python program to print each character of a string on single line. string_input = input("Please insert a string: ") for i in string_input: print(i, end = " ") # Exercise 2: # Write a Python program that will calculate the length of a string string_input = input("Please insert a string: ") counter = 0 for i in string_input: counter += 1 print(counter) # Exercise 3: # Write a Python program that reads a string and prints a string that is made up # of the first two characters and the last two characters. If the string has a length # less than 4 the program prints a message on the screen. string_input = input("Please insert a string: ") if len(string_input) < 4: print("String length less than 4") else: print(string_input[:2]+string_input[-2:]) # Exercise 4: # Write a Python program that will reverse a string (using a loop, not using slicing) #option 1 string_input = input("Please insert a string: ") new_string = "" for i in range(len(string_input)-1,-1, -1): new_string += string_input[i] print(new_string) #option 2 string_input = input("Please insert a string: ") new_string = "" for i in range(0,len(string_input)): new_string += string_input[(len(string_input)-1)-i] print(new_string) #option 3 string_input = input("Please insert a string: ") new_string = "" for i in range(1,len(string_input)+1): new_string += string_input[-i] print(new_string) # Exercise 5: # Write a Python program that will “encrypt” a string. The encryption algorithm we’ll use is add 1 to # the ASCII code, so ‘a’ becomes ‘b’, ‘b’ becomes ‘c’, etc. The string ‘abc’ becomes ‘bcd’You’ll need to use the # functions ord() and chr() discussed in class. # Hint: To encrypt the letter ‘a’ take the ASCII code of ‘a’ 97, add 1 (98) # and find the character with ASCII code 98 (‘b’). So ‘a’ encrypted becomes ‘b’ string_input = input("Please insert a string: ") encrypted_output = "" for i in string_input: encrypted_output += chr(ord(i)+1) print(encrypted_output) # Exercise 6: # Write a Python program that will swap two random letters in a string. # Hint: Random letters means “letters with random index”random.randint(x,y) will return a randomnumber in # the range fromx to y inclusive. You need to import random at the top of your program. # You’ll also need to use slicing –splitting your string into substrings. from random import randint string_input = input("Please insert a string: ") if len(string_input) <= 1: print("impossible to computate due to string length") elif len(string_input) == 2: print(string_input[::-1]) else: first_rand_index = randint(0, len(string_input) - 1) while first_rand_index == len(string_input) - 1: first_rand_index = randint(0, len(string_input) - 1) second_rand_index = randint(0, len(string_input) - 1) while second_rand_index == first_rand_index: second_rand_index = randint(0, len(string_input) - 1) if first_rand_index < second_rand_index: print(string_input[0:first_rand_index] + string_input[second_rand_index] + string_input[first_rand_index + 1:second_rand_index] + string_input[first_rand_index] + string_input[second_rand_index + 1:]) else: print(string_input[0:second_rand_index] + string_input[first_rand_index] + string_input[second_rand_index + 1:first_rand_index] + string_input[second_rand_index] + string_input[first_rand_index + 1:]) # Exercise NA: Speed control test. ## ## Sixth Lecture ## # Exercise 1: Write a function that takes a number as a parameter and prints the numbers from 1 # to that number on the screen. def first_function(inp1): for i in range(1,inp1+1): print(i) first_function(5) # Exercise 2: Write a function that takes a number as a parameter and iterates from 0 to that number. # For each iteration, it will check if the current number is even or odd, and report that to the screen # (e.g. "1 is odd, 2 is even"). def second_function(inp1): for i in range(0,inp1+1): if i % 2 == 0: print("{0} is even".format(i)) else: print("{0} is odd".format(i)) second_function(6) # Exercise 3: Write a function that takes a number as a parameter, iterates from 0 to that number, # and for each iteration of the loop, multiplies the current number by 9 and prints the result (e.g. "2 * 9 = 18"). def third_function(inp1): for i in range(0,inp1+1): print(i,"* 9 =",i*9) third_function(10) # Exercise 4: Write a function that asks the user for a number and prints the sum of all numbers from 1 to the number # they enter. def fourth_function(inp1): counter = 0 for i in range(0,inp1+1): counter += i return counter print(fourth_function(5)) # Exercise 5: Write a function to print a factorial of a number. def fifth_function(inp1): counter = 1 for i in range(1, inp1 + 1): counter *= i return counter print(fifth_function(4)) # my_fifth_function(5) # Exercise 6: Write a function that takes a string as a parameter and returns a sting that is made up of the # first two characters and the last two characters. If the string has a length less than 4 the program prints a # message on the screen.For example: “hello there” will result in “here” def sixth_function(inp1): return inp1[0:2] + inp1[-2:] print(sixth_function("hello there")) # Exercise 7: Write a Python program to remove the characters which have odd index values of a given string. # The function should return the new string. def seventh_function(inp1): return inp1[1:len(inp1):2] print(seventh_function("HelloWorld")) # Exercise 8: Write a Python function to get the first half of a specified string of even lengthSample function and # result:string_first_half('Python') should return Pyt def eigth_function(input): if not len(input) % 2 == 0: return "String length not even" else: return input[0:int(len(input)/2)] print(eigth_function("Alvaro")) # Exercise 9: Write a Python function to insert a string in the middle of a string. Sample function # and result:insert_sting_middle('{{}}', 'PHP') -> {{PHP}} def nineth_function(wrapper, input): if not len(wrapper) % 2 == 0: return "Wrapper string is not even" else: return wrapper[0:int(len(wrapper)/2)] + input + (wrapper[int(len(wrapper)/2):]) print(nineth_function("{{}}", "PHP")) # Exercise 10: Write a Python function that takes a string and two indices, and returnsa # string with the part between the indices removed.For example: remove_substring(“Hellothere”, 2, 6) -> “Hehere” def tenth_function(input,ind1,ind2): if ind1 < 0 or ind2 < 0 or ind2 <= ind1: return "negative indexes not allowed or second index needs to be higher than first index" else: return input[:ind1]+input[ind2:] print(tenth_function("Hellothere", 2, 6)) ## ## Seventh Lecture ##
list = [] def showError(msg): print("输入有误,请从新输入"+msg) def is Num(num): if num.isdigit() return True else: return false def add(): stu = {} while True: name = input("请输入学生姓名") if len(name) >= 2 and len(name)<=4: stu["name"] = name break else: showError("学生姓名必须大于2小于4") while True: age = input("请输入学生年龄") if age > 1 and age < 130: stu["age"] = age break else: showError("年龄必须大于1小于130") def delete(): pass def change(): name = input("请输入要修改的名字") for stu in list: if stu["name"] == name: flag = True while True: print("1,修改名字") print("2,修改年龄") num = input("请选择功能") if isNum(num): num = int(num) else: print("输入有误") continue if num == 1: name = input("请输入新的名字") stu["name"] = name elif num == 2: age = int(input("请输入新的年龄")) stu["age"] = age break break if not flag: print("查无此人") def find(): find = input("请输入查找的学生姓名") for i in list: if i["name"]==find: print("\n姓名为:%s\n性别为%s\n"%(i["name"],i["sex"])) def print_list(): print("姓名 年龄") for stu in list: def print_menu(): print("欢迎进入学生管理系统".center(30," ")) while True: print("1,增加学生信息") print("2,删除学生信息") print("3,更改学生信息") print("4,查找学生信息") print("5,打印学生信息") print("6,退出学生系统") input_info() def input_info(): num = int(input("请选择功能")) if num == 1: add() elif num ==2: find() elif num ==3 change() elif num ==4: find() print_menu()
# Date : 18th August, 2021 # Given a binary array nums, return the maximum number of consecutive 1's in the array. # Example 1: # Input: nums = [1,1,0,1,1,1] # Output: 3 # Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. # Example 2: # Input: nums = [1,0,1,1,0,1] # Output: 2 # Constraints: # 1 <= nums.length <= 105 # nums[i] is either 0 or 1. class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: max1 = 0 count = 0 for i in nums: if i==1: count+=1 if count>max1: max1=count else: count = 0 return max1
import random as rn print("\t\t\t\t\tHey let's play a game !") print("\t\t\t\t\t-----------------------",end='\n\n') print(""""How does it sounds !! I'll pick a number randomly between 1 to 10 and you have to guess it !!!""") ap = 0 while True: n = rn.choice(range(1,11)) print("Enter the number you guessed :",end=' ') m = int(input()) if m == n: print("Yes , it's correct !") elif m > n: print("Subtract {} from {}".format(m-n,m)) ap = round(((m-n)/n)*100,2) elif m < n: print("Add {} to {}".format(n-m,m)) ap = round((((-1)*(n-m))/n)*100,2) print("you were {}% wrong".format(ap)) print("Press 1: To play again") print("Press 2: To Quit") ch = int(input()) if ch == 2: break
# compare x with the middle element # if x > mid --> x is on the right # applt again.. def bin(a,low,high,x): if high >= low: mid = (high + low) // 2 if a[mid] == x: return mid elif a[mid] > x: return bin(a,low,mid-1,x) else: return bin(a,mid+1,high,x) else: return -1 a = [2,3,4,10,40] low = 0 high = len(a) -1 x = 10 b = bin(a,low,high,x) if b != -1: print('the element is in the index: {}'.format(str(b))) else: print('the element is not in the array')
# we have 1 number N # find all 3 number sums combinations that are equal to N # input: 3 # out: 90 # explain: (1*1*1) + (1*1*2) +(1*1*3) + ... = 1+2+3+4+6+9+8+12+18+27 = 90 import itertools n = int(input('give me num: ')) c = [] for x in range(1,n+1): for y in range(1,n+1): for z in range(1,n+1): b = x*y*z c.append(b) print('{} * {} * {} = {}'.format(x,y,z,b)) print(c) ''' a = [] for x in range(1,n): a.appen(x) print(a) print('all combinations from 1 to N: ') for x in itertools.permutations(a,n): print(x) print('start the cycle to gather all numbers: ') c = [] for x in a: for y in a: for z in a: b = x*y*z c.append(b) #print(b) ''' print('now create Dict to remove duplicate nums: ') c = list(dict.fromkeys(c)) print(c) print('All final sums: ') print(sum(c))
# the sum of 3 nums in the list should be equal to a target number, return them in sorted array or empty if none target = 24 random_list = [12,3,4,1,6,9] pair_list = [(random_list[x],random_list[y],random_list[z]) for x in range(len(random_list))\ for y in range(x+1, len(random_list)) for z in range(y+1,len(random_list))] print('We have a random list: {}\n'.format(random_list)) print('\nAll combinations of the Random List, now made in a Paired List: ') print(pair_list) print('\nIndex 0 from the new Paired list: ') print(pair_list[0]) print('\nAll the sums of the different pairs from the new paired list: ') sum_pairs = [sum(x) for x in pair_list] print(sum_pairs) print('\nWe will now find if the sum of some 2 pairs is equal to our Target: ') for x in pair_list: if sum(x) == target: print('We found the pair, equal to {} ---> {} = {}'.format(target,x,target)) else: pass