text
stringlengths
37
1.41M
# importar no shell interativo def separar_palavras(palavra): """Essa função irá separar palavras para nós.""" palavras = palavra.split() return palavras def ordenar_palavras(palavras): """Ordena palavras.""" return sorted(palavras) def imprime_primeira_palavra(palavras): """Imprime a primeira palavra, depois remove ela da lista""" palavra = palavras.pop() print(palavra) def imprime_ultima_palavra(palavras): """Imprime a ultima palavra, depois remove ela da lista""" palavra = palavras.pop(-1) print(palavra) def ordenar_sentenca(sentenca): """Recebe uma sentenca e retorna as palavras ordenadas""" palavras = separar_palavras(sentenca) return ordenar_palavras(palavras) def imprime_primeira_e_ultima(sentenca): """Imprime a primeira e ultima palavra de uma sentenca.""" palavras = separar_palavras(sentenca) imprime_primeira_palavra(palavras) imprime_ultima_palavra(palavras) def imprime_primeira_e_ultima_ordenada(sentenca): """Ordena as palavras e imprime a primeira e ultima palavra""" palavras = ordenar_palavras(sentenca) imprime_primeira_palavra(palavras) imprime_ultima_palavra(palavras)
from sys import argv script, nome_arquivo = argv print("Nós apagaremos o arquivo %r." % nome_arquivo) print("Se você não quiser, aperte CTRL-C (^C).") print("Se você não se importa, aperte ENTER.") input("?") print("Abrindo o arquivo...") arquivo = open(nome_arquivo, "w") print("Apagando o arquivo. Tchau!") arquivo.truncate() print("Agora eu vou te pedir que digite 3 linhas.") linha1 = input("1: ") linha2 = input("2: ") linha3 = input("3: ") print("Escrevendo as linhas no arquivo.") arquivo.write(linha1) arquivo.write("\n") arquivo.write(linha2) arquivo.write("\n") arquivo.write(linha3) arquivo.write("\n") print("E finalmente, fechando o arquivo.") arquivo.close()
def soma(a, b): print("Somando %d + %d" % (a, b)) return a + b def subtracao(a, b): print("Subtraindo %d - %d" % (a, b)) return a - b def multiplicacao(a, b): print("Multiplicando %d * %d" % (a, b)) return a * b def divisao(a, b): print("Dividindo %d / %d" % (a, b)) return a / b print("Vamos fazer algumas operações com estas funções!") idade = soma(10, 13) altura = subtracao(100, 16) peso = multiplicacao(42, 2) qi = divisao(150, 2) print("Idade: %d, Altura: %d, Peso: %d, QI: %d" % (idade, altura, peso, qi)) print("Quebra-Cabeça:") misterio = soma(idade, subtracao(altura, multiplicacao(peso, divisao(qi, 2)))) print("Qual é o resultado?", misterio)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 20 13:46:38 2020 @author: Hank.Da """ """ pesudocode: define find_sroot using number and epsilon as arguments initiate step = square(epsilon) initiate numGuess = 0 initiate root = 0 while (absolute number - square(root)) >= epsilon and root <= number do root = root + step numGuesses += 1 print Still running. Number of guesses:', numGuesses when numGuesses mod 100000 =0 done print number of guesses if number - square(root) < epsilon print The approximate square root of number is root else print Failed to find a square root of number print Finished! define main prompt user enter number and tolerance execute find_sroot(number, tolerance) """ def find_sroot(number,epsilon): step = epsilon ** 2 numGuesses = 0 root = 0.0 while abs(number - root ** 2) >= epsilon and root <= number: root += step numGuesses += 1 if numGuesses % 100000 == 0: print('Still running. Number of guesses:', numGuesses) print('Number of guesses:', numGuesses) if abs(number - root ** 2) < epsilon: print('The approximate square root of', number, 'is', root) else: print('Failed to find a square root of', number) print('Finished!') def main(): number = float(input('Enter the number for which you wish to calculate the square root: ')) tolerance = float(input('Enter the number for acceptable tolerance: ')) find_sroot(number,tolerance) main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 20 18:05:03 2020 @author: Hank.Da """ """ Pesudocode: function implement """ def max(a, b): if a > b: return a else: return b # Program to print out the largest of two numbers entered by the user # Uses two functions: max and print_max def print_max(): # Prompt the user for two numbers number1 = float(input('Enter a number: ')) number2 = float(input('Enter a number: ')) print('The largest of', number1, 'and', number2,'is', max(number1, number2)) return print(print_max) print(hex(id(print_max)))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 8 14:32:39 2020 @author: Hank.Da """ """ #pseudocode: ask user enter three int numbers if the number is odd number: then put the number in list find the largest number in the list by compare current number and temporary largest number print(largest number is: num_largest) if there are no odd numbers : print(All the numbers are even numbers) """ ls_odd =[] num1 = int(input('plz enter 1st number :')) num2 = int(input('plz enter 2st number :')) num3 = int(input('plz enter 3th number :')) ls_num =[num1,num2,num3] for i in range(len(ls_num)): if (ls_num[i]%2): ls_odd.append(ls_num[i]) if (len(ls_odd)): num_largest = ls_num[0] for num_test in ls_num: if num_test >= num_largest: num_largest=num_test print('largest number is:', str(num_largest)) else: print('All the numbers are even numbers')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 15 14:36:09 2020 @author: Hank.Da """ """ Pesudocode : prompt user to enter an integer print Times enterd number for num1 in range 1 : 20 +1 print print num1 and num1 multiply enterd number """ num_inp = int(input('plz enter an integer:')) print('Times %d Table' %(num_inp)) for i in range(1,21): print(i,i*num_inp)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 6 13:14:38 2020 @author: Hank.Da """ def main(): input_currency =float(input('plz type in amount of TWD to exchange to EUR: ')) print("input_currency : ", str(input_currency) , "TWD") if input_currency>=0: #TWD to EUR excahge_rate = 0.029 output_currency = input_currency*excahge_rate print("output_currency : " , str(output_currency) ,"EUR") else: print("Amount must be >= 0. Please try again.") if __name__ == "__main__": main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 22 16:02:04 2020 @author: Hank.Da """ """ Pesudocode: function implement """ # Look for prime numbers in a range of integers for number in range(2, 20): for i in range(2, number): if number % i == 0: print(number, 'equals', i, '*', number//i) break else: # loop fell through without finding a factor print(number, 'is a prime number') print('Finished!')
''' code to minimize dfa ''' import json import sys ''' function to print dfa optimally ''' def print_dfa(dfa): print("states : ") for i in dfa['states'] : print(i) print("transition :") for s in dfa['transition_function'] : print("old state : {0} , input : {1} and next state : {2}".format(s[0],s[1],s[2])) print("Alphabet") for l in dfa['letters']: print(l) print("Initial_state") for s in dfa['start_states']: print(s) print("final_state") for s in dfa['final_states']: print(s) ''' loads to the dfa from file ''' def load_input(infile): f = open(infile) dfa = json.load(f) f.close() #print_dfa(dfa) return dfa ''' function to remove unreachable states:''' def unreachable(dfa,graph): reachable = dfa['start_states'] new_states = dfa['start_states'] while(True): temp = [] for s in new_states: #check if s leads to new states for l in dfa['letters']: var = graph[s][l] already_reachable = 0 #check if var is already there for r in temp: if(r == var): already_reachable = 1 break if(already_reachable == 0): temp.append(var) temp_new = [] #check s is not in reachable already for s in temp: is_there = 0 for r in reachable: if(s == r): is_there = 1 if(is_there == 0): temp_new.append(s) new_states = temp_new reachable = reachable + new_states if(len(new_states) == 0): break not_reachable = [] for s in dfa['states']: non_reachable = 1 for r in reachable: if(s == r): non_reachable = 0 if(non_reachable == 1): not_reachable.append(s) #print("REACHABLE = {0}".format(reachable)) #print("NON_REACHABLE = {0}".format(not_reachable)) dfa['states'] = reachable is_reachable = {} for s in reachable: is_reachable[s] = 1 for s in not_reachable: is_reachable[s] = 0 non_delete_states = [] for f in dfa['final_states']: if(is_reachable[f] == 1): non_delete_states.append(f) dfa['final_states'] = non_delete_states #print("FINAL = {0}".format(non_delete_states)) #print(is_reachable) remaining_transition = [] for l in dfa['transition_function']: if(is_reachable[l[0]] == 1 and is_reachable[l[2]] == 1): remaining_transition.append(l) #print("TRANSITION = {0}".format(remaining_transition)) dfa['transition_function'] = remaining_transition #print_dfa(dfa) return dfa ''' minimizes the dfa using partitioning ''' def partition(dfa,outfile): #print("Calling Partition") #create graph graph = {} for s in dfa['states']: graph[s] = {} for l in dfa['letters'] : graph[s][l] = "" for l in dfa['transition_function']: f = l[0] letter = l[1] to = l[2] graph[f][letter] = to #print("Calling ") dfa = unreachable(dfa,graph) #print_dfa(dfa) #print("RETURNED") state_identity = {} for s in dfa['states']: state_identity[s] = 0 for s in dfa['final_states']: state_identity[s] = 1 size = len(dfa['states']) #print(state_identity) while(True): size -= 1 #if(size < - 2): # break isThereAnyPartition = 0 identities = [] temp = [] for s in state_identity: temp.append(state_identity[s]) for i in temp : if i not in identities: identities.append(i) #print(size) #print("identities : {0}".format(identities)) #print("haha") val = 0 new_state_identities = {} for s in dfa['states'] : new_state_identities[s] = -1 #print(size) #print("naha") #print(new_state_identities) #print_dfa(dfa) for r in identities: #print("") #print("state identity with id {0}".format(r)) current_state = [] for s in dfa['states']: if(state_identity[s] == r): current_state.append(s) #print("Current_State = {0}".format(current_state)) diction = {} for state1 in current_state: diction[state1] = {} for state2 in current_state: diction[state1][state2] = 0 for s1 in current_state: for s2 in current_state: same_partition = 1 if(s1 == s2): diction[s1][s2] = 1 diction[s2][s1] = 1 else: #print("CHECKING WHETHER {0} and {1} are equivalent".format(s1,s2)) for l in dfa['letters']: #print("FOR letter {0} : State : {1} to {2} and state : {3} to {4} ".format(l,s1,graph[s1][l],s2,graph[s2][l])) if(state_identity[graph[s1][l]] != state_identity[graph[s2][l]]): same_partition = 0 isThereAnyPartition = 1 #print("FOR letter {0} : State : {1} to {2} and state : {3} to {4} ".format(l,s1,graph[s1][l],s2,graph[s2][l])) if(same_partition == 1): #print("{0} and {1} are equivalent".format(s1,s2)) diction[s1][s2] = 1 diction[s2][s1] = 1 else: #print("{0} and {1} are not equivalent".format(s1,s2)) diction[s1][s2] = 0 diction[s2][s1] = 0 for s3 in current_state: if(new_state_identities[s3] == -1): new_state_identities[s3] = val for rr in diction[s3]: if(diction[s3][rr] == 1): new_state_identities[rr] = val val += 1 for s in state_identity: state_identity[s] = new_state_identities[s] if(isThereAnyPartition == 0): break #print(state_identity) max_val = 0 for r in state_identity: if(max_val <= state_identity[r]): max_val = state_identity[r] list_of_states = [] reverse_hash = {} for z in range(max_val + 1): current_state = [] for s in dfa['states']: if(state_identity[s] == z): current_state.append(s) list_of_states.append(current_state) reverse_hash[z] = current_state #print("LIST") #for r in list_of_states: #print(r) transition = [] for r in list_of_states: for l in dfa['letters']: #print(r) #print(l) #print(graph[r[0]][l]) #print("") iden = state_identity[graph[r[0]][l]] to = reverse_hash[iden] transition.append([r,l,to]) temp1 = [] for s in dfa['final_states']: temp1.append(state_identity[s]) new_final = [] for i in temp1: if reverse_hash[i] not in new_final: new_final.append(reverse_hash[i]) temp2 = [] new_start = [] for s in dfa['start_states']: temp2.append(state_identity[s]) for i in temp2: if reverse_hash[i] not in new_start: new_start.append(reverse_hash[i]) #print(new_start,new_final) dfa['start_states'] = new_start dfa['final_states'] = new_final dfa['states'] = list_of_states dfa['transition_function'] = transition # print_dfa(dfa) g = open(outfile,"w") json.dump(dfa,g,indent=4) partition(load_input(sys.argv[1]),sys.argv[2])
# Authors: Tom Lambert (lambertt) and Yuuma Odaka-Falush (odafaluy) import matrix def main(): """Executes the main program with predefined values.""" experiment = "3.2B - B" # allowed are "3.1B", "3.2B - B", "3.2B - A" # The types to use for the experiments dtypes = ["float16", "float32", "float64"] # Parameters for 3.1A mtypes = ["hilbert", "saite"] # The matrix types dims = [5, 7, 9] # The dimensions # Parameters for 3.2B - A and B n = [5, 8, 51, 101] # Parameters for 3.2B - B i = [1, 2, 3, 4, 5, 6, 7, 8] # only i <= n will be used matrix.main(experiment, mtypes, dims, dtypes, n, i) if __name__ == "__main__": main()
import scipy.sparse def get_matrix(n): size = (n-1)*(n-1) result = scipy.sparse.dok_matrix((size, size)) for block in range(0, n - 1): for i in range(0, n - 1): result[(block * (n-1)) + i, (block * (n-1)) + i] = 4 if i > 0: result[(block * (n-1)) + i, (block * (n-1)) + i - 1] = -1 if i < n-2: result[(block * (n-1)) + i, (block * (n-1)) + i + 1] = -1 if block > 0: result[(block * (n-1)) + i, ((block-1) * (n-1)) + i] = -1 if block < n-2: result[(block * (n-1)) + i, ((block+1) * (n-1)) + i] = -1 return result def main(): matrix = get_matrix(5) print(matrix) pass if __name__ == "__main__": main()
def load_data(): with open('day_1/input.txt') as data: return [int(mass) for mass in data] def total_fuel(mass): final_mass = 0 while True: mass = mass // 3 - 2 if mass > 0: final_mass += mass else: return final_mass def sum_of_fuel(): masses = load_data() fuel_1 = [mass // 3 - 2 for mass in masses] fuel_2 = [total_fuel(mass) for mass in masses] return sum(fuel_1), sum(fuel_2) if __name__ == '__main__': print(sum_of_fuel())
import random suits = ["Hearts", "Diamonds", "Spades", "Clubs"] card_value = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] suit = suits[random.randint(0,3)] card = card_value[random.randint(0,12)] print(card + " of " + suit)
## types of inheritance 1. simple inheritance 2. multi level inheritance 3. multiple inheritance class A: def feature1(self): print("Feature 1 working") class B: def feature2(self): print("Feature 2 working") class C(B): def feature3(self): print("Feature 3 working") class D(A,B): def feature4(self): print("Feature 4 working") a1 = A() b1 = B() c1 = C() d1 = D() print(a1.feature1()) print(b1.feature2()) #print(c1.feature1()) print(d1.feature1())
class Person: def __init__(self): self.name = 'Sara' self.age = 20 def compare(self, other): if self.age == other.age: print("They are same") else: print("They are not same") p1 = Person() p2 = Person() p1.compare(p2) if p1.age == p2.age: print("Their ages are same") else: print('Their ages are different')
""" Solving mazes with generic search (without numpy) See 'Classic Computer Science Problems in Python', Ch. 2 """ from enum import Enum from collections import namedtuple import random from math import sqrt class Cell(str, Enum): empty = " " blocked = "X" start = "S" goal = "G" path = "*" MazeLocation = namedtuple("MazeLocation", ("row", "col")) def euclidean_distance(goal): """ Return a callable that computes the euclidean distance between an input MazeLocation and the goal. """ def distance(ml): dx = (ml.col - goal.col) dy = (ml.row - goal.row) return sqrt(dx**2 + dy**2) return distance def manhattan_distance(goal): """ Return a callable that computes the manhattan distance between an input MazeLocation and the goal """ def distance(ml): dx = (ml.col - goal.col) dy = (ml.row - goal.row) return abs(dx) + abs(dy) return distance def grid_cost(current_node): """ Cost function for cardinal motion on a grid. """ return current_node.cost + 1 class Maze(object): """ 2D grid maze """ def __init__(self, nrows=10, ncols=10, blocked_fraction=0.2, start=MazeLocation(0, 0), end=MazeLocation(9, 9)): self._nrows = nrows self._ncols = ncols self._blocked_cells = 0 self.start = start self.goal = end # Initialize grid self._grid = [[Cell.empty for c in range(self._ncols)] for r in range(self._nrows)] # Randomly block self._randomly_fill(blocked_fraction) # Set start and end points self._grid[start.row][start.col] = Cell.start self._grid[end.row][end.col] = Cell.goal def __str__(self): out = '' for row in self._grid: out += "".join([c.value for c in row]) + "\n" return out def _randomly_fill(self, blocked_fraction): """ Randomly fill maze with blocked locations. """ for row in range(self._nrows): for col in range(self._ncols): if random.uniform(0, 1.0) < blocked_fraction: self._grid[row][col] = Cell.blocked self._blocked_cells += 1 def goal_test(self, loc): """ Test whether the end of the maze has been reached. """ return loc == self.goal def possible_next_locations(self, loc): """ Given the current location, determine valid locations for the next move in the maze. Parameters ---------- loc : MazeLocation Current location in the grid Returns ------- possible_locations : List[MazeLocation] List of allowed locations for the next move on the grid """ possible_locations = [] # Check left if loc.col > 0 and self._grid[loc.row][loc.col - 1] != Cell.blocked: possible_locations.append(MazeLocation(loc.row, loc.col - 1)) # Check right if loc.col + 1 < self._ncols and self._grid[loc.row][loc.col + 1] != Cell.blocked: possible_locations.append(MazeLocation(loc.row, loc.col + 1)) # Check top if loc.row > 0 and self._grid[loc.row - 1][loc.col] != Cell.blocked: possible_locations.append(MazeLocation(loc.row - 1, loc.col)) # Check bottom if loc.row + 1 < self._nrows and self._grid[loc.row + 1][loc.col] != Cell.blocked: possible_locations.append(MazeLocation(loc.row + 1, loc.col)) return possible_locations def mark_path(self, path): """ Mark path through the maze. Parameters ---------- path : list List of MazeLocation objects representing path. """ for ml in path: self._grid[ml.row][ml.col] = Cell.path # Re-label start and end self._grid[self.start.row][self.start.col] = Cell.start self._grid[self.goal.row][self.goal.col] = Cell.goal def clear_path(self): """ Remove path visualization from maze, if any. """ for i, row in enumerate(self._grid): for j, cell in enumerate(row): if cell == Cell.path: self._grid[i][j] = Cell.empty if __name__ == "__main__": import time from search import dfs, bfs, a_star, node_to_path nrows, ncols = 24, 120 start = MazeLocation(0, 0) end = MazeLocation(nrows - 1, ncols - 1) m = Maze(nrows, ncols, start=start, end=end) print(m) tic = time.time() df_solution = dfs(m.start, m.goal_test, m.possible_next_locations) toc = time.time() if df_solution is None: print("Depth-first search did not find solution") else: df_path = node_to_path(df_solution) m.mark_path(df_path) print("Depth-first search results:") print(" Path length: {}".format(len(df_path))) print(" Eval time: %.5f" %(toc - tic)) print(m) m.clear_path() tic = time.time() bf_solution = bfs(m.start, m.goal_test, m.possible_next_locations) toc = time.time() if bf_solution is None: print("Breadth-first search failed to find solution") else: bf_path = node_to_path(bf_solution) m.mark_path(bf_path) print("Path from BFS:") print(" Path length: {}".format(len(bf_path))) print(" Eval time: %.5f"%(toc - tic)) print(m) m.clear_path() heur = euclidean_distance(m.goal) tic = time.time() astar_solution = a_star(m.start, m.goal_test, m.possible_next_locations, grid_cost, heur) toc = time.time() if astar_solution is None: print("A* search failed to find a solution") else: astar_path = node_to_path(astar_solution) m.mark_path(astar_path) print("Path from A* (euclidean):") print(" Path length: {}".format(len(astar_path))) print(" Eval time: %.5f" %(toc-tic)) print(m) m.clear_path() heur = manhattan_distance(m.goal) tic = time.time() astar_solution = a_star(m.start, m.goal_test, m.possible_next_locations, grid_cost, heur) toc = time.time() if astar_solution is None: print("A* search failed to find a solution") else: astar_path = node_to_path(astar_solution) m.mark_path(astar_path) print("Path from A* (manhattan):") print(" Path length: {}".format(len(astar_path))) print(" Eval time: %.5f" %(toc-tic)) print(m) m.clear_path()
""" Example using a graph comprising the top 15 metro areas in the US to illustrate the Jarnik algorithm for finding the minimum spanning tree of a weighted graph. See Classic Computer Science Problems in Python, Ch. 4 """ import sys sys.path.append('..') from cities import top_15_metro_areas_in_US_weighted_by_distance from minimum_spanning_tree import jarnik, print_weighted_path, is_spanning_tree weighted_city_graph = top_15_metro_areas_in_US_weighted_by_distance() path_mst = jarnik(weighted_city_graph) if not is_spanning_tree(weighted_city_graph, path_mst): print("Warning: {} is not a spanning tree".format(path_mst)) print_weighted_path(weighted_city_graph, path_mst)
from Read_write_workbook import read_from_xlsx, write_to_xlsx from googletrans import Translator def translate_de_to_en(): filename = input('Excel table name to be read: ') column = input('Column letter to be read: ') start_row = int(input('First row number to be read: ')) end_row = int(input('Last row number to be read: ')) translated_text = [] translator = Translator() sentences_to_be_translated = read_from_xlsx(filename, start_row, end_row, column) for sentence_to_be_translated in sentences_to_be_translated: translated_text.append(translator.translate(sentence_to_be_translated, dest='en').text + " (" + sentence_to_be_translated + ")") write_to_xlsx(filename, start_row, column, translated_text) if __name__ == "__main__": translate_de_to_en()
from tkinter import * import scheduler, DisplayTasksUI, DTS def createWhitelistWindow(tkinterRoot): # This creates the new window for the whitelist menu master = Toplevel() master.title("Create whitelist") # Initialise the colours in variables black = "black" white = "white" # Load the whitelist into memory and return it as a variable scheduler.read_whitelist_file() whitelistList = scheduler.return_whitelist_list() daysDict = {"Sunday": [[], []], "Monday": [[], []], "Tuesday": [[], []], "Wednesday": [[], []], "Thursday": [[], []], "Friday": [[], []], "Saturday": [[], []], } def setWhitelist(day, time): if daysDict[day][1][time]: daysDict[day][1][time] = False daysDict[day][0][time].configure(bg=black, fg=white) else: daysDict[day][1][time] = True daysDict[day][0][time].configure(bg=white, fg=black) def submit(): newWhitelistList = [] # This is a list of all the whitelisted times on each day for day in daysDict: freeTimeList = [] # This is list of all the whitelisted times on a given day for time in range(24): # If the time is set to be whitelisted it will be added to the freeTimeList if daysDict[day][1][time] == True: if time < 10: timeString = "0" + str(time) else: timeString = str(time) freeTimeList.append(DTS.Time(timeString, "00")) """Once all the free times for a given day have been added to the list, that list gets appended to newWhitelistList """ newWhitelistList.append(scheduler.WhitelistTimes(day, freeTimeList)) scheduler.update_whitelist_list(newWhitelistList) scheduler.check_tasks() DisplayTasksUI.UI(tkinterRoot) master.destroy() def cancel(): master.destroy() timeRow = 0 for day in daysDict: Label(master, text=day).grid(row=timeRow, column=0) # This makes the left hand coloumn with the days for time in range(24): if time < 10: timeString = "0" + str(time) + ":00" else: timeString = str(time) + ":00" # This makes each button and labels it with the time of the day timeLabel = Button(master, text=timeString, bg=black, fg=white, command=lambda first=day, second=time: setWhitelist(first, second)) timeLabel.grid(row=timeRow, column=(time + 1)) daysDict[day][0].append(timeLabel) daysDict[day][1].append(False) timeRow += 1 for whitelistObject in whitelistList: for time in whitelistObject.free_times: daysDict[whitelistObject.whitelist_day_name][1][int(time.string_h())] = True daysDict[whitelistObject.whitelist_day_name][0][int(time.string_h())].configure(bg=white, fg=black) submitButton = Button(master, text="Submit", command=submit).grid(row=2, column=25) cancelButton = Button(master, text="Cancel", command=cancel).grid(row=4, column=25) master.mainloop()
""" BASICS Computes the SHA256 checksum of a file """ import hashlib # Computes the SHA 256 checksum of a file given its name # Based on https://gist.github.com/rji/b38c7238128edf53a181 def sha256_checksum(filename, block_size=65536): sha256 = hashlib.sha256() with open(filename, 'rb') as f: for block in iter(lambda: f.read(block_size), b''): sha256.update(block) return sha256.hexdigest()
prompt = "The '#' character can be used to write single-line comments. Use this to write a comment of your own!" def TEST(student_input, student_output): problems = "" if "#" not in student_input: problems = problems + "You must use the '#' character to write at least one comment." if problems == "": return "Success!" else: return problems
prompt = "Declare a variable named <strong>my_boolean</strong> and assign it a value of <strong>False</strong>." def TEST(student_input, student_output): problems = "" returns = [VALIDATE_VAR("my_boolean", "bool", False)] for thing in returns: if thing != True: problems = problems + thing+"\n" if problems == "": return "Success!" else: return problems
import random min = 1 max = 6 turn=0 user_sum=0 play="Y" while(user_sum<20) : turn+=1 if(turn!=1): print() print("Turn "+str(turn)) user_input="r" turn_sum=0 flag=0 while(user_input!="h"): print("Roll or hold? (r/h): ",end="") user_input=input() if(user_input=="r"): upper_face_value=(random.randint(min, max)) print("Die "+str(upper_face_value)) if(upper_face_value==1): print("Turn over. No score.") flag=1 break turn_sum+=upper_face_value else: break if(flag==0): user_sum+=turn_sum print("Score for turn :"+str(turn_sum)) print("Total score :"+str(user_sum)) print() print() print("You finished in "+str(turn)+" turns.") print("Game over !!")
""" 多个子进程 """ from multiprocessing import Process import os,sys import time def func01(): time.sleep(3) print("小泽一号") print(os.getpid(),"------",os.getppid()) def func02(): time.sleep(2) print("小泽二号") print(os.getpid(),"------",os.getppid()) def func03(): time.sleep(4) sys.exit("小泽四号") print("小泽三号") print(os.getpid(),"------",os.getppid()) list01 = [] for item in [func01,func02,func03]: p = Process(target=item) list01.append(p) p.start() [item.join() for item in list01]
#!/usr/bin/env python import getpass true_name = 'liuyueming' true_passwd = 'pwd' input_name = input('Please input your name:') input_passwd = input('Please input your password:') if input_name==true_name and input_passwd==true_passwd: print("Welcome",input_name) else: print("Login failure")
def is_palindrome(n): #str(n)把整数转换成字符串使用切片法反转 #例如s='123'则s[::-1]='321' #如果反转后与反转前是一致则返回True return str(n)==str(n)[::-1] #打印1-1999之间所有回数 print(list(filter(is_palindrome,range(1,2000))))
def _odd_iter(): n=1 while True: n=n+2 yield n def _not_divisible(n): def f(x): return x%n>0 return f def primes(): yield 2 it=_odd_iter() while True: n=next(it) yield n it=filter(_not_divisible(n),it) for n in primes(): if n<100: print(n) else: break
class Bucketlist(object): """Enable the user perform various operations on the bucketlist e.g create bucketlist and add bucketlist item """ def __init__(self, title): self.title = title self.titles = [] self.bucketDict = {} self.items = [] def create(self): self.titles.append(self.title) def delete_bucketlist(self, title): if title in self.titles: self.titles.remove(self.title) def view_bucketlist(self): return self.bucketDict def update_bucketlist(self, title, title_x): if title in self.bucketDict: self.bucketDict[title_x] = self.bucketDict.pop(title) return self.bucketDict def add_item(self, item): self.items.append(item) self.bucketDict[self.title] = self.items def view_items(self): return self.items def delete_item(self, item_name): if item_name in self.items: self.items.remove(item_name) def update_item(self, item1, item_x): for i, bucket_items in enumerate(self.items): if item1 in bucket_items: self.items[i] = item_x return self.items
print('Cálculo da área de um círculo') PI = 3.14 raio = int(input('Digite o raio do círculo: ' )) area = PI * raio**2 print('A área do círculo é:', area, 'cm2')
# -*- coding: utf-8 -*- """ Created on Wed Jan 22 15:52:51 2020 @author: ojhag """ class Queue: def __init__(self): self.arr = [] def isEmpty(self): return self.arr == [] def enqueue(self,item): self.arr.insert(0, item) def dequeue(self): if self.isEmpty(): return "Queue is Empty" else: self.arr.pop() def showQ(self): return self.arr q = Queue() print("Is the Queue Empty:",q.isEmpty()) print("Adding 2 to the Queue") q.enqueue(2) print("Adding String to the Queue") q.enqueue("Cold") print("Adding 3.14 to the Queue") q.enqueue(3.14) print("The Queue is : ",q.showQ()) print("Is the Queue Empty:",q.isEmpty()) print("\n") print("Dequeue from the Queue") q.dequeue() print("The Queue is : ",q.showQ()) print("Dequeue from the Queue") q.dequeue() print("The Queue is : ",q.showQ()) print("Dequeue from the Queue") q.dequeue() print("The Queue is : ",q.showQ()) print("Dequeue from the Queue") print(q.dequeue())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 26 10:24:42 2019 @author: owner """ class Person(object): def __init__(self, name, add): self._Name = name self._Address = add def getName(self): return self._Name def setName(self, name): self._Name = name return self._Name def getAddress(self): return self._Address def setAddress(self, add): self._Address = add return self._Address def __del__(self): print("I have been deleted") from functools import reduce class Employee(Person): def __init__(self, num, name, address, salary, title, loans): self.Number = int(num) # self.__Name = str(name) super().__init__(name, address) # self.__Address = str(address) self.__Salary = float(salary) self.__JobTitle = str(title) self.__Loans = list(loans) def getSalary(self): return self.__Salary def setSalary(self, salary): self.__Salary = salary return self.__Salary def getJobTitle(self): return self.__JobTitle def setJobTitle(self, title): self.__JobTitle = title return self.__JobTitle def getTotal(self): if len(self.__Loans) == 0: return 0 else: total = reduce(lambda x, y: x + y, self.__Loans) return total def getLoan(self): return self.__Loans def getMaxLoan(self): maxx = reduce(lambda a, b: a if a > b else b, self.__Loans) return maxx def getMinLoan(self): minn = reduce(lambda a, b: a if a < b else b, self.__Loans) return minn def setLoans(self, loans): self.__Loans = loans return self.__Lones def printInfo(self): print("Employee Number", self.Number, ":") print("Name :", self._Name) print("Address :", self._Address) print("Job Title :", self.__JobTitle) print("Salary :", self.__Salary) print("Loans :", self.__Loans) print("Total Loans :", self.getTotal()) def __del__(self): print("I have been deleted") class Student(Person): def __init__(self, num, name, address, subject, marks): self.Number = int(num) super().__init__(name, address) self.__Subject = str(subject) self.__Marks = dict(marks) def getSubject(self): return self.__Subject def setSubject(self, subject): self.__Subject = subject return self.__Subject def getMarks(self): return self.__Marks def setMarks(self, marks): self.__Marks = marks return self.__Marks def getAvg(self): if len(self.__Marks.values()) == 0: return 0 else: summ = reduce(lambda x, y: x + y, self.__Marks.values()) avg = summ/len(self.__Marks.values()) return avg def getA(self): A = list(filter(lambda x: x >= 90, self.__Marks.values())) return A def printInfo(self): print("Student Number", self.Number, ":") print("Name :", self._Name) print("Address :", self._Address) print("Subject :", self.__Subject) print("Student's Average:", self.getAvg()) def __del__(self): print("I have been deleted") # #Employee1=Employee(1000,"Ahmad Yazaan","Amman Jordan",500,"HR Consultant",[434,200,1020]) #Employee2= Employee(2000,"Hala rana","Aqaba jordan", 750,"Manager",[150,3000,250]) #Employee3= Employee(3000,"Mariam ali","Mafraq jordan", 600,"HR s",[304,1000,250,300,500,235]) ##Employee4= Employee(4000,"Yasmin mohameed","Karak jordan", 865,"Director",[]) #Student1=Student(20191000,"Khalid Ali","Irbid Jordan", "History",{"English":80,"Arabic":90,"Management":75,"Calculus":85, "OS":73,"Priogramming":91}) #Student2=Student(20182000,"Reem Hani","Zarqa Jordan", "Softwere Eng",{"English":80,"Arabic":90,"Management":75,"Calculus":85, "OS":73,"Priogramming":90}) #Student3=Student(20161001,"Nawras Abdallah","Amman Jordan", "Arts",{"English":83,"Arabic":92,"Art":90,"Management":75}) #Student4=Student(20172030,"Amal Raed","Tafelah Jordan", "Computer Eng",{"English":83,"Arabic":92,"Management":70,"Calculus":80, "OS":79,"Priogramming":91}) #print(Employee2.printInfo()) #print(Student1.printInfo()) #print(Student2.getA()) #def employees(employee, *employee2): # # employee.printInfo() # # # #employees(Employee1, Employee3) # EmployeeList = [] EmployeeList.append(Employee1) EmployeeList.append(Employee2) EmployeeList.append(Employee3) #EmployeeList.append(Employee4) #print(len(EmployeeList)) StudentsList = [] StudentsList.append(Student1) StudentsList.append(Student2) StudentsList.append(Student3) StudentsList.append(Student4) #print(len(StudentsList)) #print(EmployeeList) # # Q 5 + 6: #def printInfo(List): # for item in List: # print(item.printInfo()) #printInfo(EmployeeList) #printInfo(StudentsList) #print(Student1.getAvg()) # Q7: #def highest(listt): # x = reduce(lambda x, y: x if x.getAvg() > y.getAvg() else y, listt) # print(x.getAvg()) #highest(StudentsList) # Q 8+9: def maxx(listt): x = reduce(lambda x, y: x if x.getMaxLoan() > y.getMaxLoan() else y, listt) print(x.getMaxLoan()) maxx(EmployeeList) def minn(listt): x = reduce(lambda x, y: x if x.getMinLoan() < y.getMinLoan() else y, listt) print(x.getMinLoan()) minn(EmployeeList) #Q 11: def LoanDict(listt): dictionery = {} for x in listt: dictionery[x.getName()] = x.getLoan() print(dictionery) LoanDict(EmployeeList) #print(hhh) #Q 12: #def minAndMax(listt): # dictionery = {} # print(list(listt)) # for key in listt.values(): # print(hhh) # maxx = reduce(lambda x, y: x if x > y else y, listt) # minn = reduce(lambda x, y: x if x < y else y, listt.values()) # dictionery[key] = {"Max": maxx, "Min": minn} # print(dictionery) # #def hhhh(lll): # for k in lll: # print(k) #hhhh(hhh) #minAndMax(LoanDict(EmployeeList)) def Dellete(listt): # del listt for x in listt: del x Dellete(StudentsList)
####################################################### # Implement a program to check, given two strings # # if they are one edit (or zero edits) away. # # EXAMPLE # # pale, ple -> true # # pales, pale -> true # # pale, bake -> false # # # ####################################################### def oneAway(string1, string2): length1 = len(string1) length2 = len(string2) if (abs(length1-length2) > 1): return False count = 0 i = 0 j = 0 while(i < length1 and j < length2): if string1[i] != string2[j]: if count == 1: return False if length1 > length2: i += 1 elif length1 < length2: j += 1 else: # If lengths of both strings is same i += 1 j += 1 count += 1 else: # if current characters match i += 1 j += 1 if i < length1 or j < length2: # if last character is extra in any string count += 1 return count == 1 def main(): string1 = input("Enter the string 1: ") string2 = input("Enter the string 2: ") if oneAway(string1, string2): print('True') else: print("False") if __name__ == '__main__': main()
################################################################# # Implement an algorithm to delete a node in the middle # # (i.e., any node but the first and last node, not necessarily # # the exact middle) of a singly linked list, given only # # access to that node. Do not print anything # # # ################################################################# class Node(): def __init__(self, data): self.data = data self.next = None class linkedlist(): def __init__(self): self.head = None def add(self, value): # function to add nodes in a list temp = self.head new_node = Node(value) if temp == None: self.head = new_node else: while (temp.next != None): temp = temp.next temp.next = new_node def deleteNode(self, value): # function to remove duplicates current = self.head while(current != None): if current.data == value: current.data = current.next.data current.next = current.next.next current = current.next def main(): ll = linkedlist() nodeCount = int(input("Enter the number of nodes: ")) for i in range(nodeCount): value = input("Enter the element in the linkedlist:") ll.add(value) value = input("Enter the element to be deleted: ") ll.deleteNode(value) if __name__=="__main__": main()
user_string = input("Enter your String :: ") output = "" for letter in user_string: if letter in "aeiou": output = output+"P" else: output = output+letter print(output)
# for i in range(3): # print("hello world") # lst = ['xdoramming','programming','helloWorld'] # for i in lst: #1st iteration # print(i) # lst = [["xdoramming","Programming"],["mukesh","Films"]] # for i,j in lst: # print(j) # dictionary = {'name':'priyanshu', # 'channelName':'xdoramming'} # for key,value in dictionary.items(): # print(f"Key is {key} and value is {value}") lst = ['xdoramming','programming','helloWorld'] for i in range(len(lst)): print(lst[i])
a=input() is_palindrom="" for i in a: is_palindrom=i+is_palindrom print(a==is_palindrom)
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next from heapq import heappush, heapify, heappop class Solution(object): def mergeKLists(self, lists): answer_head = None answer_tail = None added = True heap = [] heapify(heap) for index, head in enumerate(lists): if head != None: heappush(heap, (head.val, index)) lists[index] = head.next if len(heap) > 0: val, ind = heappop(heap) answer_head = ListNode(val) answer_tail = answer_head if lists[ind] != None: heappush(heap, (lists[ind].val, ind)) lists[ind] = lists[ind].next while len(heap) > 0: # a = # print(a) val, ind = heappop(heap) answer_tail.next = ListNode(val) answer_tail = answer_tail.next if lists[ind] != None: heappush(heap, (lists[ind].val, ind)) lists[ind] = lists[ind].next return answer_head """ :type lists: List[ListNode] :rtype: ListNode """
# in an array arr[0] <= arr[1] >= arr[2] <= arr[3] >= arr[4] .... class Solution(object): def wiggle(self, nums, l): for i in range(0, l, 2): if i + 1 < l and nums[i] > nums[i + 1]: temp = nums[i] nums[i] = nums[i + 1] nums[i + 1] = temp if i + 2 < l and nums[i + 2] > nums[i + 1]: temp = nums[i + 2] nums[i + 2] = nums[i + 1] nums[i + 1] = temp def isWiggled(self, nums, l): print(nums) nums = list(nums) for i in range(1, l, 2): if nums[i] < nums[i - 1]: return False if i + 1 < l and nums[i] < nums[i + 1]: return False return True def wiggleSort(self, nums): l = len(nums) if l < 2: return print(nums) while not self.isWiggled(nums, l): self.wiggle(nums, l)
# if matrix is """ [[1 2 3] [4 5 6] [7 8 9]] diagonally go up, 1 diagonally go down 2 4 diagonally move up 7 5 3 then down 6 8 then up 9 answer = [1,2,4,7,5,3,6,8,9] """ class Solution(object): def findDiagonalOrder(self, matrix): row = len(matrix) if row < 1: return [] col = len(matrix[0]) if col < 1: return [] answer = [] i, j = 0, 0 while True: answer.append(matrix[i][j]) if i == row - 1 and j == col - 1: break if (i + j) % 2 == 0: # move up if i == 0 and j + 1 < col: j = j + 1 elif j == col - 1 and i + 1 < row: i = i + 1 else: i, j = i - 1, j + 1 else: # move down if i == row - 1 and j + 1 < col: j = j + 1 elif j == 0 and i + 1 < row: i = i + 1 else: i, j = i + 1, j - 1 return answer """ :type matrix: List[List[int]] :rtype: List[int] """
# binary tree - serialize # 1 # /\ # 2 3 # / # 4 -1 -1 5 # class Node: def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right class Tree: def __int__(self, head=None): self.head = head def serialize(treeHead): str = [] if treeHead != None: str.append(treeHead.data) str.append(" ") else: str.append(-1) left_str = serialize(treeHead.left) right_str = serialize(treeHead.right) return str + left_str + right_str start = Node(1) start.left = Node(3) myTree = Tree(start) print(serialize(start))
# https://leetcode.com/problems/string-to-integer-atoi/submissions/ class Solution(object): def myAtoi(self, s): l = len(s) if l < 1: return 0 i = 0 while i < l and s[i] == ' ': i += 1 if i == l: return 0 j = i sighns = ["+", "-"] digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] if (s[j] in sighns and j + 1 < l and s[j + 1] in digits) or (s[j] in digits): if s[j] in sighns: j += 2 else: j += 1 while j < l and s[j] in digits: j += 1 print("i is: " + str(i)) print("j is: " + str(j)) first_num = s[i:j] first_num = int(first_num) if first_num < -2147483648: return -2147483648 elif first_num > 2147483647: return 2147483647 return first_num return 0 """ :type s: str :rtype: int """ mysol = Solution() print(mysol.myAtoi(" +-42"))
# add all numbers in a bst, add the values that fall in [low,high] # here i checked every node, but ideally, if a node value is less than low, no need to check the left branch, as all values in left will be even lessar # https://leetcode.com/problems/range-sum-of-bst/ # 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 rangeSumBST(self, root, low, high): if root == None: return 0 stack = [root] total = 0 while len(stack) > 0: node = stack.pop() if low <= node.val <= high: total += node.val if node.right: stack.append(node.right) if node.left: stack.append(node.left) return total """ :type root: TreeNode :type low: int :type high: int :rtype: int """
''' 8) Faça um Programa que leia 20 números inteiros e armazene-os num vetor. Armazene os números pares no vetor PAR e os números IMPARES no vetor impar. Imprima os três vetores. ''' vetor=[] vetorpar=[] vetorimpar=[] i=0 while i<20: print() print("Este é o número",i+1,"de 20.") numero=eval(input("Insira um número para o vetor: ")) vetor.append(numero) i=i+1 if numero%2==0: vetorpar.append(numero) else: vetorimpar.append(numero) print() print("Vetor com os vinte números:") print (vetor) print("Vetor com os pares: ") print (vetorpar) print("Vetor com os ímpares: ") print(vetorimpar)
''' Exercício 1: faça um algoritmo que solicite ao usuário números e os armazene em um vetor de 30 posições. Crie uma função que recebe o vetor preenchido e substitua todas as ocorrência de valores positivos por 1 e todos os valores negativos por 0.  ''' vet = [0]*30 for i in range(30): print("Posição",i+1,"(de 30) do vetor.") vet[i] = int(input("Insira um valor qualquer, negativo ou positivo: ")) print() print (vet) print() print("O vetor terá seus valores positivos substituídos por 1 e negativos por 0:") def troca(vet): for i in range(30): if vet[i] > 0: vet[i] = 1 else: vet[i] = 0 return vet print() print(troca(vet)) print() print("*****FIM*****")
''' 6) Desenvolva um gerador de tabuada, capaz de gerar a tabuada de qualquer número inteiro entre 1 a 10. O usuário deve informar de qual numero ele deseja ver a tabuada. A saída deve ser conforme o exemplo abaixo: Tabuada de 5: 5 X 1 = 5 5 X 2 = 10 ... 5 X 10 = 50 ''' tabuada=int(input("Insira um valor inteiro para a tabuada de multiplicação de 1 a 10: ")) x=0 while x<10: x=x+1 resultado=tabuada*x print (tabuada,"x",x,"=",resultado)
''' 1) Faça um algoritmo para ler a idade de 5 pessoas e informar qual foi a maior idade informada. ''' maior=0 x=0 for x in range(5): print() print("Esta é a idade",x+1,"de 5.") idade=int(input("Insira uma idade: ")) if idade>maior: maior=idade print() print("A maior idade é:",maior,".")
''' 5)apos calcular o IMC informe, o de acordo com o sexo informe a situação de acordo com a tabela a seguir: Condição IMC em Mulheres IMC em Homens abaixo do peso < 19,1 < 20,7 no peso normal 19,1 - 25,8 20,7 - 26,4 marginalmente acima do peso 25,8 - 27,3 26,4 - 27,8 acima do peso ideal 27,3 - 32,3 27,8 - 31, ''' print() peso=float(input("Informe o peso em kg da pessoa: ")) altura=float(input("Informe a altura em metros da pessoa: ")) print() genero=input("A pessoa é homem ou mulher? Insira h ou m: ") print() imc=float(peso/(altura*altura)) if genero=="h" or genero=="homem": if imc < 20.7: print("O imc desse homem é %2.2f e ele está abaixo do peso."%(imc)) if imc>=20.7 and imc<26.4: print("O imc desse homem é %2.2f e ele está no peso normal."%(imc)) if imc>=26.4 and imc<27.8: print("O imc desse homem é %2.2f e ele está marginalmente acima do peso."%(imc)) if imc>=27.8 and imc<31: print("O imc desse homem é %2.2f e ele está acima do peso ideal."%(imc)) if imc>=31: print("O imc desse homem é %2.2f e ele está acima da tabela."%(imc)) if genero=="m" or genero=="mulher": if imc < 19.1: print("O imc dessa mulher é %2.2f e ela está abaixo do peso."%(imc)) if imc>=19.1 and imc<25.8: print("O imc dessa mulher é %2.2f e ela está no peso normal."%(imc)) if imc>=25.8 and imc<27.3: print("O imc dessa mulher é %2.2f e ela está marginalmente acima do peso."%(imc)) if imc>=27.3 and imc<32.3: print("O imc dessa mulher é %2.2f e ela está acima do peso ideal."%(imc)) if imc>=32.3: print("O imc dessa mulher é %2.2f e ela está acima da tabela."%(imc))
''' 2)Faça um algoritmo para converter valores de fahrenheit celsius ''' resposta="sim" while resposta=="sim": fahr=float(input("Informe a temperatura em Fahrenheit: ")) celsius=(fahr-32)/1.8 print("A temperatura em Celsius é %2.2f"%(celsius)) resposta=input("Deseja inserir mais uma temperatura em Fahrenheit? Digite sim ou não: ")
x0 = 0 y0 = 0 j = 0 x1 = 0 y1 = 0 x2 = 0 def showled(x: number, y: number, dir: number): pass def on_forever(): showled(0, 0, 0) showled(4, 0, 1) showled(0, 4, 2) showled(4, 4, 3) basic.forever(on_forever) def on_forever2(): global x0, y0, j, x1, y1, x2 x0 = 4 y0 = 0 for i in range(5): j = 0 led.plot(x0, y0) while j <= i - 1: y2 = 0 j += 1 x1 = x0 y1 = y0 - j x2 = x0 + j led.plot(x1, y1) led.plot(x2, y2) basic.pause(200) x0 = x0 - 1 y0 = y0 + 1 basic.clear_screen() basic.forever(on_forever2)
# -*- coding: utf-8 -*- """ Created on Sat Oct 5 21:28:09 2019 @author: laksh """ l=[1,4,2,7,4,8] print(max(l[2:5])) print(l) print(min(l[2:5]))
# -*- coding: utf-8 -*- """ Created on Thu Oct 17 11:02:39 2019 @author: laksh """ for i in range(int(input())): n=int(input()) l=[] for j in range(n): #l.append([]) l.append(str(input())) print(l) print(sorted(l)) break
# Implementation of Matrix Chain Multiplication in Python # Time Complexity: O(n^3) # Space Complexity: O(n^2) from math import inf def matrixChain(arr): n = len(arr) dp = [[0]*n for i in range(n)] # dp[i, j] = Minimum number of scalar multiplications needed to multiply arr[i..j] # chain length for length in range(2, n): for l in range(1, n-length+1): r = l + length - 1 dp[l][r] = inf for c in range(l, r): # cost of left cut + cost of right cut + cost of merging cost = dp[l][c] + dp[c+1][r] + arr[l-1]*arr[c]*arr[r] dp[l][r] = min(dp[l][r], cost) return dp[1][n-1]
from math import factorial as fact def factorial(numStr): try: n = int(numStr) r = str(fact(n)) except: r = 'Error!' return r def decToBin(numStr): try: n = int(numStr) r = bin(n)[2:] except: r = 'Error!' return r def binToDec(numStr): try: n = int(numStr, 2) r = str(n) except: r = 'Error!' return r def decToRoman(numStr): try: n = int(numStr) except: return "Error!" if n >= 4000: return "Error!" romans = [(1000, 'M'),(900,'CM'),(500,'D'),(400,'CD'), (100, 'C'),(90,'XC'),(50, 'L'),(40, 'XL'), (10, 'X'),(9, 'IX'),(5, 'V'),(4, 'IV'), (1, 'I'), ] result = '' for value, letters in romans: # 보기에 훨씬 좋음! & 사전을 연속시키면 순서가 정해지지 않아서 계산 순서 고려 ㄴㄴ! while n >= value: result += letters n -= value return str(result) def romanToDec(numStr): try: n = numStr except: return "Error!" romans = [(1000,'M'),(900,'CM'),(500,'D'),(400,'CD'), (100,'C'),(90,'XC'),(50,'L'),(40,'XL'), (10,'X'),(9,'IX'),(5,'V'),(4,'IV'), (1,'I'), ] result = 0 for j in range(len(romans)): while(n.find(romans[j][1]) == 0): result += romans[j][0] n = n[len(romans[j][1]):] return str(result)
class Menu (object): def mostrarMenu(self): print("\nIngresar opcion:\n" "\t1 - Ver listado de cuentas \n" "\t2 - Ver cuentas por titular \n" "\tq - salir \n") key = input() self.procesarOpcion(key) def procesarOpcion(self, key): item = self.keySwitcher.get(key) if callable(item): return item() def verListaCuentas(self): listaCuentas = self.bd.getListaCuentas() for c in listaCuentas: self.printCuenta(c) def verCuentasTitular(self): print("Ingrese ID del cliente: ") clienteID = input() if self.bd.existeCliente(clienteID): listaCuentas = self.bd.getListaCuentasDelTitular(clienteID) print("\nID del cliente: " + clienteID) if listaCuentas == []: print("\nEl cliente no posee cuentas") else: for c in listaCuentas: self.printCuenta(c) else: print("\nEl cliente no existe en la base de datos!") def printCuenta(self, cuenta): print("Cuenta id: " + cuenta['id'] + "\n \t Balance: " + cuenta['balance']) def __init__(self, bd): self.bd = bd self.key = '' self.keySwitcher = {"1": self.verListaCuentas, "2": self.verCuentasTitular, "q": quit}
""" Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. Solution: Two pointers / Start from the end Time complexity: O(m + n) Space complexity : O(1) """ import unittest class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead. """ last, i, j = n+m-1, m-1, n-1 while i >= 0 and j >= 0: if nums1[i] < nums2[j]: nums1[last] = nums2[j] j -= 1 else: nums1[last] = nums1[i] i -= 1 last -= 1 if j >= 0: nums1[:(j+1)] = nums2[:(j+1)] return nums1 class testMerge(unittest.TestCase): def testCase1(self): s = Solution() self.assertEqual(s.merge([1,0], 1, [2], 1), [1,2]) def testCase2(self): s = Solution() self.assertEqual(s.merge([2,0], 1, [1], 1), [1,2]) def testCase3(self): s = Solution() self.assertEqual(s.merge([0], 0, [2], 1), [2]) if __name__ == "__main__": unittest.main()
""" // Time Complexity : O(nlogn), where n is the number of elements in the array // Space Complexity : O(n) // Did this code successfully run on Leetcode : not on leetcode // Any problem you faced while coding this : No """ # Python program for implementation of Quicksort # This function is same in both iterative and recursive def partition(arr, l, h): #write your code here p = h #setting pivot to be the last element i = l #setting i to start from the first element in arr for i in range(l, h): if arr[i] < arr[p]: #if element smaller than the pivot element is found, we swap that element with low and increment low to point to the next position arr[i], arr[l] = arr[l], arr[i] #swap l = l+1 arr[l], arr[p] = arr[p], arr[l] #after the loop terminates, low will be pointing to the correct position of the pivot element, hence we swap the values at low and p so that the pivot element is at its correct position return l #return the point where partition happens def quickSortIterative(arr, l, h): #write your code here stack=[] #using stack to keep track of end points of all the lists created on partitioning stack.append(l) #adding the initial values to the stack stack.append(h) while stack: high=stack.pop() low=stack.pop() p=partition(arr,low, high) #gets the pivot element if p-1>low: #if elements are present on the left side of the pivot, we add the end points from low to p-1 to the stack stack.append(low) stack.append(p-1) if p+1<high: #if elements are present on the right side of the pivot, we add the end points from p+1 to high to the stack stack.append(p+1) stack.append(high)
#!/usr/bin/env python # -*- coding: utf-8 -*- # q/quit to quit, ENC_message to print encoded "message", otherwise decodes message # To type an encoded message, use type your message while holding the option key # (this makes it type in weird unicode characters), letters will be automatically # lowercased due to an overlap issue, but you can use symbols and punctuation with # the shift key and it should encode/decode correctly. # Doesn't support ` or ~ (they're the same character w/ option key), but why the # hell would you need that? # Also doesn't support multi-line input, because why import sys lettersH = u'œ∑´®†\¨ˆøπåß∂ƒ©˙∆˚¬Ω≈ç√∫˜µŒ„´‰ˇÁ¨ˆØ∏ÅÍÎÏ˝ÓÔÒ¸˛Ç◊ı˜Â¥' letters = u'qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmy' punctH = u' ¯˘¿ÚÆ”’» ≤≥÷…æ“‘«``' punct = u' <>?:"{}| ,./;\'[]\\`~' numbersH = u'⁄€‹›fifl‡°·‚—±¡™£¢∞§¶•ªº–≠' numbers = u'!@#$%^&*()_+1234567890-=' def decode(s): print 'DECODE:',s ret = '' for i in range(len(s)): if s[i] in lettersH: ret += letters[lettersH.find(s[i])] elif s[i] in punctH: ret += punct[punctH.find(s[i])] elif s[i] in numbersH: ret += numbers[numbersH.find(s[i])] else: ret += s[i] return ret def encode(s): print 'ENCODE:',s ret = '' for c in s: if c in letters: ret += lettersH[letters.find(c)] elif c in punct: ret += punctH[punct.find(c)] elif c in numbers: ret += numbersH[numbers.find(c)] else: ret += c return ret if __name__ == "__main__": while True: s = raw_input('Gimme an encoded message: ') encodeCode = 'ENC_' if s == 'q' or s == 'quit': sys.exit() elif s.find(encodeCode) == 0: print encode(unicode(s[len(encodeCode):].lower(),'utf-8')) else: print decode(unicode(s,'utf-8'))
# <QUESTION 1> # Given a list of items, return a dictionary mapping items to the amount # of times they appear in the list # Note: the order of this dictionary does not matter # <EXAMPLES> # one(['apple', 'banana', 'orange', 'orange', 'apple', 'apple']) → {'apple':3, 'orange':2, 'banana':1} # one(['tic', 'tac', 'toe']) → {'tic':1, 'tac':1, 'toe':1} def one(items): return {item : items.count(item) for item in items} pass # <QUESTION 2> # Given two numbers, a & b, and an operator, evaluate the operation between a & b # using the given operator # The operator will be a string, and will only be +, -, *, or /. # <EXAMPLES> # two(2, 4, '+') → 6 # two(7, 3, '-') → 4 # two(3, 1.5, '*') → 4.5 # two(-5, 2, '/') → -2.5 def two(a, b, operator): if (operator == '+'): return a + b elif (operator == '-'): return a - b elif (operator == '*'): return a * b elif (operator == '/'): return a / b else: return "Not a valid operator" pass # <QUESTION 3> # Given a positive integer, return the next integer below it that has an # integer square root (is the square of another integer) # If the number has a square root, just return the number # <EXAMPLES> # three(7) → 4 # 4 is the square of 2 # three(64) → 64 # 64 is the square of 8 already # three(32) → 25 # <HINT> # We can use `x ** 0.5` to get the square root of `x` def three(num): i = num while i >= 1: if i %(i ** 0.5) == 0: return i i -=1 pass # <QUESTION 4> # Given two integers, return the greatest common factor of the two numbers # <EXAMPLES> # four(32, 24) → 8 # four(18, 11) → 1 # four(10, 50) → 10 def four(a, b): c = min(a,b) factorlist = [] i = 1 while i <= c: if(a % i == 0 and b % i == 0): factorlist.append(i) i +=1 factorlist.sort() return factorlist[-1] pass # <QUESTION 5> # Given a string, return a string where each letter is the previous letter in the alphabet # in comparison to the original string # For a or A, use z or Z respectively # Ignore characters that aren't in the alphabet, such as whitespace or numbers # <EXAMPLES> # five('wxyz') → 'vwxy' # five('abc') → 'zab' # five('aAbB') → 'zZaA' # five('hello world') → 'gdkkn vnqkc' # five('54321') → '54321' def five(string): newlist = [] for letter in string: if not (letter.isalpha()): newlist.append(letter) elif (letter == "a"): newlist.append("z") elif (letter == "A"): newlist.append("Z") else: newlist.append(chr(ord(letter)-1)) return "".join(newlist) pass
import requests import sys import glob import csv import os from zipfile import ZipFile from datetime import datetime DATE=sys.argv[1] MONTH=sys.argv[2] YEAR=sys.argv[3] url = "https://www.nseindia.com/content/historical/EQUITIES/%s/%s/cm%s%s%sbhav.csv.zip" % (YEAR, MONTH, DATE, MONTH, YEAR) fileZip = "Zip%s%s%s.zip" % (DATE, MONTH, YEAR) file = "cm%s%s%s.csv" % (DATE, MONTH, YEAR) print ("INFORMATION: Connecting to " +url) # download the file contents in binary format to healthcheck URL print ("STAGE 1/5: Connecting to URL") r = requests.get(url) # 200 means a successful request if (r.status_code == 200): # open method to open a file on your system and write the contents print ("STAGE 2/5: Saving zip") with open(fileZip, "wb") as code: code.write(r.content) #Extract all the contents of zip in new file directory (created relativve to he current dir) print ("STAGE 3/5: Unzip the file") with ZipFile(fileZip, 'r') as zipObj: zipObj.extractall('file') #Rename extracted files dst = 'file/'+ file for filename in os.listdir('file'): src = 'file/' + filename os.rename(src, dst) print ("STAGE 4/5: Filter the data") # Apply filter condition csvReader=csv.reader(open(dst,'r'),delimiter = ',') csvWriter=csv.writer(open('file/filtered.csv','w',newline=''),delimiter = ',') firstline = True for row in csvReader: if firstline: csvWriter.writerow(row) firstline = False continue EQCONDITIONON=row[1] VALUECONTIONON=row[9] if(EQCONDITIONON=='EQ' and float(VALUECONTIONON)>=10000000): csvWriter.writerow(row) # Format datetime print ("STAGE 5/5: Formating date") csvReader=csv.reader(open('file/filtered.csv','r'),delimiter = ',') csvWriter=csv.writer(open('output.csv','w',newline=''),delimiter = ',') firstline = True for row in csvReader: if firstline: csvWriter.writerow(row) firstline = False continue data=row[10] df=datetime.strptime(data, '%d-%b-%Y').strftime('%y%m%d') csvWriter.writerow(row+[df]) print ("INFORMATION: All stage complete") print ("INFORMATION: Performing cleanup") os.remove(fileZip) else: print ("ERROR: Something went wrong!") print ("Exiting Program due to Error in URL, Please try different URL") print ("SUCCESS: Please check processed 'output.csv' file in your current directory")
"""This module defines the `Space` class.""" import abc import random import typing import numpy from . import dataset from . import metric class Space(abc.ABC): """This class combines a `Dataset` and a `Metric` into a `MetricSpace`. We build `Cluster`s and `Graph`s over a `MetricSpace`. This class provides access to the underlying `Dataset` and `Metric`. Subclasses should implement the methods to compute distances between indexed instances using the underlying `Metric` and `Dataset`. For those cases where the distance function in `Metric` is expensive to compute, this class provides a cache which stores the distance values between pairs of instances by their indices. If you want to use the cache, set the `use_cache` parameter to True when instantiating a metric space. """ def __init__(self, use_cache: bool) -> None: """Initialize the `MetricSpace`.""" self.__use_cache = use_cache self.__cache: dict[tuple[int, int], float] = {} @property def name(self) -> str: """The name of the `MetricSpace`.""" return f"{self.data.name}__{self.distance_metric.name}" @property def uses_cache(self) -> bool: """Whether the object distance values.""" return self.__use_cache @property @abc.abstractmethod def data(self) -> dataset.Dataset: """The `Dataset` used to compute distances between instances.""" pass @property @abc.abstractmethod def distance_metric(self) -> metric.Metric: """The `Metric` used to compute distances between instances.""" pass @abc.abstractmethod def are_instances_equal(self, left: int, right: int) -> bool: """Given two indices, returns whether the corresponding instances are equal. Usually, this will rely on using a `Metric`. Two equal instances should have a distance of zero between them. The default implementation relies on this. """ return self.distance_one_to_one(left, right) == 0.0 @abc.abstractmethod def subspace(self, indices: list[int], subset_data_name: str) -> "Space": """See the `Dataset.subset`.""" pass @abc.abstractmethod def distance_one_to_one(self, left: int, right: int) -> float: """See the `Dataset.one_to_one`. The default implementation uses the cache.""" if not self.is_in_cache(left, right): d = self.distance_metric.one_to_one(self.data[left], self.data[right]) self.add_to_cache(left, right, d) return self.get_from_cache(left, right) @abc.abstractmethod def distance_one_to_many(self, left: int, right: list[int]) -> numpy.ndarray: """See the `Dataset.one_to_many`. The default implementation uses the cache.""" distances = [self.distance_one_to_one(left, r) for r in right] return numpy.asarray(distances, dtype=numpy.float32) @abc.abstractmethod def distance_many_to_many(self, left: list[int], right: list[int]) -> numpy.ndarray: """See the `Dataset.many_to_many`. The default implementation uses the cache.""" distances = [self.distance_one_to_many(i, right) for i in left] return numpy.stack(distances) @abc.abstractmethod def distance_pairwise(self, indices: list[int]) -> numpy.ndarray: """See the `Dataset.pairwise`. The default implementation uses the cache.""" return self.distance_many_to_many(indices, indices) @staticmethod def __cache_key(i: int, j: int) -> tuple[int, int]: """This works because of the `symmetry` property of a `Metric`.""" return (i, j) if i < j else (j, i) def is_in_cache(self, i: int, j: int) -> bool: """Checks whether the distance between `i` and `j` is in the cache.""" return self.__cache_key(i, j) in self.__cache def get_from_cache(self, i: int, j: int) -> float: """Returns the distance between `i` and `j` from the cache. Raises a KeyError if the distance value is not in the cache. """ return self.__cache[self.__cache_key(i, j)] def add_to_cache(self, i: int, j: int, distance: float) -> None: """Adds the given `distance` to the cache.""" self.__cache[self.__cache_key(i, j)] = distance def remove_from_cache(self, i: int, j: int) -> float: """Removes the distance between `i` and `j` from the cache.""" return self.__cache.pop( # type: ignore[call-overload] self.__cache_key(i, j), default=0.0, ) def clear_cache(self) -> int: """Empty the cache and return the number of items that were in the cache.""" num_items = len(self.__cache) self.__cache.clear() return num_items def choose_unique( self, n: int, indices: typing.Optional[list[int]] = None, ) -> list[int]: """Randomly chooses `n` unique instances from the dataset. Args: n: The number of unique instances to choose. indices: Optional. The list of indices from which to choose. Returns: A randomly selected list of indices of `n` unique instances. """ indices = indices or list(range(self.data.cardinality)) if not (0 < n <= len(indices)): msg = ( f"`n` must be a positive integer no larger than the length of " f"`indices` ({len(indices)}). Got {n} instead." ) raise ValueError(msg) randomized_indices = indices.copy() random.shuffle(randomized_indices) if n == len(randomized_indices): return randomized_indices chosen: list[int] = [] for i in randomized_indices: for o in chosen: if self.are_instances_equal(i, o): break else: chosen.append(i) if len(chosen) == n: break return chosen class TabularSpace(Space): """A `Space` that uses a `TabularDataset` and a `Metric`.""" def __init__( self, data: typing.Union[dataset.TabularDataset, dataset.TabularMMap], distance_metric: metric.Metric, use_cache: bool, ) -> None: """Initialize the `MetricSpace`.""" self.__data = data self.__distance_metric = distance_metric super().__init__(use_cache) @property def data( self, ) -> typing.Union[dataset.TabularDataset, dataset.TabularMMap]: """Return the data.""" return self.__data @property def distance_metric(self) -> metric.Metric: """Return the distance metric.""" return self.__distance_metric def are_instances_equal(self, left: int, right: int) -> bool: """Return whether the instances at `left` and `right` are identical.""" return self.distance_one_to_one(left, right) == 0.0 def distance_one_to_one(self, left: int, right: int) -> float: """Compute the distance between `left` and `right`.""" if self.uses_cache: return super().distance_one_to_one(left, right) return self.distance_metric.one_to_one(self.data[left], self.data[right]) def distance_one_to_many( self, left: int, right: list[int], ) -> numpy.ndarray: """Compute the distances between `left` and each instance in `right`.""" if self.uses_cache: return super().distance_one_to_many(left, right) return self.distance_metric.one_to_many(self.data[left], self.data[right]) def distance_many_to_many( self, left: list[int], right: list[int], ) -> numpy.ndarray: """Compute the distances between instances in `left` and `right`.""" if self.uses_cache: return super().distance_many_to_many(left, right) return self.distance_metric.many_to_many(self.data[left], self.data[right]) def distance_pairwise(self, indices: list[int]) -> numpy.ndarray: """Compute the distances between all pairs of instances in `indices`.""" return self.distance_metric.pairwise(self.data[indices]) def subspace( self, indices: list[int], subset_data_name: str, ) -> "TabularSpace": """Return a subspace of this space.""" return TabularSpace( self.data.subset(indices, subset_data_name), self.distance_metric, self.uses_cache, ) __all__ = [ "Space", "TabularSpace", ]
myVar = input("What if your answer to my 1st question? (yes/no) ") if myVar == "yes": myNextVar = input("What id your answer to my 2nd question? (yes/no) ") if myNextVar == "yes": print("Good your paying attention.") elif myNextVar == "no": print("Come on man pay attention") else: print("Answer my question! You didnt type yes or no.") elif myVar =="no": ("Come on man pay attention") else: print("Answer my question! You didn't type yes or no")
#ben shade #Counts_to_twenty this program count to 20 print("this counts to 20") number = 0 while number < 21: print(number , end = " " ) number += 1
import abc class StorageManagerInterface(abc.ABC): """ Interface for a file storage manager of our time series Methods ------- store: Stores a given time series `t` into the storage manager by index size: Returns the length of the time series in storage by index get: Returns a time series instance by index """ @abc.abstractmethod def store(self, id, t): """ Stores a given time series `t` into the storage manager, indexed by `id` Parameters ---------- id : int / string id to which the given time series `t` is assigned t : SizedContainerTimeSeriesInterface The time series to be stored Returns ------- t : SizedContainerTimeSeriesInterface The input time series Notes ----- - if the `id` already exists in storage, then we overwrite the previous time series corresponding with the given id with `t`. """ @abc.abstractmethod def size(self, id): """ Returns the length of the time series in storage indexed by `id` Parameters ---------- id: int / string id of the time series of interest Returns ------- l : int Length of the time series in storage corresponding to `id` Notes ----- PRE: `id` should exist in the storage manager WARNINGS: If given `id` does not exist, then KeyError is raised """ @abc.abstractmethod def get(self, id): """ Returns a time series instance by given `id` Parameters ---------- id: int / string id of the time series of interest Returns ------- t : SizedContainerTimeSeriesInterface The time series corresponding to the given `id` Notes ----- PRE: `id` should exist in the storage manager WARNINGS: If given `id` does not exist, then KeyError is raised """
# The 3-sum problem. def has_three_sum(nums, t): nums.sort() for n in nums: if has_two_sum(nums, t - n): return True return False def has_two_sum(nums, t): i, j = 0, len(nums) - 1 while i < j: cur_sum = nums[i] + nums[j] if cur_sum < t: i += 1 elif cur_sum == t: return True else: j -= 1 return False
# Is an anonymous letter constructible? def is_letter_constructable(str_m, str_l): dict_m = {} for c in str_m: if c not in dict_m: dict_m[c] = 1 else: dict_m[c} += 1 for c in str_l: if c not in dict_m: return False else: dict_m[c] -= 1 if dict_m == 0: dict_m.pop(c) return True
# Find the nearest repeated entries in an array. import sys def find_nearest_repetition(p): words = {} ret = sys.maxint for i in range(len(p)): cur_word = p[i] if cur_word in words: ret = min(ret, i - words[cur_word]) words[cur_word] = i return ret
# Test palindromicity. def is_palindrome(s): i, j = 0, len(s) - 1 while i < j: while (not s[i].isalnum() and i < j): i += 1 while (not s[j].sialnum() and i < j): j -= 1 if s[i] != s[j]: return False i += 1 j -= 1 return True
# Test for palindromic permutations. def can_form_palindrome(s): c2cnt = {} for c in s: if c in c2cnt: c2cnt[c] += 1 else: c2cnt[c] = 1 odd_cnt = 0 for v in c2cnt.values(): if v % 2 != 0: odd_cnt += 1 if odd_cnt > 1: return False return True
# Find the first key greater than a given value in a BST. class TreeNode: def __init__(v=None, l=None, r=None): self.v = v self.l = l self.r = r def find_first_greater(t, k): sub_t, ret = t, None while sub_t: if sub_t.v > k: ret = sub_t.v sub_t = sub_t.l else: sub_t = sub_t.r return ret
# Find the majority element. def majority_search(iter_str): cand = None cur_str, cnt_cand = next(iter_str, None), 0 while cur_str: if cnt_cand == 0: cand = cur_str cnt_cand = 1 elif cur_str == cand: cnt_cand += 1 else: cnt_cand -= 1 cur_str = next(iter_str, None) return cand # Test. case = [2,1,3,1,1,2,1,1,3,1] print majority_search(iter(case))
def find_maxsum_subarray(nums): min_sum, cur_sum, max_sum = 0, 0, 0 for n in nums: cur_sum += n if cur_sum < min_sum: min_sum = cur_sum if cur_sum - min_sum > max_sum: max_sum = cur_sum - min_sum return max_sum
# recursive, O(n) space def calc_fibonacci_recursive(n): f_dict = {} if n < 2: return n elif n not in f_dict: f_dict[n] = (calc_fibonacci_recursive(n - 2) + calc_fibonacci_recursive(n - 1)) return f_dict[n] # iterative, O(1) space def calc_fibonacci_iterative(n): if n < 2: return n else: pre, cur = 0, 1 for _ in range(2, n + 1): ret = cur + pre pre, cur = cur, ret return ret for i in range(6): print calc_fibonacci_iterative(i)
from __future__ import division from collections import defaultdict from math import log import csv # create function to train # it takes data data is a dict: (words) -> lang # from tuple of language words -> to language def train(data): # 2 dicts with 0 as default values # classes are languages, we classify texts by languages # counts how many programms written in each language # e.g. JAVA: 39123 classes = defaultdict(lambda: 0) # frequenses is dict: (LANG, WORD) -> FREQ # from tuple of lang and a word from this lang -> to frequency of this word in lang # e.g. (C++, #include<iostream>): 302 # means that #include<iostream> meets C++ 302 times frequences = defaultdict(lambda: 0) print('learning...') # features here are words from language # label is a language for features, label in data.items(): # count each text in the language classes[label] += 1 # for each word in the text for feature in features: # increase count for the word from the language # (C++, #include<iostream>): 302 -> (C++, #include<iostream>): 303 frequences[label, feature] += 1 # label is language here # feature is a word from this language for label, feature in frequences.keys(): # divide each lang-word-counter by amount of programms in the language # we get the probability of meeting of the word in the text of the language frequences[label, feature] /= classes[label] # for each language for c in classes: # we get the probability of meeting of the language classes[c] /= len(data) print('learned.') return classes, frequences def classify(classifier, features): # classes.keys is frequences of languages # prob is probability of meeting word in the language # prob type (LANGUAGE, WORD) -> PROBABILITY classes, prob = classifier # find minimum value in Languages by function which is math magic # key defines how we search minimum, how to compare values # how to map Languages to numbers to make them comparable return min( classes.keys(), key = lambda cl: -log(classes[cl]) + sum(-log(prob.get((cl,f), 10**(-7))) for f in features) ) # function to extract features modify it change # how words are separated, which words are taken and so on def get_features(text: str) -> tuple: # v2 addition: delete words with length < 2 long_word = lambda s: len(s) > 1 return tuple( filter(long_word, text.split()) ) # create dicts for train and tests # their type is Dict<TupleOfStrings, String> # where TupleOfStrings are words for language # String is language name test_data = {} train_data = {} def read_data(): # just reading data to test_data and train_data # open file data.csv data_csv = open('data.csv', 'r') # create csv reader from the file data_reader = csv.reader(data_csv) # reading header to make it absent in data header = next(data_reader) print('reading train data') # reading 400 thousands of samples as training data i = 0 for line in data_reader: # line is solutionId, program, language # e.g. 1234, "#include<iostream> using namespace std;...", 'C++' # we split program by space and get list ['#include<iostream>', 'using', 'namespace', 'std;'] # we delete words from 1 symbol # we make tuple from result. tuple is immutable list words = get_features(line[1]) train_data[words] = line[2] i += 1 # we take only 400_000 programs for training, the others for test #FIXME #TODO replace 400 with 400_000 or number of programs to learn # remaining will be used for test # please note: original dataset has over 620 thousands of samples (link in README.md) # data.csv in this repository has a thousand times less if i >= 400: break print('reading test data') # other 230_778 # idk how 400_000 + 230_778 = 620_536 for line in data_reader: words = get_features(line[1]) test_data[words] = line[2] # print(len(all_data)) # 620_536 read_data() # features classifier = train(train_data) # create dictionary with default value equal to (0, 0) # it is a dict of type string: (int, int) # where string is langueage name, and (int, int) is how # predictions are correct of all programs amount # if we have 300 programs in python, and we predict it to be python for 230 times # it will be {'PYTH': (230, 300)} analysis = defaultdict(lambda: (0, 0)) print('testing...') size = len(test_data) i = 0 for test_feat, lang in test_data.items(): ans = classify(classifier, test_feat) # match - how many times we predicted the language # whole - how many programs in the language we met indeed match, whole = analysis[lang] # match is how many matches classifier got # whole is how many times classifier met the lang # if we predicted it right +1 otherwise do nothing # in both cases increase how many times we met programs in the language analysis[lang] = (match + 1 if ans == lang else match, whole + 1) if i % 1000 == 0: print(str(i) + ' of ' + str(size) + ' ready.') i += 1 print('ready.') # pring results # <LANG>: <we got it right> of <how many programs in the language actually> # e.g. JAVA: 1234 of 4312 for k, v in analysis.items(): print(k + ': ' + str(v[0]) + ' of ' + str(v[1]))
#The main purpose of this file is to determine the best word using the spaces #on the board, and to calculate what the score would be for a specific #word placement on a certain part of the board, after we define the specific #spaces on the board that correspond to "special" tiles, and the scores we would #get for each letter. This lets us calculate the optimal score. tripleWord = [0, 7, 14, 105, 119, 210, 217, 224] doubleWord = [16, 28, 32, 42, 48, 56, 64, 70, 154, 160, 168, 176, 182, 192, 196, 208] doubleLetter = [3, 11, 36, 38, 45, 52, 59, 92, 96, 98, 102, 108, 116, 122, 126, 128, 132, 165, 172, 179, 186, 188, 213, 221] tripleLetter = [20, 24, 76, 80, 84, 88, 136, 140, 144, 148, 200, 204] scoresForTiles = {'A': 1, 'B': 3, 'C': 3, 'D': 2, 'E': 1, 'F': 4, 'G': 2, 'H': 4, 'I': 1, 'J': 8, 'K': 5, 'L': 1, 'M': 3, 'N': 1, 'O': 1, 'P': 3, 'Q': 10, 'R': 1, 'S': 1, 'T': 1, 'U': 1, 'V': 4, 'W': 4, 'X': 8, 'Y': 4, 'Z': 10} def bestPossibleWord(letterCombinations, currBoard): bestWord = [-1, [], []] bestPlacementLocations = [] for combination in letterCombinations: wordVal = 0 letters = {} for (char, cell) in zip(combination[0], combination[1]): letters[cell] = char for combo in combination[2]: wordVal += calculateWordScore(combo, letters, currBoard) if len(combination[1]) == 7: #full hand! wordVal += 50 if wordVal > bestWord[0]: bestWord = [wordVal, combination[0], combination[1]] bestPlacementLocations = combination[1] for cell in bestPlacementLocations: if cell in tripleWord: tripleWord.remove(cell) elif cell in doubleWord: doubleWord.remove(cell) elif cell in doubleLetter: doubleLetter.remove(cell) elif cell in tripleLetter: tripleLetter.remove(cell) return bestWord def calculateWordScore(wordPossible, lettersDict, currBoard): thisTileScore = 0 dubscore = 0 tripscore = 0 scoreAdd = 1 dub = 2 trip = 3 for cell in wordPossible: if cell in doubleWord: dubscore += scoreAdd elif cell in tripleWord: tripscore += scoreAdd if cell in doubleLetter: if cell in lettersDict: thisTileScore += dub*scoresForTiles[lettersDict[cell]] else: thisTileScore += dub*scoresForTiles[currBoard[cell]] elif cell in tripleLetter: if cell in lettersDict: thisTileScore += trip*scoresForTiles[lettersDict[cell]] else: thisTileScore += trip*scoresForTiles[currBoard[cell]] else: if cell in lettersDict: thisTileScore += scoresForTiles[lettersDict[cell]] else: thisTileScore += scoresForTiles[currBoard[cell]] return thisTileScore * (dub**dubscore) * (trip**tripscore)
""" Exercício 2: Nova busca : até o momento nossa estrutura consulta elementos através da posição. Nesta atividade será necessário criar uma função chamada def index_of(self, value) , onde ela será responsável por consultar na lista a existência do valor informado e retornar a posição da primeira ocorrência. Caso o valor não exista, considere retornar -1 . Esta função deve respeitar a complexidade O(n). """ """ Nesta atividade é necessário percorrer toda a lista. As condições de parada são a existência do valor ou ter percorrido toda a lista sem sucesso. O valor é retornado caso encontrado e -1 caso contrário. """ def index_of(self, value): position = 1 current_value = self.head_value while current_value: if current_value.value == value: return position current_value = current_value.next position += 1 return -1
# Exercício 2 Suponha que se está escrevendo uma função para um jogo de batalha # naval. Dado um array bidimensional com n linhas e m colunas, e um par de # coordenadas x para linhas e y para colunas, o algoritmo verifica se há um # navio na coordenada alvo. Por exemplo: entrada = [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, ] # resultado para (0, 4) = True # resultado para (1, 1) = False """ Mesmo para um array bidimensional, o acesso a um elemento é O(1). A complexidade de espaço também é O(1), pois não consideramos a entrada em seu cálculo.""" def battleship(grid, line, column): if grid[line][column] == 1: return True return False
# ❗ Importe arquivo books.json no mongo antes de responder próximas questões. # 🦜 mongoimport --db library books.json # Exercício 6 Escreva um programa que se conecte ao banco de dados library e # liste os livros da coleção books para uma determinada categoria recebida por # uma pessoa usuária. Somente o título dos livros deve ser exibido. from pymongo import MongoClient category = input("Escolha uma categoria: ") with MongoClient() as client: db = client.library for book in db.books.find({"categories": category}, projection=["title"]): print(book["title"])
# Exercício 3: Faça um programa que, dado um valor n qualquer, # tal que n > 1, imprima na tela um quadrado feito de asteriscos # de lado de tamanho n. Por exemplo: def draw_square(n): for row in range(n): print(n * "*") draw_square(10)
# Exercício 2: Faça um programa que, dado um valor n qualquer, tal que n > 1, # imprima na tela um triângulo retângulo com 5 asteriscos de base. Por exemplo: def draw_triangle(n): for row in range(1, n + 1): print(row * '*') draw_triangle(15)
""" Quais elementos da lista A também ocorrem na lista B? Ou seja, qual interseção entre lista """ listA = [1, 2, 3, 4, 5, 6] listB = [4, 5, 6, 7, 8, 9] # resposta: [4, 5, 6] # O(n + m) def instersection(listA, listB): # criar uma dict da listA seen_in_a = {} for item in listA: if item not in seen_in_a: seen_in_a[item] = True ans = [] for item in listB: if item in seen_in_a: ans.append(item) return ans print(instersection(listA, listB))
""" Exercício 1: Pilhas - Baseado nos conhecimentos adquiridos neste bloco, implemente uma pilha utilizando a Deque como a estrutura interna. Sua pilha deve conter as operações: push, pop, peek e is_empty Para este desafio, é necessário efetuar o import da classe Deque e utilizar seus métodos de acesso para simular uma pilha. """ from exercicio_dia_2 import Deque class Stack: def __init__(self): self._deque = Deque() def __len__(self): return len(self._deque) def push(self, value): self._deque.push_back(value) def pop(self): return self._deque.pop_back() def peek(self): return self._deque.peek_back() def is_empty(self): return not len(self)
# Exercício 6 # Dado um array de doces candies e um valor inteiro extra_candies, onde o # candies[i] representa o número de doces que a enésima criança possui. Para # cada criança, verifique se há uma maneira de distribuir doces extras entre # as crianças de forma que ela possa ter o maior número de doces entre elas. # Observe que várias crianças podem ter o maior número de doces. Analise o # código abaixo para o melhor, pior caso e caso médio. """Para os três casos, utilizando a função `max()` do Python, a complexidade será O(n). A lista abaixo da função `max()` também é executada em O(n). Ou seja, O(n) + O(n) = O(n). A complexidade de espaço também é O(n), pois quanto mais crianças temos, maior vai ser o tamanho da lista gerada. Faça a analise de complexidade de espaço também.""" def kids_with_candies(candies, extra_candies): # parece que a solução percorre o array somente uma vez, # porém isto é feito duas vezes, uma no `max` e outra para # preencher a resposta max_candies = max(candies) return [candy + extra_candies >= max_candies for candy in candies] # saída: [True, True, True, False, True] print(kids_with_candies([2, 3, 5, 1, 3], 3))
# CRIANDO ENTIDADE USER class User: def __init__(self, name, email, password): """Método construtor da classe User. Note que o primeiro parâmetro deve ser o `self`. Isso é uma particularidade de Python, vamos falar mais disso adiante!""" self.name = name self.email = email self.password = password # Para invocar o método construtor, a sintaxe é # NomeDaClasse(parametro 1, parametro 2) # Repare que o parâmetro self foi pulado -- um detalhe do Python. meu_user = User("Valentino Trocatapa", "[email protected]", "Grana") # A variável `meu_user` contém o objeto criado pelo construtor da classe User!
# Exercício 6 # Escreva uma função que identifique o único número duplicado em uma lista. # Retorne o número duplicado em O(n). # Exemplos de entrada e saída: entrada = [1, 3, 2, 4, 5, 1] # saída: 1 # Exercício 7 # Sua trajetória no curso foi um sucesso e agora você está trabalhando para a # Trybe! Em um determinado módulo, os estudantes precisam entregar dois # trabalhos para seguir adiante. Cada vez que um dos trabalhos é entregue, o # nome da pessoa fica registrado. Precisamos saber como está o andamento da # entrega das listas. Para isso, você tem acesso aos nomes das pessoas da # turma, bem como ao log de quem já entregou qual lista. A partir das listas # abaixo, crie quatro funções que respondem às perguntas a seguir. estudantes = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] lista1_entregues = ['a', 'd', 'g', 'c'] lista2_entregues = ['c', 'a', 'f'] # Quem ainda não entregou a lista1? # Quem já entregou as duas listas? # Quem já entregou qualquer uma das duas listas? # Quem ainda não entregou nenhuma das listas?
""" Separe as palavras de acordo com sua letra inicial text = ['ana', 'ama', 'joao', 'que', 'ama', 'jose', 'mas', 'jose', 'nao', 'ama', 'ana'] reposta: a: ['ana', 'ama', 'ama', 'ama', 'ana'] j: ['joao', 'jose', 'jose'] q: ['que'] m: ['mas'] n: ['nao'] """ text = [ "ana", "ama", "joao", "que", "ama", "jose", "mas", "jose", "nao", "ama", "ana", ] def screening(text): screen = {} for word in text: first_char = word[0] if first_char not in screen: screen[first_char] = [word] else: screen[first_char].append(word) return screen for key, value in screening(text).items(): print(f"{key}: {value}")
""" Exercício 1: Aprimorando a classe Lista : nossa classe Lista atende as principais operações que essa TAD nos oferece, mas que tal melhorarmos? Para isso, você deve adicionar os seguintes métodos: a. A operação clear nos permite remover todos os Nodes da lista; b. A operação __get_node_at nos permite acessar o Node em qualquer posição da lista. Após criada as operações anteriores, refatore os seguintes métodos para que utilizem a __get_node_at ante iterações: insert_at insert_last remove_last remove_at get_element_at """ """ 1 - a. clear(self) - Para este desafio existem 2 possibilidades de respostas a serem implementadas. A opção #1 só funciona, sem que ocorra vazamento de memória, graças ao garbage collector do python, porém, o mais indicado é a opção #2 , pois utilizam a própria estrutura para atribuir um novo comportamento. """ # # 1 # def clear(self): # self.head_value = None # self.__length = 0 # 2 def clear(self): while not self.is_empty(): self.remove_first() """ 1 - b. __get_node_at(self, position) - Para este desafio foi realizado a extração do trecho de código mais repetitivo, que estava sendo utilizado nos demais métodos. Vale salientar que nos casos que precisamos do anterior ao ultimo, precisamos fazer a operação len(self) - 2. """ def __get_node_at(self, position): value_to_be_returned = self.head_value if value_to_be_returned: while position > 0 and value_to_be_returned.next: value_to_be_returned = value_to_be_returned.next position -= 1 return value_to_be_returned """A refatoração nas demais funções ficaram da seguinte forma:""" def insert_at(self, value, position): if position < 1: return self.insert_first(value) if position >= len(self): return self.insert_last(value) current_value = self.__get_node_at(position - 1) next_value = Node(value) next_value.next = current_value.next current_value.next = next_value self.__length += 1 def insert_last(self, value): if self.is_empty(): return self.insert_first(value) new_last_value = Node(value) actual_last_value = self.__get_node_at(len(self) - 1) actual_last_value.next = new_last_value self.__length += 1 def remove_last(self): if len(self) <= 1: return self.remove_first() previous_to_be_removed = self.__get_node_at(len(self) - 2) value_to_be_removed = previous_to_be_removed.next previous_to_be_removed.next = None self.__length -= 1 return value_to_be_removed def remove_at(self, position): if position < 1: return self.remove_first() if position >= len(self): return self.remove_last() previous_to_be_removed = self.__get_node_at(position - 1) value_to_be_removed = previous_to_be_removed.next previous_to_be_removed.next = value_to_be_removed.next value_to_be_removed.next = None self.__length -= 1 return value_to_be_removed def get_element_at(self, position): value_returned = None value_to_be_returned = self.__get_node_at(position) if value_to_be_returned: value_returned = Node(value_to_be_returned.value) return value_returned
from exercicio1 import fizzbuzz def test_fizzbuzz_should_return_list_of_numbers(): assert fizzbuzz(2) == [1, 2] def test_fizzbuzz_divisible_by_three_should_be_fizz(): assert fizzbuzz(3)[-1] == "Fizz" def test_fizzbuzz_divisible_by_five_should_be_buzz(): assert fizzbuzz(5)[-1] == "Buzz" def test_fizzbuzz_divisible_by_five_and_three_should_be_fizzbuzz(): assert fizzbuzz(15)[-1] == "FizzBuzz"
# Exercício 1: Lembra do exercício da TV que já abstraímos? Hoje vamos # implementar ele, porém com algumas modificações. Veja o diagrama abaixo: # Atributos: # volume - será inicializado com um valor de 50 e só pode estar entre 0 e 99; # canal - será inicializado com um valor de 1 e só pode estar entre 1 e 99; # tamanho - será inicializado com o valor do parâmetro; # ligada - inicializado com o valor de False, pois está inicialmente desligado. # Todos os atributos devem ser privados. # Métodos: # aumentar_volume - aumenta o volume de 1 em 1 até o máximo de 99; # diminuir_volume - diminui o volume de 1 em 1 até o mínimo de 0; # modificar_canal - altera canal de acordo com parâmetro recebido e deve lançar # uma exceção ( ValueError ) caso o valor esteja fora dos limites; # ligar_desligar - alterna estado TV entre ligado e desligado ( True / False ). class TV: def __init__(self, tamanho): self.__volume = 50 self.__canal = 1 self.__tamanho = tamanho self.__ligada = False def aumentar_volume(self): if self.__volume <= 99: self.__volume += 1 def diminuir_volume(self): if self.__volume >= 0: self.__volume -= 1 def modificar_canal(self, canal): if canal <= 1 or canal >= 99: raise ValueError('Canal indisponível') self.__canal = canal return self.__canal def ligar_desligar(self): self.__ligada = not self.__ligada return self.__ligada televisor = TV(55) print(televisor.ligar_desligar())
# Exercício 5 Em um software gerenciador de servidores, precisamos verificar o # número de servidores que se comunicam. Os servidores estão representados como # um array bidimensional onde o valor 1 representa um computador e 0 a ausência # do mesmo. Dois servidores se comunicam se eles estão na mesma linha ou mesma # coluna. # servidores = [[1,0],[0,1]] # resultado: 0 # Linhas e colunas são diferentes. # servidores = [[1,0],[1,1]] # resultado: 3 # Todos os servidores se comunicam com ao menos um outro servidor. # servidores = [[1, 0, 0], # [1, 0, 0], # [0, 0, 1]] # resultado: 2 # O servidor de índice (2, 2) não possui nenhum outro na mesma linha e coluna. def count_servers(grid): rows, columns = len(grid), len(grid[0]) servers_in_rows = [0 for _ in range(rows)] servers_in_columns = [0 for _ in range(columns)] for i in range(rows): for j in range(columns): if grid[i][j] == 1: servers_in_rows[i] += 1 servers_in_columns[j] += 1 answer = 0 for i in range(rows): for j in range(columns): if grid[i][j] == 1 and ( servers_in_rows[i] > 1 or servers_in_columns[j] > 1 ): answer += 1 return answer print(count_servers([[1, 0, 0], [1, 0, 0], [0, 0, 1]]))
NAME = input("Insira seu nome: ") for letter in NAME: print(letter)
''' 8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order. You can download the sample data at http://www.py4e.com/code3/romeo.txt''' fname = input("Enter the file name : ") try : file = open(fname, 'r') except : print("File can not be found!! : ", fname) quit() words = [] full_text = [] for line in file : words = line.split() for i in range(len(words)) : if words[i] not in full_text : full_text.append(words[i]) else : continue full_text.sort() print(full_text)
import re fname = 'regex_sum_702244.txt' file = open(fname , 'r') print('Sum :', sum([int(number for number in re.findall('[0-9]+' , file.read()))])) numbers = list() total_num = list() for line in file : line = line.rstrip() numbers = re.findall('[0-9]+' , line) for num in numbers : try : x = int(num) except : print('Not a number') total_num.append(x) #print(total_num) print('Sum :' , sum(total_num))
def computepay(hrs, rate) : if (hrs <= 40) : pay = hrs * rate else : pay = (40 * rate) + ((hrs - 40) * (rate * 1.5)) return pay hours = input("Enter hours : ") rate_per_hour = input("Enter the Rate : ") try: hrs = float(hours) rate = float(rate_per_hour) except : print("Invalid input!!") quit() pay = computepay(hrs, rate) print("Pay :" , pay)
a=2 for a in range(1,4): print("praveen",a) for b in range(1,4): print("praveen",b)
# -*- coding: utf-8 -*- """ Created on Sun Oct 25 23:24:12 2020 @author: Yung """ import random class game: def __init__(self): #variable initialization self.choices = ["rock", "paper", "scissors"] #valid input/choices self.yes = ["yes", "y"] self.no = ["no", "n"] self.player_score = 0 self.computer_score = 0 # This functions prompts user for the choice and validates input # Input: none # Output: User's seleciton of rock, paper, or scissors def player_input_check(self): player_input = input("Rock, Paper, or Scissors? ").lower() #filter input to lowercase while player_input not in self.choices: #while input not valid print("That is not a valid input!") #yell at user player_input = input("Rock, Paper, or Scissors?").lower() #get input agin return player_input # This function receives player choice, selects random choice and scores the result # Input: player choice from player_input_check # Output: player score and computer score def who_won(self): p_choice = self.player_input_check() print("Your choice: ", p_choice.title()) #print out input computer_choice = random.choice(self.choices) print("Computer's choice: ", computer_choice.title()) #logic comparison if computer_choice == p_choice: #draw condition print("It's a draw!") elif computer_choice == "rock" and p_choice == "paper": print("You win!") self.player_score += 1 elif computer_choice == "rock" and p_choice == "scissors": print("Computer wins!") self.computer_score += 1 elif computer_choice == "paper" and p_choice == "scissors": print("You win!") self.player_score += 1 elif computer_choice == "paper" and p_choice == "rock": print("Computer wins!") self.computer_score += 1 elif computer_choice == "scissors" and p_choice == "paper": print("Computer wins!") self.computer_score += 1 elif computer_choice == "scissors" and p_choice == "rock": print("You win!") self.player_score += 1 return self.player_score, self.computer_score def play_again(self): again = input("Play Again? (Y/N) ").lower() print("\n") #white space for formatting while again not in (self.yes + self.no): #while input not valid print("That is not a valid input!") #yell at user again = input("Play Again? (Y/N) ").lower() if again in self.yes: return True else: return False
j=input() i=0 for a in range (len(j)): if(j[a].isdigit() or j[a].isalpha() or j[a]==' '): continue else: i+=1 print(i)
''' This program deletes a node in the linked list. @author: Asif Nashiry ''' from deleteNodeLinkedList import LinkedList import random # number of elements in the list numOfData = 15 aList = LinkedList() # create a list with random numbers for i in range(numOfData): data = random.randint(1, 30) aList.insertNode(data) print('List: ') aList.printList() print('\nNumber of elements: ', aList.numberOfNode()) target = int(input('\nEnter the data to be deleted: ')) # find the location of the node to be deleted targetLoc = aList.findLocTarget(target) if targetLoc is None: print('The element', target, 'does not appear in the list') else: aList.deleteNode(targetLoc) print('List after deleting: ') aList.printList() print('\nNumber of elements: ', aList.numberOfNode())
import sqlite3 import os import datetime class Db_sql(object): def __init__(self,form): self.form = form def db_select(self): # 获取提交的表单数据! # form = request.form # 提取名称、日期 food_name = self.form.get('food_name').strip() start_date = self.get('start_date').strip() stop_date = self.get('stop_date').strip() print(food_name, start_date, stop_date) # 如果相关项为空,则进行默认值配置! if food_name == '': pass if start_date == '': start_date = '1970-01-01' if stop_date == '': stop_date = str(datetime.datetime.now().date()) print(food_name, start_date, stop_date) path = os.path.join(os.getcwd(), 'ShuCai.db') if os.path.isfile(path): print(path) else: print("无文件") conn = sqlite3.connect(path) cur = conn.cursor() if food_name == '': cur.execute('select name, lowest, average, highest, date from shucai ' 'where date Between ? and ? ', (start_date, stop_date)) else: cur.execute('select name, lowest, average, highest, date from shucai ' 'where name=? and date Between ? and ? ', (food_name, start_date, stop_date)) datebase = cur.fetchall() cur.close() conn.close() print(datebase) return datebase
#!/usr/bin/env python3 import argparse import sys class ownParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n\n' % message) self.print_help() sys.exit(1) def magical_tree(height): for level in range(1,height+1): for spaces in range(1,height-level+1): print(" ", end = "") for balls in range(0, 2*(level-1)+1): print("*", end = "") print("") if __name__ == '__main__': exit_code = 0 parser = ownParser(description='Build a magical tree') parser.add_argument('-l', '--levels', nargs='?', type=int, default=[], required=True) args=parser.parse_args() magical_tree(args.__dict__["levels"])