text
stringlengths
37
1.41M
from admin_functions import * def manage_books_and_authors(): valid = 0 while(valid == 0): print('''Books and authors: what would you like to do: 1) Add Book 2) Delete Book 3) Edit Book 4) Add Author 5) Delete Author 6) Update Author Or Enter to go back to admin menu ''') choice = input() if choice == '': return if(choice.isdecimal() and int(choice) in range(0,7)): if choice == '1': add_book() elif choice == '2': delete_book() elif choice == '3': update_book() elif choice == '4': add_author(0) elif choice == '5': delete_author() elif choice == '6': update_author() else: print('Please enter a valid option: ',end='') def manage_publishers(): valid = 0 while(valid == 0): print('''Publishers: what would you like to do: 1) Add Publishers 2) Delete Publishers 3) Edit Publishers Or enter Enter to go back to admin menu ''') choice = input() if choice == '': return elif(choice.isdecimal() and int(choice) in range(0,4)): if choice == '1': add_publisher(0) elif choice == '2': delete_publisher() elif choice == '3': update_publisher() else: print('Please enter a valid option: ',end='') def manage_branches(): valid = 0 while(valid == 0): print('''Branches: what would you like to do: 1) Add Branch 2) Delete Branch 3) Edit Branch Or Enter to go back to admin menu ''') choice = input() if choice == '': return if(choice.isdecimal() and int(choice) in range(0,4)): if choice == '1': add_branch() elif choice == '2': delete_branch() elif choice == '3': update_branch() else: print('Please enter a valid option: ',end='') def manage_borrowers(): valid = 0 while(valid == 0): print('''Branches: what would you like to do: 1) Add Borrowers 2) Delete Borrowers 3) Edit Borrowers Or Enter to go back to admin menu ''') choice = input() if choice == '': return if(choice.isdecimal() and int(choice) in range(0,4)): if choice == '1': add_borrower() elif choice == '2': delete_borrower() elif choice == '3': update_borrower() else: print('Please enter a valid option: ',end='') def admin_menu(): valid = 0 while(valid == 0): print('''Hello Administrator, what would you like to do: 1) Manage Book and Authors 2) Manage Publishers 3) Manage Library Branches 4) Manage Borrowers 5) Override a Due Date for a Book Loan Or Enter to go back to main menu ''') choice = input() if choice == '': return if(choice.isdecimal() and int(choice) in range(0,6)): if choice == '1': manage_books_and_authors() elif choice == '2': manage_publishers() elif choice == '3': manage_branches() elif choice == '4': manage_borrowers() elif choice == '5': manage_due_date() else: print('Please enter a valid option: ',end='')
import unittest from quince.components import Deck, Card class TestDeck(unittest.TestCase): def test_constructor(self): """Takes a Card class and builds a deck of 40 Cards""" deck = Deck(Card) self.assertEqual(40, len(deck.cards())) # Assert that there are no duplicate cards in the deck deck_check = {"oro": [], "espada": [], "copa": [], "basto": []} for card in deck.cards(): val = card.value palo = card.suit if val in deck_check[palo]: self.fail("Duplicate card in deck") else: deck_check[palo].append(val) # And that each suit has cards 1-10 for palo in deck_check: for i in range(1, 11): if i not in deck_check[palo]: self.fail("Missing " + str(i) + " in " + palo) def test_cards(self): """Returns a copy of the deck""" deck = Deck(Card) cards = deck.cards() cards[0].value = 20 self.assertNotEqual(20, deck._cards[0].value) def test_deal(self): """Returns a new deck object and a hand List containing the cards that were dealt""" deck = Deck(Card) (deck2, hand) = deck.deal(4) self.assertEqual(36, len(deck2.cards())) self.assertEqual(4, len(hand)) for c in hand: self.assertTrue(c not in deck2._cards) def test_str(self): """String representation""" d = Deck(Card) s = str(d) self.assertTrue("40" in s) def test_repr(self): """String representation""" d = Deck(Card) d.deal(4) s = repr(d) self.assertTrue("36" in s) def test_generate_clone(self): """Builds a clone of an existing deck, if one is passed.""" d1 = Deck(Card) d1._cards = d1._cards[20:] # instantiate a clone d2 = Deck(Card, clone=d1) # check that the right cards got passed cards_in_d1 = [f"{x.value}-{x.suit}" for x in d1.cards()] cards_in_d2 = [f"{x.value}-{x.suit}" for x in d2.cards()] self.assertEqual(cards_in_d1, cards_in_d2) # check that it really is a clone d1._cards[0].value = 14 self.assertNotEqual(14, d2._cards[0].value)
""" The Card object represents a Card. Each card has a value and a suit. """ from os import path, getcwd from PIL import Image SETENTA_SCORING = [11.0, 4.0, 6.0, 8.0, 10.0, 14.0, 17.5, 1, 1, 1] class Card(object): """ The Card object represents a Card. Each card has a value and a suit. """ def __init__(self, value, suit): """Instatiates a Card object. Args: value (int) -- Number on the card suit (str) -- Card suit """ if value < 1 or value > 10: raise ValueError("Cards can only be between 1 and 10") self.value = value self.suit = suit # Values 8, 9, and 10 use the card images numbered 10, 11, 12 img_num = value if value < 8 else value + 2 self._image = f"quince/assets/cards/card_{suit}_{img_num}.png" self.points_setenta = SETENTA_SCORING[value - 1] def image(self): """Getter for the card's image""" img_path = path.join(getcwd(), self._image) return Image.open(img_path) def clone(self): """Clones a Card object""" return Card(self.value, self.suit) def __str__(self): return str((self.value, self.suit)) def __repr__(self): return str((self.value, self.suit)) def __hash__(self): hashable = f"{self.value}{self.suit}" return hash(hashable) def __eq__(self, other): return self.value == other.value and self.suit == other.suit
# 菜鸟教程 http://www.runoob.com/python/att-string-format.html # 不设置指定位置,按默认顺序 str1 = "{} {}".format("hello", "world") print(str1) # 设置指定位置 str2 = "{0} {1}".format("hello", "world") print(str2) # 设置指定位置 str3 = "{1} {0} {1}".format("hello", "world") print(str3)
def stack(): s=[] return(s) def push(s,data): s.append(data) def pop(s): data=s.pop() return(data) def peek(s): return(s[len(s)-1]) def isEmpty(s): return (s==[]) def size(s): return (len(s)) def balik(teks): a=stack() hasil ='' for i in range(len(teks)): push(a, teks[i]) for i in range (len(teks)): hasil=hasil+pop(a) return hasil print(balik('arek'))
#Crie um programa que leia uma FRASE qualquer #e diga se ela é um PALÍNDROMO, desconsiderando os espaços # Exemplos de PALÍNDROMOS # APOS A SOPA # A SACADA DA CASA # A TORRE DA DERROTA # O LOBO AMA O BOLO # ANOTARAM A DATA DA MARATONA frase = str(input('Digite uma frase: ')).strip().upper() palavras = frase.split() junto = ''.join(palavras) #inverso = '' #Com FOR '''for letra in range(len(junto)-1, -1, -1): inverso += junto[letra]''' #SEM FOR inverso = junto[::-1] print('O inverso de {} e {}'.format(junto, inverso)) if inverso == junto: print('Tem um palíndromo') else: print('Não forma um palíndromo')
from random import randint from time import sleep import emoji print('{:=^100}'.format("\033[1;31;m Play Jokempô \033[m" + emoji.emojize("\033[1;31;m :sunglasses: \033[m", use_aliases=True))) print("""Suas opções: [0] PEDRA [1] PAPEL [2] TESOURA """) lista = ['PEDRA', 'PAPEL', 'TESOURA'] computador = randint(0, 2) jogador = int(input('ESCOLHA UMA OPÇÃO:')) print('JO') sleep(1) print('KEN') sleep(1) print('PO!!!') sleep(1) print("-=" * 14) print('O computador escolheu: \033[1;31;m {} \033[m'.format(lista[computador])) print('O jogador escolheu: \033[1;31;m {} \033[m'.format(lista[jogador])) print("-=" * 14) if computador == 0: # computador jogou PEDRA if jogador == 0: print('EMPATE!') elif jogador == 1: print("VITÓRIA DO JOGADOR!") elif jogador == 2: print("VITÓRIA DO COMPUTADOR!") else: print("JOGADA INVÁLIDA!") elif computador == 1: # computador jogou PAPEL if jogador == 1: print('EMPATE!') elif jogador == 0: print("VITÓRIA DO COMPUTADOR!") elif jogador == 2: print("VITÓRIA DO JOGADOR!") else: print("JOGADA INVÁLIDA!") elif computador == 2: if jogador == 2: print('EMPATE!') elif jogador == 0: print("VITÓRIA DO JOGADOR!") elif jogador == 1: print("VITÓRIA DO COMPUTADOR!") else: print("JOGADA INVÁLIDA!")
sal_atual = float(input('Digite o salário atual: ')) sal_novo = sal_atual + (sal_atual * 15 / 100) print('O salário de R${:.2f} com 15% de aumento será de R${:.2f}'.format(sal_atual, sal_novo))
#Refaça o DESAFIO 009, mostrando a tabuada de um número #que o usuário escolher, só que agora utilizando um laço for. #r = 0 #n = int(input('Digite um número para ver sua tabuada: ')) #for c in range(1, 11): # r = n*c # print('{}x{}={}'.format(n, c, r)) #Usando apenas 3 linhas num = int(input('Digite um número para ver sua tabuada: ')) for i in range(1, 11): print('{} x {:2} = {}'.format(num, i, num*i))
import datetime import pafy from selenium import webdriver driver = webdriver.Chrome(r"C:\projects\Eclipse\chromedriver.exe") # using pafy to get duration of youtube video # return int - seconds of youtube video duration def get_duration(url): video = pafy.new(url) with open("result.txt", 'a', encoding='utf-8') as f: f.write("VideoId: " + str(video.videoid) + " Duration " + str(video.duration) + '\n') duration_list = str(video.duration).split(":") hours = int(duration_list[0]) minutes = int(duration_list[1]) seconds = int(duration_list[1]) final_time = seconds + (minutes * 60) + (hours * 60 * 60) return final_time # get all links and write them to file def get_links(): driver.get("https://atidcollege.co.il/digital/qa/ch06-part03-password.html") driver.switch_to.frame(driver.find_element_by_xpath("//iframe[@src='../menus/menu-software-testing.html']")) text_list = driver.find_elements_by_xpath("//li[@class='list-group-item']") for i in range(len(text_list)): try: link = text_list[i].find_element_by_tag_name('a').get_attribute("href") with open("links.txt", 'a', encoding='utf-8')as f: f.write(link + '\n') except: pass # use selenium to open page and locate youtube video link # return boolean - if is youtube or not , and link from youtube or the source link def get_youtube_link(link): driver.get(link) frames = driver.find_elements_by_tag_name('iframe') is_youtube = False for i in frames: if "youtube" in i.get_attribute("src"): link = i.get_attribute("src") link = link.split("/")[-1] is_youtube = True return is_youtube, link def main(): # open file with all links to open with open("links.txt", 'r') as links: final_duration_in_seconds = 0 for line in links: line = line.replace("\n", "") is_youtube_link = get_youtube_link(line) # pafy works for youtube only, if video storage in google drive we need to manual calculate if is_youtube_link[0]: final_duration_in_seconds += get_duration(is_youtube_link[1]) else: print("drive? " + line) # convert seconds to format "HH:MM:SS" duration = str(datetime.timedelta(seconds=final_duration_in_seconds)) print("duration of all youtube videos: " + duration) if __name__ == '__main__': main()
mdp = input("Entrez un mot de passe (min 8 caractères) : ") mdp_trop_court = "votre mot de passe est trop court." if(len(mdp)==0): print(mdp_trop_court) elif(len(mdp)<8 and not mdp.isdigit()): mdp_trop_court = mdp_trop_court.capitalize() print(mdp_trop_court) elif (mdp.isdigit()): print("Votre mot de passe ne contient que des nombres.") elif(mdp == "ilyaskorri"): print("Inscription terminée.")
import numpy as np import scipy.optimize as opt # para la funcion de gradiente from matplotlib import pyplot as plt # para dibujar las graficas from valsLoader import * from dataReader import save_csv # g(X*Ot) = h(x) def sigmoid(Z): return 1/(1+np.exp(-Z)) def dSigmoid(Z): return sigmoid(Z)*(1-sigmoid(Z)) def pesosAleatorios(L_in, L_out, rango): O = np.random.uniform(-rango, rango, (L_out, 1+L_in)) return O def cost(X, Y, O1, O2, reg): """devuelve un valor de coste""" a = -Y*(np.log(X)) b = (1-Y)*(np.log(1-X)) c = a - b d = (reg/(2*X.shape[0]))* ((O1[:,1:]**2).sum() + (O2[:,1:]**2).sum()) return ((c.sum())/X.shape[0]) + d def neuronalSuccessPercentage(results, Y): """determina el porcentaje de aciertos de la red neuronal comparando los resultados estimados con los resultados reales""" numAciertos = 0 for i in range(results.shape[0]): result = np.argmax(results[i]) if result == Y[i]: numAciertos += 1 return (numAciertos/(results.shape[0]))*100 def forPropagation(X1, O1, O2): """propaga la red neuronal a traves de sus dos capas""" m = X1.shape[0] a1 = np.hstack([np.ones([m, 1]), X1]) z2 = np.dot(a1, O1.T) a2 = np.hstack([np.ones([m, 1]), sigmoid(z2)]) z3 = np.dot(a2, O2.T) h = sigmoid(z3) return a1, z2, a2, z3, h def backPropAlgorithm(X, Y, O1, O2, num_etiquetas, reg): G1 = np.zeros(O1.shape) G2 = np.zeros(O2.shape) m = X.shape[0] a1, z2, a2, z3, h = forPropagation(X, O1, O2) for t in range(X.shape[0]): a1t = a1[t, :] # (1, 401) a2t = a2[t, :] # (1, 26) ht = h[t, :] # (1, 10) yt = Y[t] # (1, 10) d3t = ht - yt # (1, 10) d2t = np.dot(O2.T, d3t) * (a2t * (1 - a2t)) # (1, 26) G1 = G1 + np.dot(d2t[1:, np.newaxis], a1t[np.newaxis, :]) G2 = G2 + np.dot(d3t[:, np.newaxis], a2t[np.newaxis, :]) AuxO2 = O2 AuxO2[:, 0] = 0 G1 = G1/m G2 = G2/m + (reg/m)*AuxO2 return np.concatenate((np.ravel(G1), np.ravel(G2))) def backPropagation(params_rn, num_entradas, num_ocultas, num_etiquetas, X, Y, reg): O1 = np.reshape(params_rn[:num_ocultas*(num_entradas + 1)], (num_ocultas, (num_entradas+1))) O2 = np.reshape(params_rn[num_ocultas*(num_entradas+1):], (num_etiquetas, (num_ocultas+1))) c = cost(forPropagation(X, O1, O2)[4], Y, O1, O2, reg) gradient = backPropAlgorithm(X,Y, O1, O2, num_etiquetas, reg) return c, gradient def neuronalNetwork(X, Y, Xtest, Ytest, polyGrade): """aplica redes neuronales sobre un conjunto de datos, entrenando con una seccion de entrenamiento, y probando los resultados obtenidos (porcentaje de acierto) con una seccion de test""" poly = preprocessing.PolynomialFeatures(polyGrade) Xpoly = polynomize(X, polyGrade) # pone automaticamente columna de 1s Xnorm, mu, sigma = normalize(Xpoly[:, 1:]) # se pasa sin la columna de 1s (evitar division entre 0) XpolyTest = polynomize(Xtest, polyGrade) XnormTest = normalizeValues(XpolyTest[:, 1:], mu, sigma) m = Xnorm.shape[0] # numero de muestras de entrenamiento n = Xnorm.shape[1] # numero de variables x que influyen en el resultado y, mas la columna de 1s num_etiquetas = 2 l = 1 AuxY = np.zeros((m, num_etiquetas)) for i in range(m): AuxY[i][int(Y[i])] = 1 capaInter = 40 O1 = pesosAleatorios(Xnorm.shape[1], capaInter, 0.12) O2 = pesosAleatorios(capaInter, num_etiquetas, 0.12) thetaVec = np.append(O1, O2).reshape(-1) result = opt.minimize(fun = backPropagation, x0 = thetaVec, args = (n, capaInter, num_etiquetas, Xnorm, AuxY, l), method = 'TNC', jac = True, options = {'maxiter':70}) O1 = np.reshape(result.x[:capaInter*(n + 1)], (capaInter, (n+1))) O2 = np.reshape(result.x[capaInter*(n+1):], (num_etiquetas, (capaInter+1))) success = neuronalSuccessPercentage(forPropagation(XnormTest, O1, O2)[4], Ytest) print("Neuronal network success: " + str(success) + " %") return O1, O2, poly, success def bestColumns(X, Y, Xtest, Ytest): """devuelve la mejor combinacion de columnas de X (las que obtienen un mejor porcentaje de acierto), mostrando el porcentaje de acierto obtenido de cada combinacion""" mostSuccessfull = 0 bestRow = 0 bestColumn = 0 for x in range(0, 6): for y in range(0, 6): print("Row: " + str(x)) print("Column: " + str(y)) Xaux = np.vstack([X[:, x][np.newaxis], X[:, y][np.newaxis]]).T XtestAux = np.vstack([Xtest[:, x][np.newaxis], Xtest[:, y][np.newaxis]]).T O1, O2, poly, success = neuronalNetwork(Xaux, Y, XtestAux, Ytest, 3) if(success > mostSuccessfull): mostSuccessfull = success bestRow = x bestColumn = y return bestRow, bestColumn, mostSuccessfull def main(): X, Y, Xval, Yval, Xtest, Ytest = loadValues("steamReduced.csv") bestRow, bestColumn, mostSuccessfull = bestColumns(X, Y, Xtest, Ytest) # mejor combinacion de columnas (mejor porcentaje de acierto) print("Best Row: " + str(bestRow)) print("Best Column: " + str(bestColumn)) print("Most Successfull: " + str(mostSuccessfull)) # redes neuronales con todas las columnas O1, O2, poly, success = neuronalNetwork(X, Y, Xtest, Ytest, 3) save_csv("O1.csv", O1) save_csv("O2.csv", O2) #main()
"""2048 game hussein suleman 25 april 2014""" # random number generator import random # grid utility routines import util # grid value merging routines import push def add_block (grid): """add a random number to a random location on the grid""" # set distributon of number possibilities options = [2,2,2,2,2,4] # get random number chosen = options[random.randint(0,len(options)-1)] found = False while (not found): # get random location x = random.randint (0, 3) y = random.randint (0, 3) # check and insert number if (grid[x][y] == 0): grid[x][y] = chosen found = True def play (): """generate grid and play game interactively""" # create grid grid = [] util.create_grid (grid) # add 2 starting random numbers add_block (grid) add_block (grid) won_message = False while (True): util.print_grid (grid) key = input ("Enter a direction:\n") if (key in ['x', 'u', 'd', 'l', 'r']): # make a copy of the grid saved_grid = util.copy_grid (grid) if (key == 'x'): # quit the game return # manipulate the grid depending on input elif (key == 'u'): push.push_up (grid) elif (key == 'd'): push.push_down (grid) elif (key == 'r'): push.push_right (grid) elif (key == 'l'): push.push_left (grid) # check for a grid with no more gaps or legal moves if util.check_lost (grid): print ("Game Over!") return # check for a grid with the final number elif util.check_won (grid) and not won_message: print ("Won!") won_message = True # finally add a random block if the grid has changed if not util.grid_equal (saved_grid, grid): add_block (grid) # initialize the random number generator to a fixed sequence random.seed (12) # play the game play ()
import json def _dict_traverse(d, level, max_level, show_values, show_levels): if level > max_level: return "" accum = "" keys = d.keys() for k in keys: key_str = f'{" " * level}"{k}"' if isinstance(d[k], str): d_val = f'"{d[k]}"' elif isinstance(d[k], dict): d_val = '' elif isinstance(d[k], list): d_val = '[' else: d_val = str(d[k]) if len(d_val) > 32: d_val = d_val[:32] + '...' if not show_values and d_val != '[': d_val = "" level_str = f'({level})' if show_levels else '' accum += f'{key_str}: {d_val} {level_str}\n' if isinstance(d[k], dict): accum += _dict_traverse(d[k], level + 1, max_level, show_values, show_levels) elif isinstance(d[k], list): accum += _list_traverse(d[k], level + 1, max_level, show_values, show_levels) if isinstance(d[k], list): accum += f'\n{" " * level}]\n' return accum def _list_traverse(a, level, max_level, show_values, show_levels): if level > max_level: return "" accum = "" e_str = f'{" " * level}' for i, e in enumerate(a): if isinstance(e, str): e_val = f'"{e}"' elif isinstance(e, list): e_val = '' elif isinstance(e, dict): e_val = f'{{' else: e_val = str(e) if len(e_val) > 32: e_val = e_val[:32] + '...' if not show_values: e_val = "" else: if isinstance(e, dict): accum += f'{e_str}{e_val}\n' else: if i == 0: accum += e_str accum += f'{e_val}, ' if isinstance(e, dict): accum += _dict_traverse(e, level + 1, max_level, show_values, show_levels) elif isinstance(e, list): accum += _list_traverse(e, level + 1, max_level, show_values, show_levels) if isinstance(e, dict): accum += e_str + '\n' + e_str + '},\n' return accum def jsonkeys(s, max_level=0, show_values=True, show_levels=False): if max_level == 0: max_level = 99 j = json.loads(s) print("\n") print(_dict_traverse(j, 0, max_level, show_values, show_levels))
#[email protected] number=int(Input()) if (number>0): print('Positive') elif ('Number<0') print('Negative') elif: prin('Zero')
""" Exercise 3 Using the same CelestialBody class, create a factory method called make_earth. This method returns a CelestialBody object for planet Earth. Earth is 149,600,000 km from the Sun, has a diameter of 12,756.3 km, and has one moon. Expected Output The factory method should return a CelestialBody object. This object should be able to do the following things: print(my_planet.name) will return Earth print(my_planet.distance) will return 149600000 print(my_planet.diameter) will return 12756.3 print(my_planet.moons) will return 1 """ class CelestialBody: """Represents a celestial body""" def __init__(self, name, diameter, distance, moons): self.name = name self.diameter = diameter self.distance = distance self.moons = moons @classmethod def make_earth(cls): return CelestialBody("Earth", 12756.3, 149600000, 1) my_planet = CelestialBody.make_earth() print(my_planet.name) print(my_planet.diameter) print(my_planet.distance) print(my_planet.moons)
# Recursion Exercise 5 # Write a recursive function called get_max that takes a list of numbers as a parameter. # Return the largest number in the list. # Expected Output # If the function call is get_max([1, 2, 3, 4, 5]), then the function would return 5 # If the function call is get_max([11, 22, 3, 41, 15]), then the function would return 41 # Use the max function to return the larger of two numbers. def get_max(num_list): """Recursively returns the largest number from the list""" if len(num_list) == 1: return num_list[0] else: return max(num_list[0], get_max(num_list[1:])) def main(): print(get_max([1, 2, 3, 4, 5])) print(get_max([11, 22, 3, 41, 15])) if __name__ == "__main__": main()
#One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given TWO strings, write a function to check if THEY are ONE edit (or zero edits) away. #EXAMPLE #pale, ple -> true #pales, pale -> true #pale, bale -> true #pale, bae -> false #check if can REMOVE character #check if can ADD character #checK if can REPLACE character #check if strings are EQUAL def oneAway(string1, string2): matches = 0 #first check if strings are EQUAL if(string1==string2): return True else: length1 = len(string1) length2 = len(string2) length2_rem = length2-1 length2_add = length2+1 print(length2) print(length2_rem) if(length1 == length2): #possibly 1 character replaced #number of matching chars should equal the lengths-1 #for loop run through string1 #for loop run through string 2 for i in range(len(string1)): #print(string1[i]) #print(string2[i]) if(string1[i]==string2[i]): matches+= 1 #print(matches) if(matches == length2_rem): print("1 character replaced") return True elif length1 == length2_rem: #possibly 1 character can be added to string1 #possibly 1 character can be removed from string2 #test1: (appl, apple) #test2: (apple, appl) #still need to compare if most of the letters are matching #also the letters can be removed in ANY INDEX in the string #for loop iterate through 1st and 2nd and then if different, check if next elem in strin1 is equal to the one currently at string2 print("hi") elif length1 == length2_add: print("hi") #possibly 1 character can be removed from string1 #possibly 1 character can be removed from string2 #test3: (aaple, apple) elif: return False test1= "applf" test2= "apple" if(oneAway(test1, test2)): print("they ARE one edit away") else: print("they are NOT one edit away")
""" Given two arrays, write a function to compute their intersection. """ def intersect(nums1, nums2): d = {} for n in nums1: d[n] = d.get(n, 0) + 1 out = [] for n in nums2: if n in d and d[n] > 0: out.append(n) d[n] -= 1 return out
""" Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value. """ def findMaxAverage(nums, k): _sum = 0 for i in range(k): _sum += nums[i] _max = _sum / (k + 0.0) i = 0 j = i + k - 1 while j < len(nums) - 1: j += 1 _sum -= nums[i] _sum += nums[j] i += 1 m = _sum / (k + 0.0) if m > _max: _max = m return _max if __name__ == "__main__": import unittest class Test(unittest.TestCase): def test1(self): self.assertEqual(findMaxAverage([2, 4, -1, 10, 15], 1), 15) unittest.main()
class Node: def __init__(self, v=None, l=None, r=None): self.key = v self.lc = l self.rc = r def add(root, new_node): if root is None: root = new_node else: if new_node.key < root.key: if not root.lc: root.lc = new_node else: add(root.lc, new_node) else: if not root.rc: root.rc = new_node else: add(root.rc, new_node) def in_order(root): if root: in_order(root.lc) print(root.key) in_order(root.rc) a = Node(10) add(a, Node(8)) add(a, Node(2)) add(a, Node(23)) add(a, Node(54))
""" Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. """ def minimumTotal(triangle): if len(triangle) == 0: return 0 if len(triangle[0]) == 0: return 0 i = len(triangle) - 2 while i >= 0: for j in range(len(triangle[i])): triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]) i -= 1 return triangle[0][0] if __name__ == "__main__": import unittest class Test(unittest.TestCase): def test1(self): t = [ [2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ] self.assertEqual(minimumTotal(t), 11) unittest.main()
""" Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one """ def findDuplicate(nums): for i in range(len(nums)): if nums[abs(nums[i])] < 0: return abs(nums[i]) else: nums[abs(nums[i])] = nums[abs(nums[i])] * -1 return -1 if __name__ == "__main__": import unittest class Test(unittest.TestCase): def test1(self): self.assertEqual(findDuplicate([1, 1, 2, 3, 4]), 1) def test2(self): self.assertEqual(findDuplicate([4, 4, 4, 4, 4]), 4) def test3(self): self.assertEqual(findDuplicate([1,2,2]), 2) unittest.main()
# problem: https://www.hackerrank.com/challenges/funny-string t = int(input().strip()) out_string = "" for test in range(t): s = list(map(ord, list(input().strip()))) f = list(reversed(s)) for i in range(1, len(s)): if abs(s[i] - s[i - 1]) != abs(f[i] - f[i - 1]): out_string += "Not Funny\n" break else: out_string += "Funny\n" print(out_string)
""" Given an array where elements are sorted in ascending order, convert it to a height balanced BST. """ class TreeNode(object): def __init__(self, x, left=None, right=None): self.left = left self.right = right def sortedArraytoBST(nums): root = _sortedArraytoBST(nums, 0, len(nums) - 1, None) def _sortedArraytoBST(nums, left, right, root): if left < right: mid = (left + right) // 2 if not root: root = TreeNode(mid) return root
# Dijkstra's algorithm implemented for a graph represented using a dict of adjacent nodes # Dijkstra's algorithm is used to find the shortest path to any node from a single source class Graph: def __init__(self): self.g = dict() def add(self, s, e, w): self.add_aux(s, e, w) self.add_aux(e, s, w) def add_aux(self, s, e, w): if s not in self.g: self.g[s] = { e:w } else: self.g[s][e] = w def __repr__(self): out = "" for vertex, neighbors in self.g.items(): sub_out = "" for neighbor, weight in neighbors.items(): sub_out += "\tconnects to {} with weight {}\n".format(neighbor, weight) out += "vertex " + str(vertex) + "\n" + sub_out return out def build_spt_from(self, source): if source not in self.g: raise KeyError("source must be in graph") else: # initializing some variables used to keep track dist_val = dict() # ideally this would be a min-heap for k in self.g: dist_val[k] = dict() if k == source: dist_val[k]["dist"] = 0 else: dist_val[k]["dist"] = float('inf') dist_val[k]["path"] = [source] visited = [] min_node = source # find min dist while len(visited) != len(self.g.keys()): # find target min_dist = float('inf') for k, v in dist_val.items(): if k in visited: continue if v["dist"] < min_dist: min_node = k min_dist = v["dist"] if not min_node: continue visited.append(min_node) neighbors = self.g[min_node] for neighbor in neighbors: if neighbor in visited: continue cur_dist_val = dist_val[neighbor]["dist"] new_dist_val = dist_val[min_node]["dist"] + self.g[min_node][neighbor] if new_dist_val < cur_dist_val: dist_val[neighbor]["dist"] = new_dist_val dist_val[neighbor]["path"] = dist_val[min_node]["path"] + [neighbor] return dist_val def main(): import json g = Graph() g.add("A", "B", 7) g.add("B", "C", 10) g.add("B", "D", 15) g.add("C", "A", 9) g.add("A", "F", 14) g.add("C", "F", 2) g.add("C", "D", 11) g.add("D", "E", 6) g.add("E", "F", 9) print(g) spt = g.build_spt_from("A") print("Shortest distance from A to vertex") print("\tvertex\tdist\tpath") for k, v in spt.items(): if v["dist"] == float('inf'): print("\t{}\t{}".format(k, "no path found")) continue path = "" for vertex in v["path"][:-1]: path += str(vertex) + " -> " path += str(v["path"][-1]) print("\t{}\t{}\t{}".format(k, v["dist"], path)) if __name__ == "__main__": main()
# task: given an array with negative and positive numbers, find a subarray such that its sum is maximized # simple solution that does not keep track of the start and end indices def maximum_subarray_simple(lst): cur_max = 0 global_max = -float("inf") for val in lst: cur_max += val if cur_max <= 0: cur_max = 0 elif cur_max > global_max: global_max = cur_max return global_max # O(n) time complexity with O(1) space complexity # if the maximum sum is negative then return 0 since not picking any element # maximizes the sum def maximum_subarray(lst): cur_start = 0 max_start = 0 max_end = 0 global_max = -float('inf') cur_max = 0 for i, val in enumerate(lst): cur_max += val if cur_max > global_max: global_max = cur_max max_start = cur_start max_end = i if cur_max <= 0: cur_start = i + 1 cur_max = 0 if global_max < 0: return 0, None, None return global_max, max_start, max_end
""" Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. """ import unittest class TreeNode(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def add(root, val): if not root: return TreeNode(val) if val < root.val: root.left = add(root.left, val) return root elif root.val < val: root.right = add(root.right, val) return root def add_all(root, lst): for n in lst: add(root, n) # assumption: all values in the BST is unique def findTarget(root, k): d = dict() q = [root] while q: cur = q.pop(0) d[cur.val] = True if cur.left: q.append(cur.left) if cur.right: q.append(cur.right) for key in d: complement = k - key if complement != key and complement in d: return True return False class Test(unittest.TestCase): def test1(self): t1 = TreeNode(5) add_all(t1, [3, 6, 2, 4, 7]) self.assertEqual(findTarget(t1, 9), True) def test2(self): t1 = TreeNode(5) add_all(t1, [3, 6, 2, 4, 7]) self.assertEqual(findTarget(t1, 28), False) if __name__ == "__main__": unittest.main()
# task: given a binary tree, write a function to check if the given tree is a valid binary search tree class Node: def __init__(self, v=None, l=None, r=None): self.key = v self.lc = l self.rc = r def is_BST(tree): if not tree: return True if not tree.lc and not tree.rc: return True # single child case if not tree.lc or not tree.rc: if tree.lc: if tree.lc.key > tree.key: return False else: if tree.rc.key < tree.key: return False else: if tree.lc.key > tree.key or tree.rc.key < tree.key: return False return is_BST(tree.lc) and is_BST(tree.rc) A = Node(2, Node(1), Node(3)) B = Node(2, Node(3), Node(1)) C = Node(6, Node(5, Node(4, Node(3, Node(2, Node(1)))))) print(is_BST(A)) print(is_BST(B)) print(is_BST(C))
""" The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Now your job is to find the total Hamming distance between all pairs of the given numbers. """ def totalHammingDistance(nums): return sum(b.count('0') * b.count('1') for b in zip(*map('{:032b}'.format, nums))) if __name__ == "__main__": import unittest class Test(unittest.TestCase): def test1(self): self.assertEqual(totalHammingDistance([4, 14, 2]), 6) unittest.main()
# task: given a binary tree, swap all children class Node: def __init__(self, v, l=None, r=None): self.key = v self.lc = l self.rc = r def swap(tree): if not tree: return tree q = [tree] while q: cur_node = q.pop(0) cur_node.lc, cur_node.rc = cur_node.rc, cur_node.lc if cur_node.lc: q.append(cur_node.lc) if cur_node.rc: q.append(cur_node.rc) return tree A = Node(10, Node(23, Node(34), Node(45)), Node(32, Node(40), Node(50))) A = swap(A)
#task: given a pointer to some node that has a valid next node, delete itself from the linkedlist without # an access to previous nodes. # e.g) a -> b -> c -> d -> . # you are given a pointer to node 'c', but no other previous elements # turn the linked list into # a -> b -> d -> . class Node: def __init__(self, v=None, n=None): self.key = v self.next = n def delete_middle(node): if not node.next: raise Exception("faulty input") node.key = node.next.key node.next = node.next.next def print_ll(head): s = "" while head: s += str(head.key) + " -> " head = head.next return s + "." A = Node("A", Node("B", Node("C", Node("D")))) pointer = A.next.next print(print_ll(A)) delete_middle(pointer) print(print_ll(A))
#task: given two linked lists each of which represents a string. Return 0 if they are the same, # 1 if the first string is lexicographically greater than the second, -1 if the second is # lexicographically less than the second. class Node: def __init__(self, v=None, n=None): self.key = v self.next = n def compr(h1, h2): while h1 and h2: if h1.key != h2.key: return -1 if h1.key < h2.key else 1 h1 = h1.next h2 = h2.next if not h1 and not h2: return 0 return -1 if not h1 and h2 else 1 A = Node("h", Node("e", Node("l", Node("l", Node("o"))))) B = Node("h", Node("e", Node("l", Node("l", Node("j"))))) print(compr(A, B)) print(compr(A, A))
""" Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. You may assume the integer do not contain any leading zero, except the number 0 itself. The digits are stored such that the most significant digit is at the head of the list. """ def plusOne(digits): """ :type digits: List[int] :rtype: List[int] """ i = len(digits) - 1 while i >= 0: digit = digits[i] new_digit = digit + 1 if new_digit <= 9: digits[i] += 1 return digits else: digits[i] = new_digit % 10 i -= 1 return [1] + digits
""" Given a binary tree, return the inorder traversal of its nodes' values. """ class TreeNode(object): def __init__(self, x, left=None, right=None): self.val = x self.left = left self.right = right def inorderTraversal(root, iterative=True): lst = [] if not iterative: _recursiveInorderTraversal(root, lst) else: _iterInorderTraversal(root, lst) return lst def _recursiveInorderTraversal(root, lst): if root: _recursiveInorderTraversal(root.left, lst) lst.append(root.val) _recursiveInorderTraversal(root.right, lst) def _iterInorderTraversal(root, lst): if root: stack = [] cur = root while cur or stack: while cur: stack.append(cur) cur = cur.left cur = stack.pop() lst.append(cur.val) cur = cur.right
# task: given a list of N coins, their values, and the total mass S, Find the minimum number of coins the sum of which is S. def minimum_coins(coins, S): if not coins: return 0
""" Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] """ def generateMatrix(n): matrix = [[0 for i in range(n)] for j in range(n)] i = j = 0 n = 1 direction = [0, 1] while True: matrix[i][j] = n n += 1 new_i = i + direction[0] new_j = j + direction[1] if 0 <= new_i < len(matrix) and 0 <= new_j < len(matrix[0]) and matrix[new_i][new_j] == 0: i += direction[0] j += direction[1] else: next_found = False if j + 1 < len(matrix[0]) and matrix[i][j + 1] == 0: next_found = True direction = [0, 1] j += 1 elif i + 1 < len(matrix) and matrix[i + 1][j] == 0: next_found = True direction = [1, 0] i += 1 elif j - 1 >= 0 and matrix[i][j - 1] == 0: next_found = True direction = [0, -1] j -= 1 elif i - 1 >= 0 and matrix[i - 1][j] == 0: next_found = True direction = [-1, 0] i -= 1 if not next_found: return matrix
#task: given a sorted linked list, insert a new node so that the sorted order is retained class Node: def __init__(self, v=None, n=None): self.key = v self.next = n def insert(head, v): if not head: return Node(v) if not head.next: if v < head.key: return Node(v, head) else: head.next = Node(v) return head n = head while n.next and v > n.next.key: n = n.next new_node = Node(v, n.next) n.next = new_node return head def p(head): s = "" while head: s += str(head.key) + " -> " head = head.next return s + "." A = Node(1, Node(11, Node(13, Node(24, Node(29, Node(32, Node(35))))))) print(p(A)) A = insert(A, 15) print(p(A))
# Completed # Problem: https://leetcode.com/problems/reverse-integer/#/description def reverseAux(x, neg, acc=0): if x == 0: if neg: return acc * -1 else: return acc else: new_x = x // 10 cur_digit = x % 10 return reverseAux(new_x, neg, (acc * 10) + cur_digit) def reverse(x): """ :type x: int :rtype: int """ neg = False if x < 0: x = x * -1 neg = True return reverseAux(x, neg) n = int(input().strip()) print(reverse(n))
# task: given two string, determine if the strings are at most one edits from each other # 'edit' refers to a deletion, insertion or replacement def one_away(src, s): if abs(len(src) - len(s)) > 1: return False if len(src) == len(s): diff = False for i, j in zip(src, s): if i != j: if not diff: diff = True else: return False return True if len(src) < len(s): s, src = src, s j = 0 diff = False for i in range(len(s)): if s[i] != src[j]: if not diff: diff = True else: return False else: j += 1 return True A = "helloworld" B = "jelloworld" C = "bellomold" D = "jellowold" print(one_away(A, B)) print(one_away(B, C)) print(one_away(B, D))
# task: given a pointer to a node in a binary search tree, write an algorithm to return the node containing the # next largest element class Node: def __init__(self, key=None, left_child=None, right_child=None, parent=None): self.k = key self.lc = left_child self.rc = right_child self.p = parent def get_successor(node): if not node.p: n = node.rc while n.lc: n = n.lc return n no_children = not node.lc and not node.rc lc_of_parent = node == node.p.lc rc_of_parent = node == node.p.rc if node.lc or (no_children and lc_of_parent): return node.p if no_children and rc_of_parent: n = node.parent if not n.parent: return None return n.parent n = node.rc while n.lc: n = n.lc return n A = Node(5) B = Node(3) C = Node(7) A.lc = B B.p = A A.rc = C C.p = A print(get_successor(B).k)
""" Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. For example, Consider the following matrix: [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] Given target = 3, return true. """ def searchMatrix(matrix, target): if not matrix or not matrix[0]: return False left = 0 right = len(matrix) - 1 while left < right: mid = (left + right) // 2 if target >= matrix[mid][0] and target <= matrix[mid][-1]: break else: if target > matrix[mid][-1]: left = mid + 1 else: right = mid - 1 else: return False row = matrix[mid] left = 0 right = len(row) - 1 while left < right: mid = (left + right) // 2 if target == row[mid]: return True else: if target > row[mid]: left = mid + 1 else: right = mid - 1 return False if __name__ == "__main__": import unittest class Test(unittest.TestCase): def test1(self): grid = [[1,3,5,7],[10,11,16,20],[23,30,34,50]] self.assertTrue(searchMatrix(grid, 3)) unittest.main()
""" You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number. """ def nextGreaterElement(findNums, nums): d = dict() for i, n in enumerate(nums): d[n] = i out = [] for n in findNums: i = d[n] + 1 while i < len(nums): if nums[i] > n: out.append(nums[i]) break i += 1 else: out.append(-1) return out print(nextGreaterElement([4,1,2], [1, 3, 4, 2]))
""" Reverse a singly linked list """ import unittest class ListNode(object): def __init__(self, x, next=None): self.val = x self.next = next def create_LL(lst): if not lst: return None root = ListNode(lst[0]) cur = root for i in range(1, len(lst)): cur.next = ListNode(lst[i]) cur = cur.next return root def collapse_LL(root, lst=None): if lst is None: lst = [] if root: lst.append(root.val) collapse_LL(root.next, lst) return lst def reverseList(head): if not head: return None prev = None _next = head.next while _next: head.next = prev prev = head head = _next _next = head.next head.next = prev return head if __name__ == "__main__": import unittest class Test(unittest.TestCase): def test1(self): root = create_LL([4, 3, 6]) root = reverseList(root) self.assertEqual(collapse_LL(root), [6, 3, 4]) def test2(self): root = create_LL([]) root = reverseList(root) self.assertEqual(collapse_LL(root), []) def test3(self): root = create_LL([1, 0, 23, 11, 53, 10, 4, 7, 9]) root = reverseList(root) self.assertEqual(collapse_LL(root), [9, 7, 4, 10, 53, 11, 23, 0, 1]) unittest.main()
""" Given a positive integer num, write a function which returns True if num is a perfect square else False. """ def isPerfectSquare(num): if num <= 0: return False base = 1 increment = 3 while base < num: base += increment increment += 2 return base == num
""" Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). """ class TreeNode(object): def __init__(self, x, left=None, right=None): self.val = x self.left = left self.right = right def isSymmetric(root): if not root: return True return _isSymmetric(root.left, root.right) def _isSymmetric(left, right): if not left and not right: return True if not left and right: return False if left and not right: return False if left.val != right.val: return False else: inner = _isSymmetric(right.left, left.right) outer = _isSymmetric(left.left, right.right) return inner and outer if __name__ == "__main__": import unittest class Test(unittest.TestCase): def test1(self): t = TreeNode(1, TreeNode(2, TreeNode(3), TreeNode(4), ), TreeNode(2, TreeNode(4), TreeNode(3), ) ) self.assertTrue(isSymmetric(t)) def test2(self): t = TreeNode(1, TreeNode(2, None, TreeNode(3) ), TreeNode(2, None, TreeNode(3), ) ) self.assertFalse(isSymmetric(t)) def test3(self): t = TreeNode(1, TreeNode(2), TreeNode(3), ) self.assertFalse(isSymmetric(t)) unittest.main()
""" Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.) """ def maxAreaOfIsland(grid): visited = [[False for i in range(len(row))] for row in grid] max_size = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1 and not visited[i][j]: size = traverse(grid, i, j, visited) if size > max_size: max_size = size return max_size def traverse(grid, i, j, visited): if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]): return 0 if grid[i][j] == 0 or visited[i][j]: return 0 else: visited[i][j] = True return 1 + traverse(grid, i - 1, j, visited) + traverse(grid, i, j - 1, visited) + traverse(grid, i, j + 1, visited) + traverse(grid, i + 1, j, visited)
""" Unfinished, taken help from book solution """ import string import random def process_file(filename, skip_header): hist = {} fp = file(filename) if skip_header: skip_gutenberg_header(fp) for line in fp: process_line(line, hist) return hist def skip_gutenberg_header(fp): for line in fp: if line.startswith('*END*THE SMALL PRINT!'): break def process_line(line, hist): # replace hyphens with spaces before splitting line = line.replace('-', ' ') for word in line.split(): # remove punctuation and convert to lowercase word = word.strip(string.punctuation + string.whitespace) word = word.lower() # update the histogram hist[word] = hist.get(word, 0) + 1 def most_common(hist): t = [] for key, value in hist.items(): t.append((value, key)) t.sort() t.reverse() return t
# python3 from collections import namedtuple from typing import List from unittest import TestCase Loot = namedtuple('Loot', 'value weight') def get_optimal_value(cap: int, loots: List[Loot]) -> float: optimal = 0.0 loots = sorted(loots, key=lambda x: x.value / x.weight, reverse=True) while cap > 0 and loots: best, loots = loots[0], loots[1:] score = best.value / best.weight w = min(best.weight, cap) optimal += score * w cap -= w return optimal class Test(TestCase): def test_get_optimal_value(self): tests = [ {'cap': 50, 'loots': [Loot(60, 20), Loot(100, 50), Loot(120, 30)], 'expected': 180.0000}, {'cap': 10, 'loots': [Loot(500, 30)], 'expected': 166.6667}, ] for test in tests: expected, obtained = test['expected'], get_optimal_value(test['cap'], test['loots']) self.assertEqual('{:.4f}'.format(expected), '{:.4f}'.format(obtained)) if __name__ == '__main__': n, capacity = list(map(int, input().split())) data = [] for _ in range(n): value, weight = map(int, input().split()) data.append(Loot(value, weight)) opt_value = get_optimal_value(capacity, data) print('{:.4f}'.format(opt_value))
# python3 from collections import namedtuple from sys import stdin from typing import List from unittest import TestCase test = namedtuple('test', 'seq expected') def number_of_inversions(seq: List[int], buf: List[int], left: int, right: int) -> int: count = 0 if right - left <= 1: return count ave = (left + right) // 2 count += number_of_inversions(seq, buf, left, ave) count += number_of_inversions(seq, buf, ave, right) i, j = left, ave while i < ave and j < right: if seq[i] <= seq[j]: buf[i + j - ave] = seq[i] i += 1 continue buf[i + j - ave] = seq[j] j += 1 count += ave - i while i < ave: buf[i + j - ave] = seq[i] i += 1 while j < right: buf[i + j - ave] = seq[j] j += 1 seq[left:right] = buf[left:right] return count class Test(TestCase): def test_number_of_inversions(self): tests = [ # samples test([2, 3, 9, 2, 9], 2), # acceptance test([9, 8, 7, 3, 2, 1], 15), # additional test([1, 2, 3, 4, 5], 0), ] for i, t in enumerate(tests): self.assertEqual(t.expected, number_of_inversions(t.seq, [0] * len(t.seq), 0, len(t.seq)), msg='at {} position'.format(i)) if __name__ == '__main__': n, *a = list(map(int, stdin.read().split())) print(number_of_inversions(a, n * [0], 0, len(a)))
# python3 def naive_gcd(a: int, b: int) -> int: current_gcd = 1 for d in range(2, min(a, b) + 1): if a % d == 0 and b % d == 0: if d > current_gcd: current_gcd = d return current_gcd def fast_gcd(a: int, b: int) -> int: if b == 0: return a if a < b: return fast_gcd(a, b % a) return fast_gcd(b, a % b) if __name__ == '__main__': print(fast_gcd(*map(int, input().split())))
# python3 from sys import stdin from typing import List from unittest import TestCase def compute_min_refills(distance: int, tank: int, points: List[int]) -> int: points.insert(0, 0) if distance != points[-1]: points.append(distance) num_refills = current_refill = 0 destination = len(points) - 1 while current_refill < destination: last_refill = current_refill while current_refill < destination and points[current_refill + 1] - points[last_refill] <= tank: current_refill += 1 if last_refill is current_refill: return -1 if current_refill < destination: num_refills += 1 return num_refills class Test(TestCase): def test_compute_min_refills(self): tests = [ {'distance': 950, 'tank': 400, 'points': [200, 375, 550, 750], 'expected': 2}, {'distance': 10, 'tank': 3, 'points': [1, 2, 5, 9], 'expected': -1}, {'distance': 200, 'tank': 250, 'points': [100, 150], 'expected': 0}, ] for test in tests: expected, obtained = test['expected'], compute_min_refills(test['distance'], test['tank'], test['points']) self.assertEqual(expected, obtained) if __name__ == '__main__': d, m, _, *stops = map(int, stdin.read().split()) print(compute_min_refills(d, m, stops))
# python3 from sys import stdin from typing import List from unittest import TestCase def max_dot_product(profits: List[int], clicks: List[int]) -> int: profits = sorted(profits, reverse=True) clicks = sorted(clicks, reverse=True) res = 0 for i in range(len(profits)): res += profits[i] * clicks[i] return res class Test(TestCase): def test_max_dot_product(self): tests = [ {'profits': [23], 'clicks': [39], 'expected': 897}, {'profits': [1, 3, -5], 'clicks': [-2, 4, 1], 'expected': 23}, ] for test in tests: expected, obtained = test['expected'], max_dot_product(test['profits'], test['clicks']) self.assertEqual(expected, obtained) if __name__ == '__main__': data = list(map(int, stdin.read().split())) n = data[0] a = data[1:n + 1] b = data[n + 1:] print(max_dot_product(a, b))
# -*- coding: utf-8 -*- """ Created on Thu Nov 24 01:29:55 2016 @author: sergeys04 Program that prints the sum of the numbers in s """ s = '2.3456,98.12,654.23,1.21' string = '' total = 0 for x in s: if x != ',': string = string + x elif x == ',': total = total + float(string) string = '' else: if len(string) > 0: total = total + float(string) print (total)
#binary search def binary_search(array,value): left = 0 right = len(array) while left <= right: middle = (left+right) // 2 if value == array[middle]: return middle elif value > array[middle]: left = middle + 1 elif value < array[middle]: right = middle - 1 return -1 def selection_sort(array): for i in range(len(array)-1): position = i for j in range(i+1,len(array)): if array[i] > array[j]: temp = array[i] position = j array[i] = array[position] array[position] = temp def bubble_sort(array): n = len(array) for p in range(n-1, 0, -1): for i in rang(n-1): if array[i] > array[i+1]: array[i], array[i+1] = array[i+1], array[i]
import random import turtle turtle.shape('turtle') for i in range(100): turn = random.randint(-360, 360) forward_t = random.randint(30, 100) turtle.forward(forward_t) turtle.left(turn)
import string import os def system_drives(): """ Find the different drives located in the system Args: Does not take any arguments Returns: available_drives: A list of all available drives in the system """ # Runs a list through all uppercase alphabets and stores values which are drives available_drives = ['%s:' % d for d in string.ascii_uppercase if os.path.exists('%s:' % d)] print("The system is searching for your files...") return available_drives
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 21 12:51:35 2019 @author: owner """ list=[1,20,-1,0,1000] #EX1: for x in list: print(x) #EX2: print(sum(list)) #EX3: print(max(list)) #EX4: x= set(list) #EX5: print("Empty") if (len(list)==0) else print("Not Empty") #EX6: tuple=(1,2,3,"Hi", ["B","Y","E"]) for x in tuple: print(x) #EX7: num_set = set([0, 1, 2, 3, 4, 5]) for x in num_set: print(x) #EX8: s1={1,2,3,4,5,6} s2={2,4,6} print ( s1 & s2 ) #EX9: print({"green","blue","yellow"}) #EX10: print(6) #EX11: print({1:10, 2:20, 3:30, 4:40, 5:50, 6:60}) #EX12: print("e") print("llo,") print("orl") print(13) print("hello, world!") print("Jello, World!")
def begin(): print("装饰开始:瓜子板凳备好,坐等[生成]") def end(): print("装饰结束:瓜子嗑完了,板凳坐歪了,撤!") def wrapper_counter_generator(func): # 接受func的所有参数 def wrapper(*args, **kwargs): # 处理前 begin() # 执行处理 result = func(*args, **kwargs) # 处理后 end() # 返回处理结果 return result # 返回装饰的函数对象 return wrapper class DIGCounter: """ 装饰器-迭代器-生成器,一体化打包回家 """ def __init__(self, start, end): self.start = start self.end = end def __iter__(self): """ 迭代获取的当前元素 :rtype: object """ return self def __next__(self): """ 迭代获取的当前元素的下一个元素 :rtype: object :exception StopIteration """ if self.start > self.end: raise StopIteration current = self.start self.start += 1 return current @wrapper_counter_generator def counter_generator(self): """ 获取生成器 :rtype: generator """ while self.start <= self.end: yield self.start self.start += 1 def main(): """ 迭代器/生成器(iterator)是不可重复遍历的, 而可迭代对象(iterable)是可以重复遍历的, iter()内置方法只会返回不可重复遍历的迭代器 """ k_list = list(DIGCounter(1, 19)) even_list = [e for e in k_list if not e % 2 == 0] odd_list = [e for e in k_list if e % 2 == 0] print(even_list) print(odd_list) g_list = DIGCounter(1, 19).counter_generator() five_list = [e for e in g_list if e % 5 == 0] print(five_list) if __name__ == '__main__': main()
# -.- coding: latin-1 -.- from __future__ import print_function from math import sqrt ''' Amicable Numbers Problem 21 Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. ''' try: xrange # Python 2 except NameError: xrange = range # Python 3 def sum_of_divisors(n): total = 0 for i in xrange(1, int(sqrt(n) + 1)): if n % i == 0 and i != sqrt(n): total += i + n // i elif i == sqrt(n): total += i return total - n total = [i for i in range(1, 10000) if sum_of_divisors(sum_of_divisors(i)) == i and sum_of_divisors(i) != i] print(sum(total))
""" Problem Statement: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3,5,6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below N. """ from __future__ import print_function N = 10 N_limit = 101 while N < N_limit: # raw_input = input("请输入一个大于3的自然数:") # n = int(filter(str.isdigit(), raw_input)) n = N sum_ = 0 for e in range(3, n): if e % 3 == 0 or e % 5 == 0: sum_ += e print(sum_) N += 10
s=0 a=int(input("Введите число:")) while a!=0: s+=a a = int(input("Введите число:")) print(s)
# -*- coding:utf-8 -*- # @time : 2019-12-17 14:43 # @author : xulei # @project: Fluent_Python import math from array import array import itertools import numbers class Vector: typecode = 'd' def __init__(self, components): self._components = array(self.typecode, components) def __iter__(self): # 使Vector实例是可迭代的对象 return iter(self._components) def __abs__(self): # 计算绝对值 return math.sqrt(sum(x*x for x in self)) def __neg__(self): # 计算-v,构建一个新的Vector实例,把self的每个分量都取反 return Vector(-x for x in self) def __pos__(self): # 计算+v,构建一个新的Vector实例,传入self的每个分量 return Vector(self) def __add__(self, other): # pairs是生成器,(a, b)形式的元组,a来自self,b来自other。self和other长度不同,使用fillvalue填充那个较短的可迭代对象 try: pairs = itertools.zip_longest(self, other, fillvalue=0.0) # zip_longest可以处理任何可迭代对象 return Vector(a + b for a, b in pairs) # 计算pairs中各个元素的和 except TypeError: return NotImplemented def __radd__(self, other): return self + other def __str__(self): # 实现Vector实例执行print方法时,打印真实的数值元组 return str(tuple(self)) def __mul__(self, other): if isinstance(other, numbers.Real): return Vector(n * other for n in self) else: return NotImplemented # 让Python尝试在other操作数上调用__rmul__方法 def __rmul__(self, other): return self * other # 委托给__mul__方法 def __matmul__(self, other): try: return sum(a * b for a, b in zip(self, other)) except TypeError: return NotImplemented def __rmatmul__(self, other): return self @ other if __name__ == '__main__': v1 = Vector([1.0, 2.0, 3.0]) print(14 * v1) print(v1 * True) from fractions import Fraction print(v1 * Fraction(1, 3)) ''' (14.0, 28.0, 42.0) (1.0, 2.0, 3.0) (0.3333333333333333, 0.6666666666666666, 1.0) ''' from numpy import matrix print(matrix([1, 2, 3]) @ matrix([[1], [2], [3]])) # 矩阵乘法 ''' [[14]] ''' print(Vector([1, 2, 3]) @ Vector([1, 1, 1])) ''' 6.0 '''
from typing import List class Solution: def largestRectangleArea(self, heights: List[int]) -> int: stack = [-1] ans = 0 heights.append(0) for i in range(len(heights)): while stack[-1] >= 0 and heights[stack[-1]] > heights[i]: x = stack.pop() start = stack[-1] + 1 ans = max(ans , heights[x]*(i-start)) stack.append(i) return ans s = Solution() print(s.largestRectangleArea([2,1,2]))
from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] s = [root] res = [] while s: t = s[-1] if t.left: s.append(t.left) t.left = None else: res.append(t.val) s.pop() if t.right: s.append(t.right) return res def other(self, root: TreeNode) -> List[int]: if not root: return [] res = [] cur = root while cur: if cur.left: x = t = cur.left while t.right and t.right != cur: t = t.right if t.right == cur: res.append(cur.val) cur = cur.right else: t.right = cur cur = x else: res.append(cur.val) cur = cur.right return res
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def rob(self, root: TreeNode) -> int: cache = {} def done(node: TreeNode, flag: bool): if node is None: return 0 if cache.get((node,flag)) is not None: return cache[(node,flag)] temp = done(node.left, True) + done(node.right, True) if flag: temp = max(node.val+done(node.left,False)+done(node.right,False),temp) cache[(node,flag)] = temp return temp return done(root,True) def other(self, root: TreeNode) -> int: def done(node: TreeNode): if node is None: return [0,0] l = done(node.left) r = done(node.right) return [node.val+l[1]+r[1],max(l[0],l[1])+max([r[0],r[1]])] res = done(root) return max(res[0],res[1])
from typing import List class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ iIndex = [] jIndex = [] for i in range(len(matrix)): for j in range(len(matrix[i])): if matrix[i][j] == 0: iIndex.append(i) jIndex.append(j) for i in range(len(matrix)): for j in range(len(matrix[i])): if i in iIndex or j in jIndex: matrix[i][j] = 0 def other(self, matrix: List[List[int]]) -> None: lx = len(matrix) ly = len(matrix[0]) flag = False for i in range(len(matrix)): for j in range(len(matrix[i])): if matrix[i][j] == 0: if i == 0: flag = True else: matrix[i][0] = 0 matrix[0][j] = 0 for i in range(1,lx): for j in range(1,ly): if not matrix[i][0] or not matrix[0][j]: matrix[i][j] = 0 if matrix[0][0] == 0: for i in range(1,lx): matrix[i][0] = 0 if flag: for i in range(0,ly): matrix[0][i] = 0 s = Solution() a = [[0,1,2,0], [3,4,5,2], [1,3,1,5]] s.other(a) print(a)
"""The n queens puzzle.""" import sys class NQueens: """Generate all valid solutions for the n queens puzzle""" def __init__(self, size): # Store the puzzle (problem) size and the number of valid solutions self.size = size self.solutions = 0 self.solve() def solve(self): """Solve the n queens puzzle and print the number of solutions""" positions = [-1] * self.size self.put_queen(positions, 0) print("Found", self.solutions, "solutions.") def put_queen(self, positions, target_row): """ Try to place a queen on target_row by checking all N possible cases. If a valid place is found the function calls itself trying to place a queen on the next row until all N queens are placed on the NxN board. """ # Base (stop) case - all N rows are occupied if target_row == self.size: # self.show_full_board(positions) # self.show_short_board(positions) self.solutions += 1 else: # For all N columns positions try to place a queen for column in range(self.size): # Reject all invalid positions if self.check_place(positions, target_row, column): positions[target_row] = column self.put_queen(positions, target_row + 1) def check_place(self, positions, ocuppied_rows, column): """ Check if a given position is under attack from any of the previously placed queens (check column and diagonal positions) """ for i in range(ocuppied_rows): if (positions[i] == column or positions[i] - i == column - ocuppied_rows or positions[i] + i == column + ocuppied_rows): return False return True def show_full_board(self, positions): """Show the full NxN board""" for row in range(self.size): line = "" for column in range(self.size): if positions[row] == column: line += "Q " else: line += ". " print(line) print("\n") def show_short_board(self, positions): """ Show the queens positions on the board in compressed form, each number represent the occupied column position in the corresponding row. """ line = "" for i in range(self.size): line += str(positions[i]) + " " print(line) def main(size): """Initialize and solve the n queens puzzle""" NQueens(size) if __name__ == "__main__": if len(sys.argv) <= 1: print("Usage: python3 nqueens.py <chessboardSize>") sys.exit(-1) main(int(sys.argv[1]))
def calc_angle(h, m): hour_step_angle = 30 # reference for measuring tha angles is the "12" hour minute_angle = m * 6 hour_angle = (h % 12) * hour_step_angle + (m / 60) * hour_step_angle angle = abs(minute_angle - hour_angle) return angle if angle <= 180 else 360 - angle print(calc_angle(3, 30)) # 75 print(calc_angle(12, 30)) # 165 print(calc_angle(2, 20)) # 50 print(calc_angle(6, 30)) # 15 print(calc_angle(10, 16)) # 148
# Given an array containing only positive integers, # return if you can pick two integers from the array which cuts the array # into three pieces such that the sum of elements in all pieces is equal. # Example 1: # # Input: array = [2, 4, 5, 3, 3, 9, 2, 2, 2] # # Output: true # # Explanation: choosing the number 5 and 9 results in three pieces [2, 4], [3, 3] and [2, 2, 2]. Sum = 6. # # Example 2: # # Input: array =[1, 1, 1, 1], # # Output: false class Solution(object): def can_pick(self, arr): leftIndex = 1 rightIndex = len(arr) - 1 while leftIndex < rightIndex + 2: leftSum = sum(arr[0: leftIndex]) rightSum = sum(arr[rightIndex:len(arr)]) centerSum = sum(arr[leftIndex + 1: rightIndex - 1]) if leftSum > rightSum: rightIndex -= 1 else: if rightSum > leftSum: leftIndex += 1 else: if centerSum == leftSum: print( "If we extract indexes " + str(leftIndex) + " and " + str( rightIndex) + " we get 3 'equal' intervals") return True else: leftIndex += 1 return False print(Solution().can_pick([2, 4, 5, 3, 3, 9, 2, 2, 2])) # True print(Solution().can_pick([1, 2, 3, 4, 5])) # False
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 27 12:03:42 2021 @author: quantum """ import nltk import re from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords paragraph='''Coronavirus disease (COVID-19) is an infectious disease caused by a newly discovered coronavirus. Most people infected with the COVID-19 virus will experience mild to moderate respiratory illness and recover without requiring special treatment. Older people, and those with underlying medical problems like cardiovascular disease, diabetes, chronic respiratory disease, and cancer are more likely to develop serious illness. The best way to prevent and slow down transmission is to be well informed about the COVID-19 virus, the disease it causes and how it spreads. Protect yourself and others from infection by washing your hands or using an alcohol based rub frequently and not touching your face. The COVID-19 virus spreads primarily through droplets of saliva or discharge from the nose when an infected person coughs or sneezes, so it’s important that you also practice respiratory etiquette (for example, by coughing into a flexed elbow). ''' #Lemmatization lem=WordNetLemmatizer() #sentences sentence=nltk.sent_tokenize(paragraph) corpus=[] for i in range(len(sentence)): clean_data=re.sub('[^a-zA-z]', ' ',sentence[i]) clean_data=clean_data.lower() clean_data=clean_data.split() clean_data=[lem.lemmatize(word) for word in clean_data if word not in set(stopwords.words('english'))] clean_data=' '.join(clean_data) corpus.append(clean_data) from sklearn.feature_extraction.text import TfidfVectorizer tfid=TfidfVectorizer() features=tfid.fit_transform(corpus).toarray()
import sys import time from board import Board from priorityQueue import priority_queue from board import Spot as heuristics class BFS: def __init__(self, start): self.start = start self.visited = [] self.nodes_visited = 0 self.space = 0 def search(self): queue = [(self.start, [])] while queue: self.space = max(self.space, len(queue)) (state, path) = queue.pop(0) self.nodes_visited += 1 for move, board in state.successors(): if board in self.visited: continue else: self.visited += [board] if board.is_goal(): yield path + [move] else: queue.append((board, path + [move])) class AStar: def __init__(self, start, heuristic): self.start = start self.heuristic = heuristic self.visited = [] self.nodes_visited = 0 self.space = 0 def search(self): pq = priority_queue(self.heuristic) pq.put((self.start, [])) while not pq.empty(): self.space = max(self.space, len(pq)) state, path = pq.get() self.nodes_visited += 1 if state.is_goal(): yield path for move, board in state.successors(): if board in self.visited: continue else: self.visited += [board] pq.put((board, path + [move])) def main(): start_board = Board.board_from_file(sys.argv[1]) method = sys.argv[2] heuristic = heuristics.manhattan_distance start = time.time() if method == 'bfs': seeker = BFS(start_board) try: path = next(seeker.search()) except StopIteration: path = None elif method == 'astar': seeker = AStar(start_board, heuristic) try: path = next(seeker.search()) except StopIteration: path = None else: print('Invalid...') return end = time.time() print("-" * 30) print('Graph Search Method: ', sys.argv[2] if len(sys.argv) > 2 else '') print('Input File:', sys.argv[1]) print('Moves:') if path: for step in path: print(step[0], '-->', step[1]) else: print("No solution found!") print('Time: {0:.4f} seconds'.format(end - start)) print('Nodes Visited:', seeker.nodes_visited) print('Space: {} nodes'.format(seeker.space)) if hasattr(seeker, 'visited'): print('Visited Size:', len(seeker.visited)) print("-" * 30) if __name__ == '__main__': main()
# Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. # # Note: # # The solution set must not contain duplicate triplets. # # Example: # # # Given array nums = [-1, 0, 1, 2, -1, -4], # # A solution set is: # [ # [-1, 0, 1], # [-1, -1, 2] # ] # # class Solution: def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ #Brute Force #一种Solution,先排序,然后设置三个index i j k,i对nums做一次循环,每次循环中j和k一个在头一个在尾,往中间靠拢,有重复元素就跳过 resultList = [] nums.sort() if len(nums) < 3: return resultList for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue j = i + 1 k = len(nums) - 1 while j < k: tripleSum = nums[i] + nums[j] + nums[k] if tripleSum < 0: j += 1 elif tripleSum > 0: k -= 1 else: resultList.append([nums[i], nums[j], nums[k]]) j += 1 k -= 1 while j < k and nums[j] == nums[j - 1]: j += 1 while j < k and nums[k] == nums[k + 1]: k -= 1 return resultList
# Given a 32-bit signed integer, reverse digits of an integer. # # Example 1: # # # Input: 123 # Output: 321 # # # Example 2: # # # Input: -123 # Output: -321 # # # Example 3: # # # Input: 120 # Output: 21 # # # Note: # Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. # class Solution: def reverse(self, x): """ :type x: int :rtype: int """ s = str(x) if s[0] == '-': reverse = s[0] + s[-1:-len(s):-1] else: reverse = s[-1:-len(s) - 1:-1] if int(reverse) > 2147483647 or int(reverse) < -2147483648: return 0 return int(reverse)
# Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. # # Note: For the purpose of this problem, we define empty string as valid palindrome. # # Example 1: # # # Input: "A man, a plan, a canal: Panama" # Output: true # # # Example 2: # # # Input: "race a car" # Output: false # # class Solution: def isPalindrome(self, s): """ :type s: str :rtype: bool """ if len(s) == 0: return True result = re.subn('[^0-9A-Za-z]', '', s)[0].lower() reverse = result[-1:-len(result) - 1:-1] return result == reverse
# -*- coding:utf-8 -*- # Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. # # Example: # # # Input: 38 # Output: 2 # Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. #   Since 2 has only one digit, return it. # # # Follow up: # Could you do it without any loop/recursion in O(1) runtime? # class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ #想了一下全是循环的方法,看了solution,除了0以外,其他数各位的和是1-9循环,所以addDigits(n) = addDigits(n - 9) (n > 9),所以只要把任何数转化成9以内的数即可 return 1 + (num - 1) % 9 if num > 0 else 0
# -*- coding:utf-8 -*- # Reverse bits of a given 32 bits unsigned integer. # # Example: # # # Input: 43261596 # Output: 964176192 # Explanation: 43261596 represented in binary as 00000010100101000001111010011100, #   return 964176192 represented in binary as 00111001011110000010100101000000. # # # Follow up: # If this function is called many times, how would you optimize it? # class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): #自己写的,速度还不错,就是逻辑有点啰嗦,先转换成字符串,再转换成整数,有没有更好的方法? ''' n = '%032d' % (int(bin(n)[2:])) return int(str(n)[::-1], base = 2) ''' result = 0 if n == 0: return result for _ in range(32): result <<= 1 if (n & 1) == 1: result += 1 n >>= 1 return result
# # Given an integer, write a function to determine if it is a power of three. # # # Follow up: # Could you do it without using any loop / recursion? # # # Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases. class Solution: def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ #approach 1,循环判断 #approach 2,转换为三进制,然后判断是否只包含一个1,Java可以用Integer.toString(5, 3) = '12',但是python没有相关的方法 #approach 3,用数学公式,n = 3^i, i = log3(n) = logb(n) / logb(3),当n是3的幂次时,i一定为整数,所以用i % 1 == 0来判断是否为整数 ''' epsilon = 0.000000000001 return (math.log(n) / math.log(3) + epsilon) % 1 <= 2 * epsilon if n >= 1 else False ''' #approach 4,在一些会产生整数溢出的语言当中,正整数的最大值为2147483647,那么3的幂次的最大值为1162261467,所以如果n > 0且1162261467 % n == 0的话,n为3的幂次 return n > 0 and 1162261467 % n == 0 #approach 4其实可以用来计算任何质数的幂次,合数不行
# filename : var.py i=5 print i i = i+1 print i s = '''this is a multi-line string this is the second line''' print s print \ i s = 'this is a string. \ this continues the string' print s s = 'this is a string \ this continues the string' print s print "this is the first sentence. \ this is the second sentence." print 'this is the first line \n this is the second lind' print '\\1' print r'\1' i=5 print 'Value is ', i print 'I repeat, the value is ',i length = 5 breadth = 2 area = length * breadth print 'Area is', area print 'Perimeter is ', 2 * (length + breadth)
import sqlite3 import time class Ürün(): def __init__(self,urun,adet,marka,fiyat): self.urun = urun self.adet = adet self.marka = marka self.fiyat = fiyat def __str__(self): return "Ürün: {}\nAdet: {}\nMarka: {}\nFiyat: {} Tl\n".format(self.urun,self.adet,self.marka,self.fiyat) class Market(): def __init__(self): self.baglantiolustur() def baglantiolustur(self): self.baglanti = sqlite3.connect("supermarket.db") self.cursor = self.baglanti.cursor() komut = "Create Table If not exists supermarket(Ürün TEXT,Adet INT,Marka TEXT,Fiyat FLOAT)" self.baglanti.execute(komut) self.baglanti.commit() def baglantikes(self): self.baglanti.close() def urunlerigoster(self): komut = "Select * From supermarket" self.cursor.execute(komut) urunler = self.cursor.fetchall() if len(urunler) == 0: print("Süpermarkette ürün bulunmuyor.") else: for i in urunler: urun = Ürün(i[0],i[1],i[2],i[3]) print(urun) def urunekle(self): komut = "Insert into supermarket Values(?,?,?,?)" self.cursor.execute(komut,(Ürün.urun,Ürün.adet,Ürün.marka,Ürün.fiyat)) self.baglanti.commit() def urunsil(self): komut = "Delete From supermarket Where Ürün = ?" self.cursor.execute(komut,(Ürün,)) self.baglanti.commit() def adetazalt(self,urun,miktar): komut = "Select Adet From supermarket Where Ürün = ?" self.cursor.execute(komut,(Ürün,)) urunadeti = self.cursor.fetchall() for i in urunadeti: for j in i: if j <= 0: print("Stokta bu üründen kalmadı.") else: yeniadet = j - miktar komut2 = "Update supermarket set Adet = ? Where Ürün = ?" self.cursor.execute(komut2,(yeniadet,Ürün,)) self.baglanti.commit() def adetekle(self,urun,miktar): komut = "Select Adet From supermarket Where Ürün = ?" self.cursor.execute(komut,(Ürün,)) urunadeti = self.cursor.fetchall() for i in urunadeti: for j in i: yeniadet = j + miktar komut2 = "Update supermarket set Adet = ? Where Ürün = ?" self.cursor.execute(komut2,(yeniadet,Ürün,)) self.baglanti.commit() supermarket = Market() print(""" ----------------------- Süpermarket Uygulaması ----------------------- 1.Ürünleri gör 2.Ürün ekle 3.Ürün sil 4.Satış yap 5.Stok ekle q-Çıkış ----------------------- """) while True: x = input("İşlem giriniz:") if x == "q": print("Çıkış yapılıyor...") time.sleep(1) print("Hoşçakalın") supermarket.baglantiyikes() break elif x == "1": supermarket.urunlerigoster() elif x == "2": urun = input("Ürünün adını girin:") adet = int(input("Ürünün adetini girin:")) marka = input("Ürünün markasını girin:") fiyat = float(input("Ürünün fiyatını girin:")) yeniurun = Ürün(urun,adet,marka,fiyat) print("Ürün ekleniyor...") time.sleep(1) supermarket.urunekle(yeniurun) print("Ürün eklendi") elif x == "3": urun = input("Silmek istediğiniz ürünü girin:") rly = input("Emin misiniz? (E/H): ") if rly == "E": print("Ürün siliniyor...") time.sleep(1) supermarket.urunsil(urun) print("Ürün silindi") elif x == "4": urun = input("Hangi ürünü sattınız?:") adet = int(input("Kaç adet sattınız?:")) print("Satış bilgileri giriliyor....") time.sleep(1) supermarket.adetazalt(urun,adet) print("Bilgiler başarıyla güncellendi") elif x == "5": urun = input("Hangi ürüne stok ekleyeceksiniz?:") adet = int(input("Kaç adet ekleyeceksiniz?:")) print("Stok bilgileri giriliyor...") time.sleep(1) supermarket.adetekle(urun,adet) print("Bilgiler başarıyla güncellendi") else: print("Hatalı işlem")
""" fibonacci serisi yeni bir sayıyı önceki iki sayının toplamı şeklinde oluşturulur. 1,1,2,3,5,8,13,21,34..... """ a = 1 b = 1 fibonacci = [a, b] for i in range(10): a , b = b, a + b print("a:", a,"b", b) fibonacci.append(b) print(fibonacci)
import math class Vector(list): def length(self): return math.sqrt(sum(i**2 for i in self)) def dot(self, vec): return sum([i * j for (i, j) in zip(self, vec)]) def euclidDist(self, vec): return math.sqrt(sum([(i-j)**2 for (i, j) in zip(self, vec)])) def manhattanDist(self, vec): return sum([abs(i - j) for (i, j) in zip(self, vec)]) def mean(self): return sum(self)/len(self) def covariance(self, vec): self_mean = self.mean() vec_mean = vec.mean() return Vector([(x - self_mean) * (y - vec_mean) for (x,y) in zip(self, vec)]).mean() def stdDev(self): # Algorithm taken from _The Art of Computer Programming_ # vol. 2 _Seminumerical Algorithms_ 2e. p. 232 m = self[0] mOld = m s = 0 for x in range(1, len(self)): m = m + (self[x] - m) / (x + 1) s = s + (self[x] - mOld) * (self[x] - m) mOld = m length = len(self) return math.sqrt(s/length) def pearsonCorrelation(self, vec): return self.covariance(vec)/(self.stdDev() * vec.stdDev()) def largest(self): mx = self[0] for x in self: if x > mx: mx = x return mx def smallest(self): mn = self[0] for x in self: if x < mn: mn = x return mn def median(self): sorted = self[:] sorted.sort() return sorted[len(self)//2]
import random print( '''Hey there! Welcome to CERO. To play the game, type '?p' or 'play'. To know about the rules, type '?h' or 'help'. ''' ) cards = [ "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "b10", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "o1", "o2", "o3", "o4", "o5", "o6", "o7", "o8", "o9", "o10", "i1", "i2", "i3", "i4", "i5", "i6", "i7", "i8", "i9", "i10", "Uno", "Dos", "Tres", "Cuatro", "Cinco" ] def game_help(): print( '''Here I have 55 cards. 50 of them are of 5 different colors; Black, Cyan, Red, Orange, Indigo. The other 5 are called Uno, Dos, Tres, Cuatro, Cinco. This game can be played by more than one number of players. You'll give me a number more than 20 to deal with. Now a player will turn the 'Wheel of luck'. If in those numbers you have 3 or more colors with even numbers, you'll get 2 points. If you get Uno, you'll get 1 points, for Dos, 2 and so on. The player with most points will win. If they are still tied, then there would be a toss. ''' ) def point_counter(player): point = 0 black = 0 cyan = 0 red = 0 orange = 0 indigo = 0 for item in player: if item == "Uno": point += 1 elif item == "Dos": point += 2 elif item == "Tres": point += 3 elif item == "Cuatro": point += 4 elif item == "Cinco": point += 5 elif str(item).startswith('b'): black += 1 elif str(item).startswith('c'): cyan += 1 elif str(item).startswith('r'): red += 1 elif str(item).startswith('o'): orange += 1 elif str(item).startswith('i'): indigo += 1 if black % 2 == 0: point += 2 if cyan % 2 == 0: point += 2 if red % 2 == 0: point += 2 if orange % 2 == 0: point += 2 if indigo % 2 == 0: point += 2 return point def result(players, players_points): max_points = 0 for count in range(0, len(players)): print(f"Player {count + 1}'s cards: {players[count]}.") print(f"Player {count + 1}'s points: {players_points[count]}.") print() if players_points[count] > max_points: max_points = players_points[count] winners = [] for count in range(0, len(players)): if players_points[count] == max_points: winners.append(count) print(f"Thus, the winner is: Player {random.choice(winners) + 1}!") def game_play(): global card_count player_count = 0 integer_check_players = False while integer_check_players is not True: try: player_count = int(input("Please enter the number of players: ")) print() if player_count > 1: integer_check_players = True else: print("Please enter a number larger than 1.") print() integer_check_players = False except: print("Please enter an integer.") print() integer_check_players = False integer_check_cards = False while integer_check_cards is not True: try: card_count = int(input("Please enter the number of cards: ")) print() if card_count > 20: integer_check_cards = True else: print("Please enter a number larger than 20.") print() integer_check_cards = False except: print("Please enter an integer.") print() integer_check_cards = False players = [] players_points = [] for count in range(0, player_count): player = random.sample(cards, card_count) players.append(player) point = point_counter(player) players_points.append(point) print(f"Player {count + 1}'s 'Wheel of luck' has rolled!") print() reply_result = input("Wanna see the results? Reply with 'yes' or '?y' to get surprised: ") print() if reply_result == "yes" or reply_result == "?y": result(players, players_points) else: print("Well, I wanna show them as I've already calculated them!") print() result(players, players_points) check = False while check is not True: init_input = input("Please type here: ") print() if init_input == "?h" or init_input == "help": check = True game_help() reply = input("Wanna play right now? Reply with 'yes' or '?y' to play: ") print() if reply == "yes" or reply == "?y": game_play() elif init_input == "?p" or init_input == "play": check = True game_play() else: check = False print("Please enter a valid input: ") print() print("Thanks for visiting, see you around!")
import pandas as pd import matplotlib.pyplot as plt def generate_histogram(column, title, range, labels): plt.figure(figsize=(12, 8)) x = df[df[column].notnull()][column] bins = int(range[1] - range[0]) plt.hist(x, bins, facecolor='green', alpha=0.75, range=range) plt.title(title) plt.xlabel(labels[0]) plt.ylabel(labels[1]) plt.savefig("graphs/histograms/" + column + "_histogram.png") path = "C:\\Users\\janikp\\AppData\\Local\\Programs\\Python\\Python37-32\\Projekt 2\\input\\winemag-data_first150k_id.csv" df = pd.read_csv(path) columns = ["points", "price"] titles = ["Points\nThe number of points WineEnthusiast rated the wine on a scale of 1-100 ", "Price\nThe cost for a bottle of the wine"] labels = [["Points", "Counts"], ["Price", "Counts"]] generate_histogram(columns[0], titles[0], (80, 100), labels[0]) mu = df[columns[1]].mean() generate_histogram(columns[1], titles[1], (0, mu + 50), labels[1])
def fayyaz(itemList): itemList[0] = "Pulaoo" for i in itemList: print("Buying "+i) myItems = ["Briyani","Anday wala burger","Nihari","Lassi"] print(myItems) fayyaz(myItems[:]) print(myItems)
def myfunction(x): return x * 3 def doubler(f): def g(z): return z + f(6) return g myfunc = doubler(myfunction) print(myfunc) print(myfunc(2))
marks = 39 if marks >= 40 and marks < 50: print("D") elif marks >= 50 and marks <60: print("C") elif marks >= 60 and marks <70: print("B") elif marks >= 70 and marks < 80: print("A") elif marks >= 80: print("A+") else: print("Failed")
players = ['charles', 'martina', 'michael', 'florence', 'eli',"1", "2","3","4"] print(players) for p in players[::2]: print(p.title())
stu1 = {'name':'Qasim', 'email':'[email protected]', 'age':20, 23:"hello", True:"working", 2.5:"new", 4:True} print(stu1) print(stu1['name']) stu1['name'] = 'Inzamam' print(stu1['name'])
# # 재귀 함수 # def factorial(n): # if n == 0: # return 1 # else: # return n*factorial(n-1) # print("1! : {}".format(factorial(1))) # print("2! : {}".format(factorial(2))) # print("3! : {}".format(factorial(3))) # print("4! : {}".format(factorial(4))) # print("5! : {}".format(factorial(5))) # print("10! : {}".format(format(factorial(10),',d'))) import time dictionary = { 1:1, 2:1, } def fibonacci(n): if n in dictionary: return dictionary[n] else: output = fibonacci(n-1) + fibonacci(n - 2) dictionary[n] = output return output start = time.time() print("fibonnaci(35) ", fibonacci(35)) print("실행시간 : ",time.time()-start,"sec")
#! /usr/bin/python from PIL import Image import sys def get_main_color(file): img = Image.open(file) colors = img.getcolors(256*1024) #put a higher value if there are many colors in your image max_occurence, most_present = 0, 0 try: for c in colors: if c[0] > max_occurence: (max_occurence, most_present) = c return most_present except TypeError: #Too many colors in the image return (0, 0, 0) main_color = get_main_color('screen.png') print(main_color) if main_color != (0, 0, 0): print('Aw,snap') sys.exit(1)
#!/usr/bin/python3 '''Advent of Code 2018 Day 24 solution''' import re import math import copy from typing import Tuple, TextIO, List, Callable class Unit: # pylint: disable=too-many-instance-attributes '''Represents a unit group''' count = 0 hp = 0 attack = 0 attacktype = '' initiative = 0 army = '' immune: List[str] = [] weak: List[str] = [] armycount = 0 def effectivepower(self) -> int: '''Returns effective attack power of a unit group''' return self.attack * self.count def __str__(self) -> str: '''Cast to str''' return "Group %d contains %d units" % (self.armycount, self.count) Units = List[Unit] def targetsort(units: Units, u: int) -> Callable[[int], Tuple[int, int, int]]: '''Return curried sort order function for targets''' return(lambda t: (calculatedamage(units[u], units[t]), units[t].effectivepower(), units[t].initiative)) def calculatedamage(unit: Unit, target: Unit) -> int: '''Camculate damage that unit would do to target''' if unit.attacktype in target.immune: return 0 if unit.attacktype in target.weak: return unit.count * unit.attack * 2 return unit.count * unit.attack def calculateattacks(units: Units) -> List[Tuple[int, int]]: '''Perform the attack selection stage of a fight''' unitlist = list(range(0, len(units))) unitlist.sort(key=lambda x: (units[x].effectivepower(), units[x].initiative), reverse=True) chosen: List[int] = [] results = [] for unit in unitlist: if units[unit].count == 0: continue targets = [t for t in list(range(0, len(units))) if (units[t].army != units[unit].army and t not in chosen and units[t].count != 0)] targets.sort(key=targetsort(units, unit), reverse=True) if targets and calculatedamage(units[unit], units[targets[0]]) > 0: chosen.append(targets[0]) if calculatedamage(units[unit], units[targets[0]]) >= units[targets[0]].hp: # We've attacked the group but only add it to the list if we actually capable of # killing some units. This is needed for stalemate detection in part 2. results.append((unit, targets[0])) return results def runattacks(attacks: List[Tuple[int, int]], units: Units) -> None: '''Run the previously selected attacks''' attacks.sort(key=lambda x: units[x[0]].initiative, reverse=True) for attack in attacks: if units[attack[0]].count == 0: continue hp = units[attack[1]].hp * units[attack[1]].count damage = calculatedamage(units[attack[0]], units[attack[1]]) remaining = math.ceil((hp - damage) / units[attack[1]].hp) if remaining < 0: remaining = 0 units[attack[1]].count = remaining def readinputdata(f: TextIO) -> Units: '''Load input data''' units = [] m1 = re.compile((r'^(\d+) units each with (\d+) hit points (\([^)]+\))? ?' r'with an attack that does (\d+) ([^ ]+) damage at initiative (\d+)$')) m2 = re.compile(r'^([A-Za-z ]+):$') m3 = re.compile(r'^\((((immune)|(weak)) to ([a-z, ]+); )?(((immune)|(weak)) to ([a-z, ]+)\))?$') army = '' armycount = 0 # This is the unit number within the army group - used only for debugging. for line in f: result = m2.match(line) if result is not None: army = result.group(1) armycount = 1 continue result = m1.match(line) if result is not None: weak: List[str] = [] immune: List[str] = [] if result.group(3) is not None: defence = m3.match(result.group(3)) if defence is not None: if defence.group(2) is not None and defence.group(2) == 'immune': immune = defence.group(5).split(', ') if defence.group(7) is not None and defence.group(7) == 'immune': immune = defence.group(10).split(', ') if defence.group(2) is not None and defence.group(2) == 'weak': weak = defence.group(5).split(', ') if defence.group(7) is not None and defence.group(7) == 'weak': weak = defence.group(10).split(', ') unit = Unit() unit.count = int(result.group(1)) unit.hp = int(result.group(2)) unit.attack = int(result.group(4)) unit.attacktype = result.group(5) unit.initiative = int(result.group(6)) unit.army = army unit.immune = immune unit.weak = weak unit.armycount = armycount armycount += 1 units.append(unit) return units def runfight(inputs: Units) -> Tuple[str, int]: '''Run a series of fights''' while True: attacks = calculateattacks(inputs) if not attacks: return('Stalemate', 0) runattacks(attacks, inputs) if not [u for u in inputs if u.army == 'Immune System' and u.count > 0]: return ('Infection', sum([u.count for u in inputs if u.army == 'Infection' and u.count > 0])) if not [u for u in inputs if u.army == 'Infection' and u.count > 0]: return ('Immune', sum([u.count for u in inputs if u.army == 'Immune System' and u.count > 0])) def runpart1(inputs: Units) -> int: '''Solve part 1''' inputcopy = copy.deepcopy(inputs) return runfight(inputcopy)[1] def runpart2(inputs: Units) -> int: '''Solve part 2''' boost = 1 while True: inputcopy = copy.deepcopy(inputs) for u in [u for u in inputcopy if u.army == 'Immune System']: u.attack += boost result = runfight(inputcopy) if result[0] == 'Immune': return result[1] boost += 1 def run() -> Tuple[int, int]: '''Main''' with open('inputs/day24.txt', 'r') as f: inputs = readinputdata(f) return(runpart1(inputs), runpart2(inputs)) if __name__ == '__main__': print(run())
#!/usr/bin/python3 '''Advent of Code 2018 Day 4 solution''' from typing import Tuple, List, DefaultDict, TextIO import re import datetime import operator from collections import defaultdict InputData = List[Tuple[datetime.datetime, str]] def runsolution(values: InputData) -> Tuple[int, int]: '''Run solution - both parts drop out of the same loop''' # Current guard on shift guard = 0 # When the guard went to sleep (Initialise using dt object to keep the type checker happy) sleepsat = datetime.datetime(1, 1, 1) # For each guard, a dict of minutes in which they were asleep and how often guardsleeptimes: DefaultDict[int, DefaultDict[int, int]] = defaultdict(lambda: defaultdict(int)) # Total amount of time each guard spent asleep guardsleeptotals: DefaultDict[int, int] = defaultdict(int) m = re.compile(r'Guard #(\d+) begins shift') # Loop through each input line... for v in values: # Changing of the Guard z = m.match(v[1]) if z is not None: guard = int(z.group(1)) # Note if a guard fell asleep elif v[1] == 'falls asleep': sleepsat = v[0] # If a guard wakes up... elif v[1] == 'wakes up': # ...record how long they were asleep... guardsleeptotals[guard] += int((v[0] - sleepsat) / datetime.timedelta(minutes=1)) # ...and increment the counter for each minute slot in which they were asleep t = sleepsat while t < v[0]: guardsleeptimes[guard][t.minute] += 1 t += datetime.timedelta(minutes=1) # The most slept guard is the one with the maximum value in the guardsleeptotals dict. mostsleptguard = max(guardsleeptotals.items(), key=operator.itemgetter(1))[0] # And now get the most slept minute of that guard. mostsleptminute = max(guardsleeptimes[mostsleptguard].items(), key=operator.itemgetter(1))[0] # Now solve part 2, using the same output. mg = 0 part2 = 0 # Loop through each guard... for g in guardsleeptimes: # ...finding the minute they slept most in... mx = max(guardsleeptimes[g].items(), key=operator.itemgetter(1))[0] # ...and if that beats the previous record (tracked in mg), update the record and put the # answer to part 2 (minute times guard number) into part2. if guardsleeptimes[g][mx] > mg: mg = guardsleeptimes[g][mx] part2 = g * mx return(mostsleptguard * mostsleptminute, part2) def readinputdata(f: TextIO) -> InputData: '''Read input data from the given file handle into inputs''' m = re.compile(r'\[(1518-\d\d-\d\d \d\d:\d\d)\] (.*)') inputs: InputData = [] for line in f.readlines(): z = m.match(line) if z is not None: dt = datetime.datetime.strptime(z.group(1), '%Y-%m-%d %H:%M') inputs.append((dt, z.group(2))) # Sort the input data chronologically inputs.sort(key=lambda x: x[0]) return inputs def run() -> Tuple[int, int]: '''Main''' # Read input data with open('inputs/day04.txt', 'r') as f: inputs = readinputdata(f) # Solve the problem return runsolution(inputs) if __name__ == '__main__': print(run())
#!/usr/bin/python3 '''Sequence finder code''' from typing import List, Optional, Tuple def checksequence(numbers: List[int]) -> Optional[Tuple[int, int]]: '''Check to see if a sequence has started repeating. Simple check - does not actually verify contents of loop''' if len([n for n in numbers if n == numbers[-1]]) >= 3: indices = [i for i, n in enumerate(numbers) if n == numbers[-1]][-3:] sequence1 = numbers[indices[0]:indices[1]] sequence2 = numbers[indices[1]:indices[2]] if sequence1 == sequence2: return (indices[1], indices[2]) return None def predict(numbers: List[int], target: int) -> int: '''Predict what a repeating sequence will be at a target index''' result = checksequence(numbers) if not result: raise Exception('Asked to predict with no sequence detected') (start, end) = result sequence = numbers[start:end] offset = (target - start - 1) % len(sequence) return sequence[offset] def predictincrementing(numbers: List[int], target: int) -> int: '''Predict what a repeating incrementing sequence will be at a target index''' result = checksequence(numbers) if not result: raise Exception('Asked to predict with no sequence detected') (start, end) = result sequence = numbers[start:end] preamble = sum(numbers[:start]) cycles = (target - start) offset = (target - start) % len(sequence) return preamble + ((cycles+2) * sum(sequence)) + sum(sequence[:offset])
# Enter your code here. Read input from STDIN. Print output to STDOUT def do(word): odd_letters = "" even_letters = "" for i in range(len(word)): if i%2==0: even_letters = even_letters+word[i] elif i%2==1: odd_letters = odd_letters+word[i] return "{} {}".format(even_letters,odd_letters) if __name__ == "__main__" : num = int(input()) for x in range(num): word = input() print(do(word))
x = -2 y = -1111 if x < 0 and y < 0: print('mindkettő negatív') if x < 0 or y < 0: print('van köztük negatív') if not x <= 0: print('x pozitív')
szám = 1 while szám <= 10: if szám % 2 == 0: print(szám) szám = szám + 1 print("vége")
import os #declarar variables valor1,valor2,valor3,valor4=0,0,0,0 #INPUT valor1=int(os.sys.argv[1]) valor2=int(os.sys.argv[2]) valor3=int(os.sys.argv[3]) valor4=int(os.sys.argv[4]) #PROCESSING total =int(valor1 + valor2 + valor3 + valor4) #OUTPUT print ( " ############################################# " ) print ( " # SASTERIA EL BUEN VESTIR " ) print ( " ############################################# " ) print ( " #Camisa: " , valor1) print ( " #Saco: " , valor2) print ( " #Corbata: " , valor3) print ( " #Chaleco: " , valor4) #condicional multiple #si la compra es mayor a 200 soles mostrarle al comprador que ha ganado una cena romantica #si la compra esta entre 100 y 200 soles mostrarle al comprador que ha ganado una camisa #si la compra es menor a 100 soles decirle que no ha ganado nada if(total>200): print("usted ha ganado una cena romantica") if(total>=100 and total<200): print("usted a ganado una camisa") if(total<100): print("usted no ha ganadado nada") #fin_if
import os #BOLETA DE VENTA DE ELECTRODOMESTICOS #DECLARAR VARIABLES empresa,cliente,radio,costo_radio,tv,costo_tv = "","",0,0.0,0,0.0 #INPUT empresa=os.sys.argv[1] cliente=os.sys.argv[2] radio=int(os.sys.argv[3]) costo_radio=float(os.sys.argv[4]) tv=int(os.sys.argv[5]) costo_tv=float(os.sys.argv[6]) #PROCESSING total_costo_radio=(radio* costo_radio) total_costo_tv=(tv*costo_tv) total_venta=(round(total_costo_radio+total_costo_tv,2)) #VERIFICADOR total_venta_verificador = (total_venta >= 200) total_costo_radio_verificado=(total_costo_radio>=950) print(" ") #OUTPUT print("#####################" + " " + empresa +" ######################") print(" calle Pedro Ruiz") print("R.U.C: 23639275843 " ) print("cliente " + cliente + " caja: 234 " + " cajero: PANFILO " ) print("################BOLETA DE VENTA#####################") print(" ") print("electrodomestico " + " cantidad " + " precio " + " total") print("radio " + " " + str(radio) + " " + str(costo_radio) + " " + str(total_costo_radio)) print("tv " + str(tv) + " " + str(costo_tv) + " " + str(total_costo_tv)) print("monto total:......................................s/" + str(total_venta)) print("_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _") print("Donde todo es más barato! ") #CONDICIONAL SIMPLE #SI EL TOTAL DE VENTA ES MAYOR O IGUAL A 200 ENTONCES GANAS UNOS AUDIFONOS if(total_venta_verificador == True): print("FELICIDADES HA GANADO UNOS AUDIFONOS") #SI EL MONTO EN COMPRA DE LOS RADIOS ES MENOR O IGUAL A 450 ENTONCES TIENE UN DESCUENTO DEL 20% EN EL PROXIMO RADIO if(total_costo_radio_verificado == True): print("USTED HA GANADO UN DESCUENTO DEL 20% EN EL SIGUIENTE ELECTRODOMÉSTICO") #SI EL MONTO DE COMPRA GENERAL ES MAYOR A 1200 SOLES ENTONCES, GANA UN DESCUENTO DEL 50% if (total_venta<1200 and total_venta>450): print("GANASTE UN DESCUENTO DEL 10% EN TU COMPRA TOTAL") #fin_if
import os #VOLUMEN DE UNA ESFERA #DECLARAR VARIABLES pi,radio,angulo=0.0,0,0 #INPUT pi=float(os.sys.argv[1]) radio=int(os.sys.argv[2]) angulo=int(os.sys.argv[3]) #PROCESSING volumen =(round(4/3*pi*(radio**3)*angulo,2)) #VERIFICADOR volumen_correcto=(volumen>=50) #OUTPUT print("pi es: " + str(pi)) print("El radio es: " + str(radio)) print("El angulo es:" + str(angulo)) print("El volumen de la esfera es: " + str(volumen)) #CONDICION SIMPLE # si el volumen hallado es mayor o igual a 50 entonces el volumen es correcto if (volumen_correcto == True): print("EL VOLUMEN ES CORRECTO") #fin_if