text
stringlengths
37
1.41M
#Persegi Panjang print("==== Menghitung Luas dari Persegi Panjang ====") Panjang = float(input("Panjang dari persegi panjang:")) Lebar = float(input("Lebar dari persegi panjang:")) Luas = (Panjang*Lebar) print("Luas dari persegi panjang sama dengan",Luas,"satuan") #Lingkaran print("==== Menghitung Luas dari Lingkaran ====") phi = 3.14 Jari_jari = float(input("Jari-jari lingkaran :")) Luas = Jari_jari*Jari_jari*phi print("Luas dari lingkaran sama dengan",Luas,"satuan") #Kubus print("===== Menghitung dari Luas Kubus =====") Sisi = float(input("Sisi Kubus :")) Luas_permukaan = 6*Sisi*Sisi print("Luas dari permukaan kubus sama dengan",Luas_permukaan,"satuan") #Konversi Suhu Celcius ke Fahrenheit print("===== Menghitung Konversi Suhu dari Celcius ke Fahrenheit") Celcius = float(input("Suhu dalam celcius :")) Konversi_suhu = (((9/5)*Celcius)+32) print("Konversi suhu dari celcius ke fahrenheit sama dengan",Konversi_suhu,"°F") #Konversi Suhu Reamur ke Kelvin print("Menghitung konversi suhu dari Reamur ke Kelvin") Reamur = float(input("Suhu dalam reamur :")) Konversi_suhu = ((5/4)*Reamur)+273 print("Konversi suhu dari reamur ke kelvin sama dengan",Konversi_suhu,"K")
# Find out how many players total and if teams will be randomized or not # For our Yes or No question later. Returns True (y) or False (n) def randomYN(): check = str(input("\nDo you want teams to be assigned at random? (Y/N): ")).lower().strip() try: if check[0] == 'y': return True elif check[0] == 'n': return False else: print('Invalid Input') except: print("Please enter valid inputs") return randomYN() # Greets players and asks if teams will be randomized. def greet_user(): print("This is the bracket maker.") def get_player_count(): while True: try: player_count = int(input("\nHow many players are there?: ")) if player_count > 4 and player_count % 2 == 0: return player_count break else: print("Enter an even number larger than 4! ") except: print("Enter an even number larger than 4! ") def get_player_names(player_count,player_names): """Get the names of contestants""" x = 0 while x < player_count: name = input("What is player " + str(x +1) + "'s name?: ") while True: if len(name) < 1: name = input("Try entering your name again: ") else: break player_names.append(name) x += 1
import RPi.GPIO as GPIO def button_callback(channel): # define function print("Button was pressed!") # print message GPIO.setwarnings(False) # not using warnings GPIO.setmode(GPIO.BOARD) #Use physical pin numbering GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #set pin10 as input, set initial value as low GPIO.add_event_detect(10, GPIO.RISING, callback=button_callback) #set event on pin10 rising edge message = input("enter to exit\n\n") # Runs until you press enter GPIO.cleanup()
import random # In this code, we attempt to use genetic algorithms to find variables in an equation. Please note that this code isnt in its # final form and steps such as optimizing parameters or introducing reinforcement learning can help achieve perfect results. # Here given a value P i.e. pressure, we try to find V, n and T that lie in a boundary. This code using the ideal gas equation # but can be changed for any equation. To get better values of the variables, run the code again and again. def generate_pop(size,V_boundary,n_boundary,T_boundary): V_lower_boundary, V_upper_boundary = V_boundary n_lower_boundary, n_upper_boundary = n_boundary T_lower_boundary, T_upper_boundary = T_boundary population = [] for i in range(size): individual = { 'V' : random.uniform(V_lower_boundary,V_upper_boundary), 'n': random.uniform(n_lower_boundary,n_upper_boundary), 'T': random.uniform(T_lower_boundary, T_upper_boundary) } population.append(individual) return population def function(individual,P): """Calculates the function we want to find the max of/ also counts as fitness""" V = individual['V'] n = individual['n'] T = individual['T'] P_calc = (n*T*8.8314)/V fitness = P- P_calc return fitness def sort_pop_by_fitness(population): sorted_pop = sorted(population , key= function) return sorted_pop def crossover(sorted_pop): individual_a = sorted_pop[-1] individual_b = sorted_pop[-2] Va = individual_a['V'] na = individual_a['n'] Ta = individual_a['T'] Vb = individual_b['x'] nb = individual_b['y'] Tb = individual_b['T'] return {'V': (Va + Vb) / 3, 'n': (na + nb) / 3, 'T': (Ta + Tb) / 2} def mutation(individual,V_boundary,n_boundary,T_boundary): next_V = individual['V'] + random.uniform(-0.5, 0.5) next_n = individual['n'] + random.uniform(-0.3, 0.3) next_T = individual['T'] + random.uniform(-10, 10) V_lower_boundary, V_upper_boundary = V_boundary n_lower_boundary, n_upper_boundary = n_boundary T_lower_boundary, T_upper_boundary = T_boundary # Guarantee its within the boundaries next_V = min(max(next_V,V_lower_boundary), V_upper_boundary) next_n = min(max(next_n, n_lower_boundary), n_upper_boundary) next_T = min(max(next_T, T_lower_boundary), T_upper_boundary) return {'V': next_V, 'n': next_n, 'T' : next_T} def make_next_gen(previous_population, individual,population): next_gen = [] pop_size = len(previous_population) for i in range(pop_size): individual = crossover(sort_pop_by_fitness(population)) individual= mutation(individual) next_gen.append(individual) return next_gen generations = 10000 population = generate_pop(size=30, V_boundary=(1, 10), n_boundary=(0.1, 10), T_boundary= (1, 100)) i = 1 P = 100 best_scores = [] while True: print('Generation:', i) for individual in population: print(individual) print(function(individual,P)) if function(individual, P) == 0: print('The solution is:' + function(individual, P)) break elif (function(individual, P) >= -10) and (function(individual, P) <= 20): print('The solution is close to :', function(individual, P), 'The variables are:', individual) break i = i+1 if i == generations: break
for i in range(int(input())): s = input() if "010" in s or "101" in s: print("Good") else: print("Bad")
for i in range(int(input())): n,p=[int(x) for x in input().split()] if p==1 or (n==2 and p==2) or p==2 or n%p!=0: print('impossible') elif n==p: print('a'+'b'*(n-2)+'a') else: print(('a'+'b'*(p-2)+'a')*(n//p))
def gcd(a, b): if a == 0: return b else: return(gcd(b % a, a)) #Using Euclid's GCD algorithm for i in range(int(input())): n, m = [int(x) for x in input().split()] # Getting the input if n % 2: odd_n = n // 2 + 1 else: odd_n = n // 2 if m % 2: odd_m = m // 2 + 1 else: odd_m = m // 2 # Finding all odd numbers in the range total_odd = odd_n * (m - odd_m) + odd_m * (n - odd_n) # as odd + even and even + odd will result in odd common = gcd(total_odd, n * m) # Finds GCD of numertr and denomr and divides them to simplify them print(str(total_odd // common)+ '/' + str((n * m) //common)) # Prints the result
# -*- coding: utf-8 -*- """ Created on Wed Dec 25 21:12:52 2019 @author: solan """ import random print('Hello! What is your name?') myName = input() Games = ' ' while Games ==' ': try: Games = int(input("How many games would you like to play?")) except: print("Please select a number") for game in range(0,Games): pick = random.randint(1,25) guess = None Attempts = 0 while pick !=guess: try: guess = int(input("Pick a number:")) except: print("Please select a number") continue if guess != pick: Attempts += 1 if guess >pick: print("Your guess is too High!") else: print("Your guess is too Low!") else: print("Correct! It took you this much guess: %s"% Attempts)
# -*- coding: utf-8 -*- """ Simulator of a coffee machine. It can run out of ingredients, such as milk or coffee beans, it can offer you various types of coffee, and, finally, it will take money for the prepared drink. A project for hyperskill.org @author: Giliazova """ class CoffeeMachine(): d = {"water": 400, "milk": 540, "coffee beans": 120, "disposable cups": 9, "money": 550} # functions in an alphabetical order def ingredients(self, coffee_type): if coffee_type == "1": # espresso return {"water": 250, "milk": 0, "coffee beans": 16, "disposable cups": 1} elif coffee_type == "2": # latte return {"water": 350, "milk": 75, "coffee beans": 20, "disposable cups": 1} elif coffee_type == "3": # cappuccino return {"water": 200, "milk": 100, "coffee beans": 12, "disposable cups": 1} def make_coffee(self, coffee_type): components = self.ingredients(coffee_type) for ingredient in components: self.d[ingredient] -= components[ingredient] def not_enough_ingredients(self, coffee_type): components = self.ingredients(coffee_type) for ingredient in components: if self.d[ingredient] < components[ingredient]: return ingredient return False def price(self, coffee_type): prices = {"1": 4, "2": 7, "3": 6} return prices[coffee_type] def print_dict(self): print("The coffee machine has:") for thing in self.d: if thing == "money": print("$" + str(self.d[thing]) + " of " + thing) else: print(str(self.d[thing]) + " of " + thing) def user_input(self, string): return input(string) # main cm = CoffeeMachine() while True: action = cm.user_input("Write action (buy, fill, take, remaining, exit):\n") if action == "buy": coffee_type = cm.user_input("What do you want to buy? 1 - espresso, " +\ "2 - latte, 3 - cappuccino, " +\ "back - to main menu:\n") if coffee_type == "back": continue ingredient = cm.not_enough_ingredients(coffee_type) if ingredient: print(f"Sorry, not enough {ingredient}!") else: cm.make_coffee(coffee_type) cm.d["money"] += cm.price(coffee_type) print("I have enough resources, making you a coffee!") elif action == "fill": cm.d["water"] += int(cm.user_input("Write how many ml of water do you want to add:\n")) cm.d["milk"] += int(cm.user_input("Write how many ml of milk do you want to add:\n")) cm.d["coffee beans"] += int(cm.user_input("Write how many grams of coffee beans " +\ "do you want to add:\n")) cm.d["disposable cups"] += int(cm.user_input("Write how many disposable cups of " +\ "coffee do you want to add:\n")) elif action == "take": print(f"I gave you ${cm.d['money']}") cm.d["money"] = 0 elif action == "remaining": cm.print_dict() elif action == "exit": break
# NineByNine.py for i in range(1,10): for j in range(1,i+1): print("{}*{}={}".format(j,i,i*j),end=' ') print(' ') # 阶乘和1!+2!+3!+++ sum = 0 temp = 1 for i in range(1,11): temp *= i sum += temp print("运算结果:{}".format(sum))
n1 = float(input('Primeira nota: ')) n2 = float(input('Segunda Nota: ')) m = (n1 + n2)/2 if m < 5.0: print(f'Infelizmente você está \033[31mREPROVADO\033[m pois a média de {m} não é o suficiente para recuperação.') elif 5 < m < 6.9: print('Você está de \033[33mRECUPERAÇÃO\033[m pois a média {} não é o suficiente para ser aprovado'.format(m)) elif m >= 7: print('PARABAINS você está \033[34mAPROVADO\033[m!!! {} é uma boa nota!!!'.format(m))
frase = str(input('Digite uma frase: ')).strip().upper() frases = frase.split() tudojunto = ''.join(frases) reverso = '' for letras in range(len(tudojunto)-1, -1, -1): reverso += tudojunto[letras] print(tudojunto, reverso) if tudojunto == reverso: print('A Frase {} É um Políndromo'.format(frase)) else: print('A Frase {} NÃO É um Polínromo'.format(frase))
num = int(input('Digite o valor a ser convertido: ')) base = int(input("""Qual será a base de conversão? sendo: \033[34m1\033[m = binário \033[34m2\033[m = Octal \033[34m3\033[m = Hexadecimal Digite: """)) bin = bin(num) oct = oct(num) hex = hex(num) if base == 1: print('O Resultado é: {}'.format(bin)) elif base == 2: print('O Resultado é: {}'.format(oct)) elif base == 3: print('O Resultado é: {}'.format(hex))
# Programa que tem uma função notas() que pode receber várias notas de alunos e vai retornar # um dicinário com as seguintes informações # - Quantidade de notas # - A maior nota # - A menor nota # - Média da turma # - Situação(opcional) def notas(*n, sit=False): """ → Função para analizar notas e situações de varios alunos :param n: uma ou mais notas dos alunos (aceita varias) :param sit: valor opcional, indicando se deve ou não adiciona a situação :return: dicionário com varias informações sobre a situação da turma. """ di = dict() li = list() for c in n: li.append(c) di['quantidade'] = len(li) di['maior'] = max(li) di['menor'] = min(li) di['media'] = (sum(li) / len(li)) if sit: if di['media'] < 4: di['situacao'] = 'Ruim' elif di['media'] < 6: di['situacao'] = 'Razoavel' elif di['media'] < 8: di['situacao'] = 'Boa' elif di['media'] <= 10: di['situacao'] = 'Ótima' return di # Programa Principal resp = notas(5.5, 9.5, 9.5, sit=True) print(resp)
num = total = dig = 0 while num != 999: num = int(input('Digite um número [999 para parar]: ')) if num != 999: total += num dig += 1 print('Você digitou {}, E a soma dos números digitados é {}.'.format(dig, total))
num = [int(input('Digite um número na posição 0: ')), int(input('Digite um número na posição 1: ')), int(input('Digite um número na posição 2: ')), int(input('Digite um número na posição 3: ')), int(input('Digite um número na posição 4: '))] maior = max(num) menor = min(num) indexmaior = indexmenor = 0 print(f'Você digitou os números: {num}') print(f'O Maior número é {max(num)} e está nas posições: ', end='') for p, n in enumerate(num): if maior == n: indexmaior = num.index(maior, p) print(indexmaior, end=' ') print(f'\nO menor número é {menor} e está nas posições: ', end='') for p, n in enumerate(num): if menor == n: indexmenor = num.index(menor, p) print(indexmenor, end=' ')
pro = float(input('Qual o preço do produto?: R$')) desc = pro - float(pro*0.05) print('Este produto na promoção irá custar R${:.2f}, pois tem 5% de desconto'.format(desc))
num = [] for c in range(0, 5): n = int(input('Digite um número: ')) if c == 0 or n > num[-1]: num.append(n) print('O número foi adicionado a ultima posição') else: pos = 0 while pos < len(num): if n < num[pos]: num.insert(pos, n) print(f'O número foi a dicionado a posição {pos}') break pos += 1 print(f'Os números digitados em ordem crescente é {num}')
n1 = float(input('Primeiro valor: ')) n2 = float(input('Segundo valor: ')) n3 = float(input('Terceiro valor: ')) if n1 > n2 >= n3: ma = n1 so = n2 + n3 elif n2 > n3 >= n1: ma = n2 so = n3 + n1 elif n3 > n1 >= n2: ma = n3 so = n1 + n2 elif n3 > n2 >= n1: ma = n3 so = n2 + n1 elif n2 > n1 >= n3: ma = n2 so = n3 + n1 elif n1 > n3 >= n2: ma = n1 so = n3 + n2 if ma >= so: print('Essas retas não formam um triangulo!') else: print('Essas retas formam um triangulo!')
from random import randint from time import sleep computador = randint(1, 3) print('\033[7;30m', '=-=' * 20, '\033[m\n\033[7;30m | Jokenpô | \033[m', '\n\033[7;30m', '\033[7;30m-=-' * 20, '\033[m') jogador = str(input('Por Favor escolha entre: "Pedra, Papel e Tesoura" e digite a sua escolha: ')).lower().strip() print('Analizando...') sleep(2) if computador == 1 and jogador == 'pedra': print('Empate os dois Escolhem PEDRA!') elif computador == 1 and jogador == 'papel': print('Jogador Vence!! computador escolheu PEDRA!') elif computador == 1 and jogador == 'tesoura': print('Computador Vence!! Computador escolheu PEDRA!') elif computador == 2 and jogador == 'pedra': print('Computador Vence!! Computador escolheu PAPEL!') elif computador == 2 and jogador == 'papel': print('Empate os dois Escolhem PAPEL!') elif computador == 2 and jogador == 'tesoura': print('Jogador Vence!! Computador escolheu PAPEL!') elif computador == 3 and jogador == 'pedra': print('Jogador Vence!! Computador escolheu TESOURA!') elif computador == 3 and jogador == 'papel': print('Computador Vence!! Computador escolheu TESOURA!') elif computador == 3 and jogador == 'tesoura': print('Empate os dois escolhem TESOURA!') else: print('Você digitou errado! Tente novamente!')
n1 = float(input('Digite o primeiro número: ')) n2 = float(input('Digite o segundo número: ')) n3 = float(input('Digite o terceiro número: ')) if n1 > n2 > n3: print('O maior numero é {}, e o menor é {}'.format(n1, n3)) if n2 > n3 > n1: print('O maior número é {}, e o menor é {}'.format(n2, n1)) if n3 > n1 > n2: print('O maior número é {}, e o menor é {}'.format(n3, n2)) if n1 > n3 > n2: print('O maior número é {}, e o menor é {}'.format(n1, n2)) if n2 > n1 > n3: print('O maior número é {}, e o menor é {}'.format(n2, n3)) if n3 > n2 > n1: print('O maior número é {}, e o menor é {}'.format(n3, n1))
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] spar = sh3 = mv2 = 0 for h in range(0, 3): for v in range(0, 3): matriz[h][v] = int(input(f'Digite um valor para [{h}, {v}]: ')) if matriz[h][v] % 2 == 0: spar += matriz[h][v] if v == 0 or matriz[1][v] > mv2: mv2 = matriz[1][v] sh3 += matriz[h][2] for hori in range(0, 3): for vert in range(0, 3): print(f'[{matriz[hori][vert]:^5}]', end='') print() print(f'A soma de todos os valores pares digitados é {spar}') print(f'A soma dos valores da terceira coluna é {sh3}') print(f'O Maior valor da segunda linha é {mv2}')
lista = list() while True: lista.append(int(input('Digite um valor: '))) continuar = ' ' while continuar not in 'SN': continuar = str(input('Quer continuar?[S/N]: ')).strip().upper()[0] if continuar == 'N': break lista.sort(reverse=True) print(f'Foram digitados {len(lista)} números e são estes em ordem decrescente: {lista}') if 5 in lista: print('O número 5 está nesta lista') else: print('O número 5 não faz parte dessa lista')
valor = float(input('Digite o Valor que quer aplicar o desconto: R$')) desci = float(input('Digite o desconto que quer aplicar: ')) descf = desci / 100 final = valor - (descf * valor) print('O valor R${} com {}% de desconto será R${:.2f}'.format(valor, desci, final))
# Crie um módulo chamado moeda.py que tenha as funções # incorporadas aumentar(), diminuir(), doro() e metade. # Faça também um programa que importe esses módulo e # use algumas dessas funções import moeda # from ex107 import moeda num = float(input('Digite um valor: ')) print(f'O dobro do valor {num} é {moeda.dobro(num)}') print(f'A metade do valor {num} é {moeda.metade(num)}') print(f'O valor {num} aumentado em 10% é {moeda.aumentar(num, 10)}') print(f'O valor {num} diminuido em 10% é {moeda.diminuir(num, 10)}')
# Adicione ao módulo moeda.py criado nos desafios anteriores, uma função chamada resumo(), # que mostre na tela algumas informações geradas pelas funções que já temos no módulo # criado até aqui import moeda2 # Programa Principal num = float(input('Digite um valor: ')) moeda2.resumo(num, 80, 35)
#imports import json import textwrap import sys #this is the exit the code early if business is not found #functions #this function prints the adress of the business that is used def using(name,adress): print("Using {} at:".format(name)) print(adress) #this function prints the reviews from the file reviews.json def print_reviews(id_number): file = open("reviews.json") rating = [] for line in file: business = json.loads(line) if id_number == business["business_id"]: rating.append(business["text"]) #adds all the reviews to the rating list for i in range(len(rating)): print() print("Review: " + str(i+1)) wrapper = textwrap.TextWrapper( initial_indent = ' '*4, subsequent_indent = ' '*4 ) if "\n\n" in rating[i]: #if the review has mutiple paragraph rating[i] = rating[i].split("\n\n") for j in range(len(rating[i])): for l in wrapper.wrap(rating[i][j]): print(l) print() else: #if the review has only one line for l in wrapper.wrap(rating[i]): print(l) print() #main #initializations f = open("businesses.json") b = input("Enter a business name => ") print(b) bs = dict() exist = False #add business id and adress to the dictionary for line in f: business = json.loads(line) if b == business["name"]: exist = True bs[business["business_id"]] = business["full_address"] #if no name is found in the file if exist == False: print("This business is not found") sys.exit() #if only one adress found if len(bs) == 1: print() using(b,list(bs.values())[0]) print_reviews(list(bs.keys())[0]) #if mutiple adress found else: sorted_business = sorted(bs.items(), key=lambda x: x[0], reverse=True) #sorts the business by thier id print() print("Found {} at:".format(b)) #prints the options of business for i in range(len(bs.values())): print() print(str(i+1)+".") print(sorted_business[i][1]) #asks user for a input until a valid one is given print() choise = int(input("Select one from 1 - {} ==> ".format(len(bs)))) print(choise) while choise not in list(range(1,len(bs)+1)): choise = int(input("Select one from 1 - {} ==> ".format(len(bs)))) print(choise) choise -= 1 print() using(b,sorted_business[choise][1]) print_reviews(sorted_business[choise][0])
# you need to supply ip <--- to add dns lookup in future import socket from IPy import IP def scan_port(ipadd, port): try: sock = socket.socket() #the less the faster but not very accurate sock.setttimeout(0.5) sock.connect((ipadd, port)) print("[+] Port " + str(port) + " is Open") except: print("[-] Port " + str(port) + "is Closed") ipadd = input("[+] Enter IP to Scan: ") # Port 1-65535 for port in range(1,65535): scan_port(ipadd,port)
# ​ Write a Python program to remove the characters which have odd index # values of a given string. def remove_odd_index_char(string): result = "" for i in range(len(string)): if i % 2 == 0: result = result + string[i] return result def main(): string=input("Enter string: ") print(remove_odd_index_char(string)) if __name__== '__main__': main()
# Write a Python script to generate and print a dictionary that contains a # number (between 1 and n) in the form (x, x*x). # Sample Dictionary ( n = 5) : # Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} def main(): n= int(input('Enter dictionary size : ')) sample_dict={n:n*n for n in range(1,n+1) } print(sample_dict) if __name__ == '__main__': main()
# Write a Python function to find the Max of three numbers. def max(num1,num2,num3): if num1 > num2 and num1 > num3: return num1 elif num2 > num3: return num2 else: return num3 def main(): num1=int(input("First Number : ")) num2=int(input("Second Number : ")) num3=int(input("Third Number : ")) print("Max number is : ",max(num1,num2,num3)) if __name__ == '__main__': main()
# Write a Python program to get a single string from two given strings, separated # by a space and swap the first two characters of each string. def concat_swap_str(str1,str2): final_str= str1.replace(str1[:2],str2[:2]) + ' ' + str2.replace(str2[:2],str1[:2]) return final_str def main(): str1= input("Enter first String: ") str2=input("Enter second String: ") print(concat_swap_str(str1,str2)) if __name__ == '__main__': main()
# ​ Write a Python program to count the occurrences of each word in a given # sentence. def num_of_words(string): words_num={} word_list=string.split(' ') for words in word_list: if words in words_num: words_num[words] += 1 else: words_num[words] = 1 return words_num def main(): string= input("Enter the string:") print(num_of_words(string)) if __name__=='__main__': main()
# Write a Python function that takes a list and returns a new list with unique # elements of the first list. def unique_list(data): return list(set(data)) def main(): sample_list=[1,2,3,3,3,3,4,5] print("unique list=",unique_list(sample_list)) if __name__ == "__main__": main()
# Write a Python program to count the number of strings where the string # length is 2 or more and the first and last character are same from a given list of # strings. def count_str_number(string): count=0 for word in string: if len(word) >= 2: if word[0] == word[-1]: count+=1 else: count=count else: count=count return count def main(): str_list=list(input('Enter list of strings: ').split(',')) print(count_str_number(str_list)) if __name__ == '__main__': main()
# Write a Python program to get a list, sorted in increasing order by the last # element in each tuple from a given list of non-empty tuples. def last(n): return n[-1] def sort_list_last(tuples): return sorted(tuples, key=last) def main(): print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)])) if __name__ == '__main__': main()
# Dictionaries # A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index to address it. # For example, a database of phone numbers could be stored using a dictionary like this: # phonebook = {} # phonebook["John"] = 938477566 # phonebook["Jack"] = 938377264 # phonebook["Jill"] = 947662781 # Alternatively, a dictionary can be initialized with the same values in the following notation: phonebook = { "John": 93847756, "Jack": 93837726, "Jill": 94766278 } # Iterating over dictionaries (using for & in) for name, phNo in phonebook.items(): print(f"Phone number of {name} is {phNo}") # testing code 1 (For searching name(keys) in phonebook) if "John" in phonebook: print("John is listed in the phonebook.") # testing code 2 (For searching phNo(values) in phonebook) if 94766278 in phonebook.values(): print ("Number found") else: print("Number Not Found") # # Removing a value phonebook = { "John": 93847756, "Jack": 93837726, "Jill": 94766278 } del phonebook["John"] print(f"1 Printing Phone book after del 'John' : {phonebook}") phonebook = { "John": 93847756, "Jack": 93837726, "Jill": 94766278 } phonebook.pop("Jill") print(f"2 Printing Phone book after pop 'Jill' : {phonebook}") # # conditinal remove phonebook = { "John": 93847756, "Jack": 93837726, "Jill": 94766278 } if "John" in phonebook: phonebook.pop("John") print(f"3 Printing Phone book after conditional pop 'John' : {phonebook}")
# Basic Operators # Arithmetic Operators # Just as any other programming languages, the addition, subtraction, multiplication, and division operators can be used with numbers. number = 1 + 2 * 3 / 4.0 print('Print Number: ' + str(number)) remainder = 11 % 3 print('Print Remainder: ' + str(remainder)) squared = 7 ** 2 print('Print Squared: ' + str(squared)) cubed = 2 ** 3 print('Print Cubed: ' + str(cubed)) # Operators with Strings # Python supports concatenating strings using the addition operator: helloworld = "hello" + " " + "world" print('Printing HelloWorld with Space: ' + str(helloworld)) # Python also supports multiplying strings to form a string with a repeating sequence: lotsofhellos = "hello " * 10 print('Print Hello 10 times: ' + str(lotsofhellos)) # Operators with Lists # Lists can be joined with the addition operators: even_numbers = [2, 4, 6, 8] odd_numbers = [1, 3, 5, 7] all_numbers = odd_numbers + even_numbers print('Combined List of Even and Odd Numbers: ' + str(all_numbers)) all_numbers.sort() print('Sorted List Alphabetically: ' + str(all_numbers)) # Just as in strings, Python supports forming new lists with a repeating sequence using the multiplication operator: print("Printing List in repeating sequence: " + str([1, 2, 3] * 3))
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 # -10,-9,-8,-7,-6,-5,-4,-3,-2,-1 # list[start:end:step] print(f"Condition 1 : {my_list[::-1]}") print(f"Condition 2.a : {my_list[2:-1:2]}") print(f"Condition 2.b : {my_list[2:9:2]}") print(f"Condition 2.c : {my_list[-2:1:-2]}") sample_url = 'http://www.google.com' string_1 = "Print Simple Varialble : " print(f"{string_1} {sample_url}") # Reverse the url string_2 = "Print Slicing from start til last Index (Reverse the url) : " print(f"{string_2} {sample_url[::-1]}") # # Get the top level domain string_3 = "Printing the top level domain : " print(f"{string_3} {sample_url[-4:]}") # Print the url without the http:// string_4 = "Printing the url without the http:// : " print(f"{string_4} {sample_url[7:]}") # # Print the url without the http:// or the top level domain string_5 = "Printing the url without the http:// or the top level domain : " print(f"{string_5} {sample_url[11:-4]}")
import sqlite3 from employeeSqlite import Employee conn = sqlite3.connect('sqliteDemoEmp.db') c = conn.cursor() # c.execute("""CREATE TABLE employees( # first text, # last text, # pay integer # )""") # c.execute("INSERT INTO employees VALUES ('Urooj', 'Zahid', 90000)") # conn.commit() c.execute("SELECT * FROM employees WHERE last='Zahid'") print(c.fetchall()) conn.commit() conn.close()
__author__ = 'Ashwini Rajesh Singh' """ CSCI-603: Assignment 1 Author: Ashwini Singh This is a program to display Name of Author. """ import turtle import math WINDOW_WIDTH = 400 WINDOW_HEIGHT = 400 def init(x,y,z): """ Initialize for drawing. (-200, -200) is in the lower left and (200, 200) is in the upper right. :pre: pos (0,0), heading (east), up :post: pos (0,0), heading (north), up :return: None """ turtle.setworldcoordinates(-WINDOW_WIDTH/2, -WINDOW_WIDTH/2, WINDOW_WIDTH/2, WINDOW_HEIGHT/2) turtle.setheading(0) turtle.hideturtle() turtle.title('Name') turtle.up() turtle.setx(x) turtle.sety(y) turtle.color(z) turtle.speed(0) turtle.left(90) turtle.down() def setPos(x): """ Set position for turtle after drawing any letter :pre: pos (0,0), heading (east), up :post: pos (0,0), heading (north), up :return: None """ turtle.up() turtle.forward(x/3) turtle.left(90) turtle.down() pass def drawA(x): """ Draw A. :pre: (relative) pos (0,0), heading (north), up :post: (relative) pos (0,0), heading (east), up :return: None """ turtle.forward(x) turtle.right(90) turtle.forward(x/1.5) turtle.right(90) turtle.forward(x/2) turtle.right(90) turtle.forward(x/1.5) turtle.right(180) turtle.forward(x/1.5) turtle.right(90) turtle.forward(x/2) turtle.left(90) pass def drawS(x): """ Draw S. :pre: (relative) pos (0,0), heading (north), up :post: (relative) pos (0,0), heading (east), up :return: None """ turtle.right(90) turtle.forward(x/1.5) turtle.left(90) turtle.forward(x/2) turtle.left(90) turtle.forward(x/1.5) turtle.right(90) turtle.forward(x/2) turtle.right(90) turtle.forward(x/1.5) turtle.right(90) turtle.up() turtle.forward(x) turtle.left(90) turtle.down() pass def drawH(x): """ Draw H. :pre: (relative) pos (0,0), heading (north), up :post: (relative) pos (0,0), heading (east), up :return: None """ turtle.forward(x) turtle.right(180) turtle.forward(x/2) turtle.left(90) turtle.forward(x/1.5) turtle.left(90) turtle.forward(x/2) turtle.right(180) turtle.forward(x) turtle.left(90) pass def drawW(x): """ Draw W. :pre: (relative) pos (0,0), heading (north), up :post: (relative) pos (0,0), heading (east), up :return: None """ turtle.forward(x) turtle.right(180) turtle.forward(x) turtle.left(135) turtle.forward(x/2) turtle.right(90) turtle.forward(x/2) turtle.left(135) turtle.forward(x) turtle.right(180) turtle.forward(x) turtle.left(90) pass def drawI(x): """ Draw I. :pre: (relative) pos (0,0), heading (north), up :post: (relative) pos (0,0), heading (east), up :return: None """ turtle.forward(x) turtle.right(180) turtle.forward(x) turtle.left(90) pass def drawN(x): """ Draw N. :pre: (relative) pos (0,0), heading (north), up :post: (relative) pos (0,0), heading (east), up :return: None """ turtle.forward(x) turtle.right(150) turtle.forward(x/math.cos(math.radians(30))) turtle.left(150) turtle.forward(x) turtle.right(180) turtle.forward(x) turtle.left(90) pass def drawR(x): """ Draw R. :pre: (relative) pos (0,0), heading (north), up :post: (relative) pos (0,0), heading (east), up :return: None """ turtle.forward(x) turtle.right(90) turtle.forward(x/2) turtle.right(90) turtle.forward(x/2) turtle.right(90) turtle.forward(x/2) turtle.left(135) turtle.forward((x)*math.cos(math.radians(45))) turtle.left(45) pass def drawG(x): """ Draw I. :pre: (relative) pos (0,0), heading (north), up :post: (relative) pos (0,0), heading (east), up :return: None """ turtle.forward(x) turtle.right(90) turtle.forward(x/2) turtle.right(90) turtle.forward(x/4) turtle.right(180) turtle.forward(x/4) turtle.left(90) turtle.forward(x/2) turtle.left(90) turtle.forward(x) turtle.left(90) turtle.forward(x/4) turtle.left(90) turtle.forward(x/3) turtle.right(90) turtle.forward(x/4) turtle.right(90) turtle.forward(x/3) turtle.left(90) pass def main(): """ The main function. :pre: pos (0,0), heading (east), up :post: pos (0,0), heading (east), up :return: None """ init(-180,100,'green') drawA(50) setPos(50) drawS(50) setPos(50) drawH(50) setPos(50) drawW(50) setPos(50) drawI(50) setPos(50) drawN(50) setPos(50) drawI(50) setPos(50) init(-50,0,'red') drawR(50) turtle.up() turtle.forward(5) turtle.down() turtle.dot(5) init(-140,-100,'blue') drawS(50) setPos(50) drawI(50) setPos(50) drawN(50) setPos(50) drawG(50) setPos(50) drawH(50) input('Hit enter to close...') turtle.bye() main()
""" Given an array num and a number target. Find all unique combinations in num where the numbers sum to target. Example Example 1: Input: num = [7,1,2,5,1,6,10], target = 8 Output: [[1,1,6],[1,2,5],[1,7],[2,6]] Example 2: Input: num = [1,1,1], target = 2 Output: [[1,1]] Explanation: The solution set must not contain duplicate combinations. """ class Solution: """ @param num: Given the candidate numbers @param target: Given the target number @return: All the combinations that sum to target """ def combinationSum2(self, num, target): num.sort() result = [] self.dfs(num, target, result, 0, []) return result def dfs(self, num, target, result, index, path): if target < 0: return if target == 0: #append a deep copy of the code result.append(path[:]) return #iterate over the current i to the len of the list for i in range(index, len(num)): #check with the current i if it is greater we are at the previous recursion depth and if the current i == the previous i skip this level if i > index and num[i] == num[i - 1]: continue #add the current i to our path and then increase the i to one to check the next index path.append(num[i]) self.dfs(num, target - num[i], result, i + 1, path) path.pop()
""" Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, output sequence in dictionary order. Transformation rule such that: Only one letter can be changed at a time Each intermediate word must exist in the dictionary Example Example 1: Input:start = "a",end = "c",dict =["a","b","c"] Output:[["a","c"]] Explanation: "a"->"c" Example 2: Input:start ="hit",end = "cog",dict =["hot","dot","dog","lot","log"] Output:[["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]] Explanation: 1."hit"->"hot"->"dot"->"dog"->"cog" 2."hit"->"hot"->"lot"->"log"->"cog" The dictionary order of the first sequence is less than that of the second. """ from collections import deque class Solution: """ @param: start: a string @param: end: a string @param: dict: a set of string @return: a list of lists of string """ def findLadders(self, start, end, dict): #add both start and end to dict since it is a set it doesnt matter if they are in already dict.add(start) dict.add(end) distance = {} #call bfs on end word with a distance map that we will store the disance from the word to the next one as another 1 self.bfs(end, distance, dict) #initialize the path with the start word result, path = [], [start] #dfs needs to get everything self.dfs(start, end, dict, distance, result, path) return result def bfs(self, start, distance, dict): #start the distance map with the current word mapped to 0 as the value distance[start] = 0 #then add that word to the que queue = deque([start]) while queue: word = queue.popleft() #pass our popped word down to our modWord function and it will return a sublist with all the possible combinations of current word that is one letter different wordsList = self.modWord(word, dict) #iterate through the list if it is not in the distance map already add it to the distance map and and the queue, the value is the previous levels value plus 1 for i in wordsList: if i not in distance: queue.append(i) distance[i] = distance[word] + 1 def modWord(self, word, dict): wordsList=[] #iterate through each letter of the current word and each letter of the alphabet for eachLetter in range(len(word)): for letter in "abcdefghijklmnopqrstuvwxyz": #makes a new copy of a word for each iteration of the word changing one letter at a time. newWord = word[ : eachLetter] + letter + word[eachLetter +1: ] #if the newword isnt the current word and its in our original set then we can add it to the list we will pass to our other functions if newWord != word and newWord in dict: wordsList.append(newWord) return wordsList def dfs(self, start, end, dict, distance, result, path): #base case is when the current word that starts the dfs is equal to the end word if start == end: result.append(path[:]) return #take all possible permutations of the start word wordsList = self.modWord(start, dict) #iterate through that list and check if the distance is greater than 1 if it is ignore it, otherwise if it is, add to the path and pass the new word to the dfs again then once the dfs is done pop last element of path for newWord in wordsList: if distance[newWord] + 1 != distance[start]: continue path.append(newWord) self.dfs(newWord, end, dict, distance, result, path) path.pop()
""" Ugly number is a number that only have prime factors 2, 3 and 5. Design an algorithm to find the nth ugly number. The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12... Example Example 1: Input: 9 Output: 10 Example 2: Input: 1 Output: 1 """ import heapq class Solution: """ @param n: An integer @return: return a integer as description. """ def nthUglyNumber(self, n): heap = [1] visited = set([1]) val = None #pop first val from the heap for i in range(n): val = heapq.heappop(heap) #iterate over our 2,3,5 and for the current val multiply them for factor in [2, 3, 5]: #if they are not in the vistied set push it and add it to the set if val * factor not in visited: heapq.heappush(heap, factor * val) visited.add(factor * val) #if we are done with the for loop we can just return our val return val
""" Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example Example 1: Input: nums = [0, 1, 0, 3, 12], Output: [1, 3, 12, 0, 0]. Example 2: Input: nums = [0, 0, 0, 3, 1], Output: [3, 1, 0, 0, 0]. """ class Solution: """ @param nums: an integer array @return: nothing """ def moveZeroes(self, nums): #start both left and right to 0 left, right = 0, 0 #iterate with the right variable through the nums list while right < len(nums): #if the current right isnt 0 and the current left isnt the current right then replace the current left with the current right then increment both the life and right when that loop ends if nums[right] != 0: if nums[left] != nums[right]: nums[left] = nums[right] left += 1 right += 1 #after the above code exits the left pointer will be the remainder of the codes that havent been moved. meaning that the remainder of the code can be replaced with 0 by iterating through the left and for each left seeting tha balue to 0 while left < len(nums): nums[left] = 0 left += 1
""" Give a string, you can choose to split the string after one character or two adjacent characters, and make the string to be composed of only one character or two characters. Output all possible results. Example Example1 Input: "123" Output: [["1","2","3"],["12","3"],["1","23"]] first round path =["1"] second s = "23" and path is ["1", "2"] third rounds = "3" path = ["3"] and path is ["1", "2", "3"] fourth round s = "" so we append ["1", "2", "3"] to result 5th round go back to third round and pop the "3" from path then increment i t0 1 and exit that loop 6th round goes back to second round and pop "2" from path then increment 1 to 1 and since the string is "23" it wont exit so we call the dps with "1" and append that to path so it becomes [1, 23] Example2 Input: "12345" Output: [["1","23","45"],["12","3","45"],["12","34","5"],["1","2","3","45"],["1","2","34","5"],["1","23","4","5"],["12","3","4","5"],["1","2","3","4","5"]] """ class Solution: """ @param: : a string to be split @return: all possible split string array """ def splitString(self, s): result = [] path = [] self.dfs(s, result, path) return result #base case for recursion is when the lower level is the string "" def dfs(self, s, result, path): if s == "" : #use [:] to call all elements in list result.append(path[:]) #use range 2 since we are checking 2 strings for i in range(2): #if the string can be split furher continue if i + 1 <= len(s): #appends the current strings from the current index + 1 to the end of the path path.append(s[i + 1 :]) #recursively calls the remainder of the string from above self.dfs(s, result, s[: i + 1]) #after the above round of recursion is completed then pop the current rightmost item from the list path.pop()
""" Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example Example 1: Input: [2->4->null,null,-1->null] Output: -1->2->4->null Example 2: Input: [2->6->null,5->null,7->null] Output: 2->5->6->7->null """ import heapq """ using a heap Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param lists: a list of ListNode @return: The head of one sorted list. """ def mergeKLists(self, lists): heap = [] #iterate over each linked list item and use a while loop to iterate over linked list items for list in lists: #while the list is not null push each item to the heap and go to next node while list: heapq.heappush(heap, list.val) list = list.next #node is a placeholder, and sentinal points to the node so we can change to node and hold all values of the node node = ListNode(0) sent = node #while the heap still has items our next node points to the next item in the heap and add it to our node while heap: #then set it equal to the node node.next = ListNode(heapq.heappop(heap)) node = node.next #point to the nodes next val since started the node as a placeholder return sent.next """ import heapq """ """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ """ class Solution: """ """ @param lists: a list of ListNode @return: The head of one sorted list. """ """ def mergeKLists(self, lists): start, end = 0, len(lists) - 1 return self.merge(lists, start, end) def merge(self, lists, start, end): if start == end: return lists[start] mid = (start + end) // 2 left = self.merge(lists, start, mid) right = self.merge(lists, mid +1, end) return self.merge2Lists(lists, left, right) def merge2Lists(self, lists, left, right): tail = sent = ListNode(0) while left and right: if left.val > right.val: tail.next = right right = right.next else: tail.next = left left = left.next tail = tail.next if left: tail.next = left if right: tail.next = right return sent.next """
""" Implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). The function prototype should be: bool isMatch(string s, string p) isMatch("aa","a") → false isMatch("aa","aa") → true isMatch("aaa","aa") → false isMatch("aa", "a*") → true isMatch("aa", ".*") → true isMatch("ab", ".*") → true isMatch("aab", "c*a*b") → true Example Example 1: Input:"aa","a" Output:false Explanation: unable to match Example 2: Input:"aa","a*" Output:true Explanation: '*' can repeat a """ class Solution: """ @param s: A string @param p: A string includes "." and "*" @return: A boolean """ def isMatch(self, s, p): lengS = len(s) lengP = len(p) dp = [[False for _ in range(lengP + 1)] for _ in range(lengS + 1)] dp[0][0] = True for i in range(2, lengP + 1): #the only way that the top row will have a True is if it has * since it can erase one position, so it needs to have * in string for any value to be True if p[i -1] == "*" and dp[0][i - 2] == True: dp[0][i] = True for i in range(1, lengS + 1): for j in range(1, lengP + 1): #for all cases that arent * if the diagonal is True and the strings are either the same or it is a "." set the value to true if p[j-1] != "*": dp[i][j] = dp[i -1][j - 1] and (s[i -1] == p[j - 1] or p[j - 1] == ".") else: #if either the 2 to the left are true or the direct left then the current node is true dp[i][j] = dp[i][j - 2] or dp[i][j -1] #if the pattern before this current pattern equals the current string or its a "." and the above space is True set it to True if (p[j - 2] == s[i -1] or p[j -2] == ".") and dp[i - 1][j]: dp[i][j] = True return dp[-1][-1]
""" Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example Example 1: Input: tree = {1,2,3} Output: true Explanation: This is a balanced binary tree. 1 / \ 2 3 Example 2: Input: tree = {3,9,20,#,#,15,7} Output: true Explanation: This is a balanced binary tree. 3 / \ 9 20 / \ 15 7 Example 3: Input: tree = {1,#,2,3,4} Output: false Explanation: This is not a balanced tree. The height of node 1's right sub-tree is 2 but left sub-tree is 0. 1 \ 2 / \ 3 4 """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: True if this Binary tree is Balanced, or false. """ def isBalanced(self, root): def recurse(root): #need to return both boolean and number to track both in the recursion if not root: return True, 0 #sets the boolean and the left height boolie, leftHeight = recurse(root.left) #if the boolean for the left height is false return a false and the current left height if not boolie: return False, leftHeight boolie, rightHeight = recurse(root.right) if not boolie: return False, rightHeight #if the height diff is greater than one return false else return true and returns the current subtree height for thr rest of the recursion return abs(leftHeight - rightHeight) <= 1, max(leftHeight, rightHeight) + 1 #need to unpack the boolean the value is not needed result, num = recurse(root) #returns the result from the unpacked recursion return result
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): x = [] for i in matrix: x.append(list(map(lambda square: square ** 2, i))) return x
import random class GenerateRandomNum(): """docstring for GenerateRandomNum""" def check_user_input(self, input, rand): if (int(input) == " "): return "No input provided" else: if (int(input) > rand): return "Your selection is higher than" elif (int(input) < rand): return "Your selection is lower" elif (int(input) < 0 or int(input) > 6): return "User input is above range" elif (int(input) == rand): return True def user_input(): input_num = input("Please enter a number:") return int(input_num) run_app = GenerateRandomNum() random_num = random.randint(1, 6) user_data = user_input() resp = run_app.check_user_input(user_data, random_num) if resp == True: print("You win") else: print(resp)
import os import pandas as pd PATH = 'split_data' def main(): print(calculate_frequency(PATH, count_data(PATH), 3)) def count_data(path: str): count = 0 for foldername in os.listdir(path): for filename in os.listdir(f'{path}/{foldername}'): count = count + 1 return count def calculate_frequency(path: str, letters: int, seconds: int): length = 0 for foldername in os.listdir(path): for filename in os.listdir(f'{path}/{foldername}'): df = pd.read_csv(f'{path}/{foldername}/{filename}') length = length + len(df) hz = length / letters / seconds return hz if __name__ == '__main__': main()
'''O mesmo professor do desafio 019 quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada.''' import random nome1 = str(input("Primeiro aluno: ")) nome2 = str(input("Segundo aluno: ")) nome3 = str(input("Terceiro aluno: ")) nome4 = str(input("Quarto aluno: ")) alunos = [nome1, nome2, nome3, nome4] ordemApresentacao = random.sample(alunos, k=4) print("A ordem da apresentação é {}".format(ordemApresentacao))
''' Crie um programa que tenha uma função fatorial() que receba dois parâmetros: o primeiro que indique o número a calcular e outro chamado show, que será um valor lógico (opcional) indicando se será mostrado ou não na tela o processo de cálculo do fatorial. ''' def fatorial(num, show = False): """ -> Função que retorna a fatorial de um número :param num: O número a ser calculado :param show: (opcional) Mostra ou não a conta :return: fat que é a fatorial do número informado """ fat = 1 for c in range(num, 0, -1): if show: print(c, end='') if c > 1: print(' x ', end='') else: print(' = ', end='') fat *= c return fat print(fatorial(5, True))
''' Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos. ''' somaIdade = 0 cont = 0 maioridade = 0 nomeVelho = "" for pessoa in range(1,5): nome = str(input("Nome da {}° pessoa".format(pessoa))).upper() idade = int(input("Idade da {}° pessoa".format(pessoa))) sexo = str(input("Sexo: M - masculino e F - feminino")).upper() somaIdade += idade media = somaIdade / 4 if sexo == "M" and pessoa == 1: maioridade = idade nomeVelho = nome if sexo == "M" and idade > maioridade: maioridade = idade nomeVelho = nome if sexo == "F" and idade < 20: cont += 1 print("A media de idade do grupo é {}".format(media)) print("O homem mais velho tem {} anos e seu nome é {}".format(maioridade, nomeVelho)) print("A quantidade de mulheres com menos de 20 anos é {}".format(cont))
''' Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário. No final, mostre o conteúdo da estrutura na tela. ''' aluno = dict() ''' nome = str(input('Nome: ')) media = float(input(f'Média de {nome}: ')) aluno = {'Nome': nome, 'Média': media} ''' aluno['Nome'] = str(input('Nome: ')) aluno['Média'] = float(input(f'Média de {aluno["Nome"]}: ')) if aluno['Média'] >= 7: aluno['Situação'] = 'Aprovado' elif 5 <= aluno['Média'] < 7: aluno['Situação'] = 'Recuperação' else: aluno['Situação'] = 'Reprovado' for key, valor in aluno.items(): print(f'{key} é igual a {valor}')
'''Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta necessária para pintá-la,sabendo que cada litro de tinta pinta uma área de 2 metros quadrados.''' largura = float(input("Informe a largura da parede ")) altura = float(input("Informe a altura da parede")) area = largura * altura print("Sua parede tem a dimensão {}x{} e sua área é de {} m²" .format(largura, altura, area)) tinta = area / 2 print("Para pintar está parede você pracisará de {}l de tinta" .format(tinta))
''' Escreva um programa que leia um número N inteiro qualquer e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci. ''' print("SEQUÊNCIA DE FIBONACCI") print("-----------------------") num = int(input("Quantos termos deseja mostrar: ")) penultimo = 0 ultimo = 1 print("{} - {}".format(penultimo, ultimo),end='') cont = 3 while cont <= num: novo = penultimo + ultimo print(" - {}".format(novo),end='') penultimo = ultimo ultimo = novo cont += 1 print(" - FIM")
'''Crie um programa onde o usuário possa digitar vários valores e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos digitados, em ordem crescente.''' numeros = list() while True: n = int(input('Digite um valor : ')) if n not in numeros: numeros.append(n) print('Valor adicionado com sucesso') else: print('Valor duplicado!! Nao vou adicionar') resposta = str(input('Quer continuar? [s/N] ')) if resposta in 'Nn': break print('-='*30) numeros.sort() print(f'Voce digitou os valores {numeros}')
''' Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 parta viagens mais longas. ''' print("##### ALUGUEL DE CARROS #####") km = float(input('Informe a kilometragem percorrida: ')) if km <= 200: valor = km * 0.50 else: valor = km * 0.45 print("Você rodou {} km valor toral R$: {}".format(km, valor))
''' Faça um programa que leia 5 valores númericos e guarde-os em uma lista. No final, mostre qual foi o maior valor e o menor valor digitado e as suas respectivas posições na lista. ''' listanum = [] #cria a lista para armazenar os numeros maior = menor = 0 for c in range(0,5): #adicionando os numeros a lista listanum.append(int(input(f'Digite um valor para a posicao {c}: '))) if c == 0: maior = menor = listanum[c] else: if listanum[c] > maior: maior = listanum[c] if listanum[c] < menor: menor = listanum[c] print('=-'*30) print(f'Voce digitou os valores {listanum}') print(f'O maior valor digitado foi {maior} nas posicoes', end="") for indice, valor in enumerate(listanum): if valor == maior: print(f'{indice}...', end="") print(f'O maior valor digitado foi {menor}', end="") for indice, valor in enumerate(listanum): if valor == menor: print(f'{indice}...', end="")
# Mortal Fibonacci Rabbits http://rosalind.info/problems/fibd/ # calculate The total number of pairs of rabbits that will remain after the nth month if all rabbits live for m months. # any given month will contain the rabbits that were alive the previous month, plus any new offspring. # the number of offspring in any month is equal to the number of rabbits that were alive two months prior. # all rabbits die out after a fixed number of months. generations = [1, 1] #Seed the sequence with the 1 pair, then in their reproductive month. def fib(n, m): count = 2 while count < n: if (count < m): generations.append((generations[-2]) + generations[-1]) #recurrence relation before rabbits start dying (simply fib seq Fn = Fn-2 + Fn-1) elif (count == m or count == m+1): print ("in base cases for newborns (1st+2nd gen. deaths)") #Base cases for subtracting rabbit deaths (1 death in first 2 death gens) generations.append((generations[-2] + generations[-1]) - 1)#Fn = Fn-2 + Fn-1 - 1 else: generations.append((generations[-2] + generations[-1]) - (generations[-(m+1)])) #Our recurrence relation here is Fn-2 + Fn-1 - Fn-(m+1) count += 1 return (generations, generations[-1]) print (fib(6, 3)) #print ("Here's how the total population looks by generation: \n" + str(generations))
#### reverse a number import math def ReverseNumber(x): reverse = 0 while(x>0): # find the remainder of number on dividing by 10 remainder = x % 10 reverse = (reverse*10) + remainder # find the quotient and assign it as new number x = x/10 return(reverse) #print(ReverseNumber(123)) def Palindrome(x): # if input is integer if type(x) is int: if ReverseNumber(x)==x: #print "%s is palindrome \n" % x return True else: return False # if input is string elif type(x) is str: length = len(x) for i in range(0,(int(length/2))): if x[i] != x[(length-1)-i]: return False return True print(Palindrome(1234321)) print(Palindrome(12345321)) print(Palindrome("MADAM")) print(Palindrome("MADAME"))
__author__ = 'shruti' # to print all numbers which appear more than once in a list x = [1,2,3,4,3,5,6,4,7,8,4,1,1,1] #for i in range(len(x)): # print x[i] NumberDictionary = {} for i in range(len(x)): if x[i] in NumberDictionary: NumberDictionary[x[i]] += 1 else: NumberDictionary[x[i]] = 1 print("dictionary: %s \n" % NumberDictionary) for key, value in dict.items(NumberDictionary): if value>1: print ("number: %i frequency: %i" % (key, value))
# Sign your name: Jarman # This is absolute indent hell, because Python does those types of things. #1. Make the following program work. (3 mistakes) midichlorians = float(input("Enter midichlorian count: ")) # Forgot second parenthesis if midichlorians > 10000: # Forgot the colon print("Serious Jedi potential, you have young padawan.") else: # Had elif, elif could work, but you'd need a circumstance to execute the code, and an else statement after that, so else makes the most sense print("Jedi, you will never be.") # 2. Make the following program work. (3 mistakes) x = float(input("Enter a number: ")) #Takes it as a string by default if x == 3: # Forgot the Colon & need the 'double-equals' print("You entered 3") # 3. Make the following program work. (4 mistakes) answer = input("What is the name of Poe Dameron's Droid? ") if answer == "BB8": # Double equals, and instead of "a" it has to be "answer" print("Correct!") else: # Incorrect indent, and colon print("Incorrect! It is BB8.") # 4. Make the following program work. (4 mistakes) jedi = input("Name one of the top 3 greatest Jedi.") # x should be jedi (jedi on the next line could also be x instead) if jedi == "Yoda" or jedi == "Luke Skywalker" or jedi == "Obi-Wan Kenobi": # need quotes and jedi == every or print("That is correct!") # You had Python 2 syntax, but python3 has parenthesis # 5. Make the following program work whether they enter a, A, Jedi Master or jedi master # Print "Not a choice!" if they don't choose any of the three and set sensitivity to blank text. print("Welcome to the Jedi Academy!") print("A. Jedi Master") print("B. Sith Lord") print("C. Droid") user_input = input("Choose a character?") if user_input == "A": # Double-equals and quotes around A because it is a string sensitivity = 1000 elif user_input == "B": # elif not else if # Double-equals and quotes around B because it is a string sensitivity = 900 elif user_input == "C": # elif not else if # Double-equals and quotes around C because it is a string sensitivity = 0 else: sensitivity = "" print("Not a Choice!") print("Sensitivity: ", str(sensitivity)) # sensitivity, not Sensitivity and don't forget to convert it to a string!
#!/usr/bin/env python # -*- coding: UTF-8 -*- # # Copyright 2016-2021 European Commission (JRC); # Licensed under the EUPL (the 'Licence'); # You may not use this work except in compliance with the Licence. # You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl """ Python equivalents of text Excel functions. """ import functools from . import ( wrap_ufunc, Error, replace_empty, XlError, value_return, flatten, wrap_func, is_not_empty, raise_errors ) FUNCTIONS = {} def _str(text): if isinstance(text, bool): return str(text).upper() if isinstance(text, float) and text.is_integer(): return '%d' % text return str(text) def xfind(find_text, within_text, start_num=1): i = int(start_num or 0) - 1 res = i >= 0 and _str(within_text).find(_str(find_text), i) + 1 or 0 return res or Error.errors['#VALUE!'] _kw0 = dict( input_parser=lambda *a: a, args_parser=lambda *a: map(functools.partial(replace_empty, empty=''), a) ) FUNCTIONS['FIND'] = wrap_ufunc(xfind, **_kw0) def xleft(from_str, num_chars): i = int(num_chars or 0) if i >= 0: return _str(from_str)[:i] return Error.errors['#VALUE!'] FUNCTIONS['LEFT'] = wrap_ufunc(xleft, **_kw0) _kw1 = dict( input_parser=lambda text: [_str(text)], return_func=value_return, args_parser=lambda *a: map(functools.partial(replace_empty, empty=''), a), ) FUNCTIONS['LEN'] = wrap_ufunc(str.__len__, **_kw1) FUNCTIONS['LOWER'] = wrap_ufunc(str.lower, **_kw1) def xmid(from_str, start_num, num_chars): i = j = int(start_num or 0) - 1 j += int(num_chars or 0) if 0 <= i <= j: return _str(from_str)[i:j] return Error.errors['#VALUE!'] FUNCTIONS['MID'] = wrap_ufunc(xmid, **_kw0) def xreplace(old_text, start_num, num_chars, new_text): old_text, new_text = _str(old_text), _str(new_text) i = j = int(start_num or 0) - 1 j += int(num_chars or 0) if 0 <= i <= j: return old_text[:i] + new_text + old_text[j:] return Error.errors['#VALUE!'] FUNCTIONS['REPLACE'] = wrap_ufunc(xreplace, **_kw0) def xright(from_str, num_chars): res = xleft(_str(from_str)[::-1], num_chars) return res if isinstance(res, XlError) else res[::-1] FUNCTIONS['RIGHT'] = wrap_ufunc(xright, **_kw0) FUNCTIONS['TRIM'] = wrap_ufunc(str.strip, **_kw1) FUNCTIONS['UPPER'] = wrap_ufunc(str.upper, **_kw1) def xconcat(text, *args): it = list(flatten((text,) + args, is_not_empty)) raise_errors(it) return ''.join(map(_str, it)) FUNCTIONS['_XLFN.CONCAT'] = FUNCTIONS['CONCAT'] = wrap_func(xconcat) FUNCTIONS['CONCATENATE'] = wrap_ufunc(xconcat, return_func=value_return, **_kw0)
#l = list() #print l #t = (l,l) #print t #l.append(1) #print l #print t class Node: def __init__(self, data): self.left = None self.right = None self.data = data def insert(self, data): if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) else: if self.right is None: self.right = Node(data) else: self.right.insert(data) def main(): root = Node(8) print root.left, root.right, root.data root.insert(3) root.insert(10) root.insert(1) print root.left.left, root.right.right if __name__ == '__main__': main()
number = input('input number: ') number_list = list(str(number)) print(number_list) chs_map = [ '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' ] chs_number_list = [chs_map[int(x)] for x in number_list] print(''.join(chs_number_list))
class Calculator: def calculate(a, b, operator): return eval(str(a) + operator + str(b)) def main(): a = float(input()) b = float(input()) op = input() result = Calculator.calculate(a, b, op) print(result) if __name__ == "__main__": main()
import numpy as np import pla # CS 156a - Fall Term 2018 # Neymika Jain # Below is a rough outline of how I produced the linear regression model used for questions # 5 through 7. Numpy was used to handle vector operations. # Linear Regression: # Generate the target function, using two random points # Create a training set of points with corresponding outputs # Train the model by using the formula for change in w given in Lecture 3: # X_cross = (X^T X)^-1 X^T # Determine the in-sample error, using squared error # Test: # For each run, determine the in-sample error, out-of-sample error, and # pocket model iteration convergence (starting with lin reg weights) # Average these three quantities and print class linreg: def __init__(self, numpoints, d): self.initp = [np.random.uniform(-1.0,1.0,2) for x in range(2)] self.gen_points(numpoints) (x_diff, y_diff) = np.subtract(self.initp[1], self.initp[0]) self.target_slope = y_diff/x_diff self.target_b = self.initp[0][1] - (self.target_slope * self.initp[0][1]) self.Y = np.array([np.sign(x - self.initp[0][0]) for x in self.X]) self.weights = np.zeros((1+d,1)) def gen_points(self, numpoints): self.n = numpoints self.X = np.random.uniform(-1.0,1.0,(self.n, 2)) self.Y = np.array([np.sign(x - self.initp[0][0]) for x in self.X]) def train(self): X_cross = np.c_[np.ones(self.X.shape[0]), self.X] X_inv = np.linalg.pinv(X_cross) self.weights = np.dot(X_inv,self.Y) def e_in(self): xw = np.c_[np.ones(self.X.shape[0]), self.X].dot(self.weights) xw = np.sign(xw) return np.mean(np.not_equal(xw, self.Y)) def linreg_test(runs): N_1, N_2, N_3, d = 100, 1000, 10, 2 ein, eout, iterations = [], [], [] for i in range(runs): lr = linreg(N_1, 2) lr.train() ein.append(lr.e_in()) lr.gen_points(N_2) eout.append(lr.e_in()) iterations.append(pla.PLA_test(N_3, 1, lr.weights, lr.target_slope, lr.target_b)) print("e_in average: %f" % np.average(np.array(ein))) print("e_out average: %f" % np.average(np.array(eout))) print("perceptron convergence average: %f" % np.average(np.array(iterations))) linreg_test(1000)
''' This is a sample that shows how to calculate average of ciphertext. First we will generate message, and encrypt it to ciphertext. In this sample, homomorphic operation is performed in defined function. ''' import heaan import math # Step 1. Setting Parameters params = heaan.Parameters() context = heaan.Context(params) # Step 2. Generating Keys secret_key = heaan.SecretKey(context) public_key_path = "./public_key_path" public_key_pack = heaan.PublicKeyPack(context, secret_key, public_key_path) conj_key = public_key_pack.get_conj_key() enc_key = public_key_pack.get_enc_key() mult_key = public_key_pack.get_mult_key() encryptor = heaan.Encryptor(context) evaluator = heaan.HomEvaluator(context) # Step 3. Generating Messages _list = [i for i in range(128)] msg = heaan.Message(_list) # Step 4. Encrypt Message to Ciphertext ciphertext_a = heaan.Ciphertext() encryptor.encrypt(msg, enc_key, ciphertext_a) def ctxt_average(ciphertext, N) : for i in range(int(math.log(N, 2))) : ciphertext_tmp = heaan.Ciphertext() evaluator.left_rotate(ciphertext, 1 << i, public_key_pack, ciphertext_tmp) evaluator.add(ciphertext, ciphertext_tmp, ciphertext) pass ciphertext_avg = heaan.Ciphertext() evaluator.mult(ciphertext, 1.0 / N, ciphertext_avg) return ciphertext_avg avg = ctxt_average(ciphertext_a, 128) # Step 5. Decrypt Ciphertext to Message decryptor = heaan.Decryptor(context) message_result = heaan.Message() decryptor.decrypt(avg, secret_key, message_result) print(message_result)
import matplotlib.pyplot as plt import numpy as np """ Create Your Own Active Matter Simulation (With Python) Philip Mocz (2021) Princeton Univeristy, @PMocz Simulate Viscek model for flocking birds """ def main(): """ Finite Volume simulation """ # Simulation parameters v0 = 1.0 # velocity eta = 0.5 # random fluctuation in angle (in radians) L = 10 # size of box R = 1 # interaction radius dt = 0.2 # time step Nt = 200 # number of time steps N = 500 # number of birds plotRealTime = True # Initialize np.random.seed(17) # set the random number generator seed # bird positions x = np.random.rand(N,1)*L y = np.random.rand(N,1)*L # bird velocities theta = 2 * np.pi * np.random.rand(N,1) vx = v0 * np.cos(theta) vy = v0 * np.sin(theta) # Prep figure fig = plt.figure(figsize=(4,4), dpi=80) ax = plt.gca() # Simulation Main Loop for i in range(Nt): # move x += vx*dt y += vy*dt # apply periodic BCs x = x % L y = y % L # find mean angle of neighbors within R mean_theta = theta for b in range(N): neighbors = (x-x[b])**2+(y-y[b])**2 < R**2 sx = np.sum(np.cos(theta[neighbors])) sy = np.sum(np.sin(theta[neighbors])) mean_theta[b] = np.arctan2(sy, sx) # add random perturbations theta = mean_theta + eta*(np.random.rand(N,1)-0.5) # update velocities vx = v0 * np.cos(theta) vy = v0 * np.sin(theta) # plot in real time if plotRealTime or (i == Nt-1): plt.cla() plt.quiver(x,y,vx,vy) ax.set(xlim=(0, L), ylim=(0, L)) ax.set_aspect('equal') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.pause(0.001) # Save figure plt.savefig('activematter.png',dpi=240) plt.show() return 0 if __name__== "__main__": main()
# -*- coding: utf-8 -*- """ Created on Wed Sep 06 13:43:40 2017 "Python Machine Learning" Chapter 6 Page: 170-172 working with the Breast Cancer Wisconsin dataset, which contains 569 samples of malignant and benign tumor cells. The first two columns in the dataset store the unique ID numbers of the samples and the corresponding diagnosis (M=malignant, B=benign), respectively. The columns 3-32 contain 30 real-value features that have been computed from digitized images of the cell nuclei, which can be used to build a model to predict whether a tumor is benign or malignant. @author: vincchen """ """ reading in the dataset directly from the UCI website using pandas: """ import pandas as pd df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data', header=None) """ assign the 30 features to a NumPy array X. Using LabelEncoder, we transform the class labels from their original string representation (M and B) into integers: """ from sklearn.preprocessing import LabelEncoder X = df.loc[:, 2:].values y = df.loc[:, 1].values le = LabelEncoder() y = le.fit_transform(y) """ After encoding the class labels (diagnosis) in an array y, the malignant tumors are now represented as class 1, and the benign tumors are represented as class 0, respectively, which we can illustrate by calling the transform method of LabelEncoder on two dummy class labels: """ le.transform(['M', 'B']) """ divide the dataset into a separate training dataset (80 percent of the data) and a separate test dataset (20 percent of the data): """ from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=1) """ standardize the columns in the Breast Cancer Wisconsin dataset before we can feed them to a linear classifier & compress our data from the initial 30 dimensions onto a lower two-dimensional subspace via principal component analysis (PCA) we can chain the StandardScaler, PCA, and LogisticRegression objects in a pipeline: """ from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline pipe_lr = Pipeline([('scl', StandardScaler()), ('pca', PCA(n_components=2)), ('clf', LogisticRegression(random_state=1))]) pipe_lr.fit(X_train, y_train) print('Test Accuracy: %.3f' % pipe_lr.score(X_test, y_test)) """ In the preceding code example, we built a pipeline that consisted of two intermediate steps, a StandardScaler and a PCA transformer, and a logistic regression classifier as a final estimator. When we executed the fit method on the pipeline pipe_lr, the StandardScaler performed fit and transform on the training data, and the transformed training data was then passed onto the next object in the pipeline, the PCA. Similar to the previous step, PCA also executed fit and transform on the scaled input data and passed it to the final element of the pipeline, the estimator. """
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Nov 4 22:31:21 2017 Fractals in TensorFlow @author: Vincent """ import tensorflow as tf import numpy as np import matplotlib.pyplot as plt Y, X = np.mgrid[-1.3:1.3:0.005, -2:1:0.005] Z = X+1j*Y c = tf.constant(Z.astype(np.complex64)) zs = tf.Variable(c) ns = tf.Variable(tf.zeros_like(c, tf.float32)) # instantiate an InteractiveSession(): sess = tf.InteractiveSession() # initialize all the variables involved through the run() method tf.initialize_all_variables().run() # Start the iteration: zs_ = zs*zs + c #Define the stop condition of the iteration: not_diverged = tf.abs(zs_) < 4 # use the group operator that groups multiple operations: step = tf.group(zs.assign(zs_), ns.assign_add(tf.cast(not_diverged, tf.float32))) # run the operator for two hundred step for i in range(200): step.run() # visualize plt.imshow(ns.eval()) plt.show()
# -*- coding: utf-8 -*- """ Created on Tue Aug 15 14:23:15 2017 http://www.runoob.com/python/python-exercise-example27.html Python 练习实例27 Python 100例 Python 100例 题目:利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。 程序分析:无。 @author: vincchen """ s=raw_input('input string') for i in s[::-1]: print i
''' recursion Time: O(n) Space: O(h) ''' class Solution(object): def inorderTraversal(self, root): res = [] if root: res = self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right) return res ''' iteration use a visited flag to facilitate the process Time: O(n) Space: O(h) ''' class Solution(object): def inorderTraversal(self, root): result, stack = [], [(root, False)] while stack: cur, visited = stack.pop() if cur: ## remember to check cur if visited: result.append(cur.val) else: stack.append((cur.right, False)) stack.append((cur, True)) stack.append((cur.left, False)) return result ''' another solution by cleancode ''' class Solution: def inOrder(self, root, list1): stack = [] while stack or root: if root: stack.append(root) root = root.left else: root = stack.pop() list1.append(root.val) root = root.right return list1
def median(vec): if not vec: return None if len(vec) % 2 == 0: return float(vec[len(vec)/2 - 1] + vec[len(vec)/2]) / 2 return vec[len(vec)/2] print median([2, 4, 5]) print median([2, 4, 6, 7])
''' class Solution(object): def subsets(self, nums): results = [] # nums.sort() self.dfs(results, nums, [], 0) return results def dfs(self, res, nums, temp, start): res.append(temp[:]) for i in range(start, len(nums)): temp.append(nums[i]) self.dfs(res, nums, temp, i + 1) temp.pop() print Solution().subsets([1, 2, 3]) ''' ## because python's syntax, it's not neccessary to pass start parameter and backtrack manually for temp list: class Solution(object): def subset(self, nums): results = [] self.dfs(results, nums, []) return results def dfs(self, res, nums, temp): res.append(temp[:]) for i in range(len(nums)): self.dfs(res, nums[i + 1:], temp + [nums[i]]) print Solution().subset([1, 2, 3])
''' make full use of the peek function, also make another temp to collect the reversed data structure ''' class Queue(object): def __init__(self): self.queue = [] self.temp = [] def push(self, x): ### add more to queue, but pop and peek using temp, then temp is empty, reinput the elements in ### in queue to the temp stack reversely self.queue.append(x) def pop(self): self.peek() self.temp.pop() def peek(self): if not self.temp: while self.queue: self.temp.append(self.queue.pop()) return self.temp[-1] def empty(self): return not self.queue
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: maxSumm = float("-inf") def maxSumPath(self, root): self.maxSum(root) return self.maxSumm def maxSum(self, root): if not root: return 0 maxLeft = max(0, self.maxSum(root.left)) maxRight = max(0, self.maxSum(root.right)) self.maxSumm = max(self.maxSumm, root.val + maxLeft + maxRight) return root.val + max(maxLeft, maxRight) if __name__ == "__main__": root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) result = Solution().maxSumPath(root) print result
class Solution: def stairs(self, n): i, j = 1, 1 for k in range(n - 1): i, j = j, i + j return j if __name__ == "__main__": print Solution().stairs(5)
## if check the palindrome of strings then we can use two pointers or ## leverage the string symmetric property ## if for integer we can also make it like string and then reverse it ## if the practice of converting integer to string is deemed as bad ## then use it the other way def isPalindrome(num): if num < 0: return False copy, rev = num, 0 while True: rev *= 10 low = num % 10 rev += low num = num / 10 if num == 0: break return copy == rev def validPalindrome(string): s = filter(lambda x: x.isalnum(), s).lower() return s == s[::-1] def validPalindrome(string): start = 0 end = len(string) - 1 while start < end: while start < end and not string[start].isalnum(): start += 1 while start < end and not string[end].isalnum(): end -= 1 if start < end and string[start].lower() != string[end].lower(): return False start += 1 end -= 1 return True
def isAnagram(s, t): s1 = sorted(s) t1 = sorted(t) return s1 == t1 def isAnagram(s, t): dic1, dic2 = {}, {} for item1 in s: dic1[item1] = dic1.get(item1, 0) + 1 for item2 in t: dic2[item2] = dic2.get(item2, 0) + 1 ## these way we can work around with the 0 problem better return dic1 == dic2 ## use list as a dic with the index as the key def isAnagram(s, t): dic1, dic2 = [0] * 26, [0] * 26 for item in s: dic1[ord(item) - ord('a')] += 1 for item in t: dic2[ord(item) - ord('a')] += 1 return dic1 == dic2
class Solution: def strStr(self, haystack, needle): len1 = len(haystack) len2 = len(needle) if len1 < len2: return -1 for i in range(len1): if i + len2 <= len1: if haystack[i:i+ len1] == needle: return i else: return -1 if len2 == 0: return 0 else: return -1 if __name__ == "__main__": print Solution().strStr("aaba", "ba")
# Question 12 def toss_dice(number_of_sides): "Roll any polygon shape dice and return the rolled value." import random number_of_sides = tidy_user_input((number_of_sides)) for i in number_of_sides: number_of_sides = int(number_of_sides) if number_of_sides >= 4: dice_face_showing = random.randrange(1, number_of_sides) print("Side facing up: ", dice_face_showing) repeat_dice_toss = input("If you would like to try again enter 'y' for yes. \nOr, you can hit any other key if you wish to exit toss_dice mode and move on with the next program: ") print("") if repeat_dice_toss == "y": dice_face_showing = random.randrange(1, number_of_sides) message = ("Dice roll in action... new side of dice facing up: ", dice_face_showing) return message else: number_of_sides = (input("Oops, a dice must have four or more sides, please try again: ")) return toss_dice(number_of_sides) # Question 13 - 1 def turtle_draw_numbers(alexa, cleaned_input): """Draw seven-segment-indicator numbers given user input, making calls to helper functions for each line segment.""" print("Your number to be drawn: ", cleaned_input) for i in cleaned_input: if i == "0": make_line_a(alexa) make_line_b(alexa) make_line_c(alexa) make_line_d(alexa) make_line_e(alexa) make_line_f(alexa) space_between_numbers(alexa) if i == "1": alexa.penup() alexa.forward(2) alexa.pendown() alexa.forward(18) alexa.penup() alexa.forward(2) make_line_b(alexa) make_line_c(alexa) alexa.left(90) alexa.forward(2) alexa.forward(20) alexa.right(180) alexa.pendown() alexa.forward(41) alexa.forward(2) alexa.right(90) forward_2_then_45_(alexa) forward_2_then_45_(alexa) space_between_numbers(alexa) if i == "2": make_line_a(alexa) make_line_b(alexa) forward_2_then_45_(alexa) make_line_d(alexa) make_line_e(alexa) forward_2_then_45_(alexa) make_line_g(alexa) move_turle_zero_position(alexa) space_between_numbers(alexa) if i == "3": make_line_a(alexa) make_line_b(alexa) make_line_c(alexa) make_line_d(alexa) alexa.right(90) forward_2_then_45_(alexa) forward_2_then_45_(alexa) make_line_g(alexa) move_turle_zero_position(alexa) space_between_numbers(alexa) if i == "4": forward_2_then_45_(alexa) make_line_b(alexa) make_line_c(alexa) alexa.right(90) forward_2_then_45_(alexa) alexa.right(90) forward_2_then_45_(alexa) make_line_f(alexa) make_line_g(alexa) move_turle_zero_position(alexa) space_between_numbers(alexa) if i == "5": make_line_a(alexa) alexa.right(90) forward_2_then_45_(alexa) make_line_c(alexa) make_line_d(alexa) alexa.right(90) forward_2_then_45_(alexa) make_line_f(alexa) make_line_g(alexa) move_turle_zero_position(alexa) space_between_numbers(alexa) if i == "6": # forward_2_then_45_(alexa) forward_2_then_45_(alexa) alexa.right(90) forward_2_then_45_(alexa) make_line_c(alexa) make_line_d(alexa) make_line_e(alexa) make_line_f(alexa) make_line_g(alexa) move_turle_zero_position(alexa) space_between_numbers(alexa) if i == "7": make_line_a(alexa) make_line_b(alexa) make_line_c(alexa) alexa.right(90) forward_2_then_45_(alexa) alexa.right(90) forward_2_then_45_(alexa) forward_2_then_45_(alexa) alexa.right(90) space_between_numbers(alexa) if i == "8": make_line_a(alexa) make_line_b(alexa) make_line_c(alexa) make_line_d(alexa) make_line_e(alexa) make_line_f(alexa) make_line_g(alexa) move_turle_zero_position(alexa) space_between_numbers(alexa) if i == "9": make_line_a(alexa) make_line_b(alexa) make_line_c(alexa) alexa.right(90) forward_2_then_45_(alexa) alexa.right(90) forward_2_then_45_(alexa) make_line_f(alexa) make_line_g(alexa) move_turle_zero_position(alexa) space_between_numbers(alexa) # Question 13 - 2 def make_line_a(alexa): """Draw a particular line/segment, "a", that will serve as a building block for the turtle_draw_numbers().""" alexa.penup() alexa.forward(2) alexa.pendown() alexa.forward(45) alexa.penup() alexa.forward(2) # Question 13 - 3 def make_line_b(alexa): """Draw a particular line/segment, "b", that will serve as a building block for the turtle_draw_numbers().""" alexa.right(90) alexa.penup() alexa.forward(2) alexa.pendown() alexa.forward(45) alexa.penup() # Question 13 - 4 def make_line_c(alexa): """Draw a particular line/segment, "c", that will serve as a building block for the turtle_draw_numbers().""" alexa.up() alexa.forward(2) alexa.pendown() alexa.forward(45) alexa.penup() alexa.forward(2) # Question 13 - 6 def make_line_d(alexa): """Draw a particular line/segment, "d", that will serve as a building block for the turtle_draw_numbers().""" alexa.right(90) alexa.pendown() alexa.forward(2) alexa.pendown() alexa.forward(45) alexa.penup() alexa.forward(2) # Question 13 - 7 def make_line_e(alexa): """Draw a particular line/segment, "e", that will serve as a building block for the turtle_draw_numbers().""" alexa.right(90) alexa.pendown() alexa.forward(2) alexa.pendown() alexa.forward(45) alexa.penup() alexa.forward(2) # Question 13 - 8 def make_line_f(alexa): """Draw a particular line/segment, "f", that will serve as a building block for the turtle_draw_numbers().""" alexa.up() alexa.pendown() alexa.forward(45) alexa.penup() alexa.forward(2) # Question 13 - 9 def make_line_g(alexa): """Draw a particular line/segment, "g", that will serve as a building block for the turtle_draw_numbers().""" alexa.right(180) alexa.forward(45) alexa.left(90) alexa.forward(3) alexa.pendown() alexa.forward(42) alexa.penup() alexa.forward(2) # Question 13 - 10 def space_between_numbers(alexa): """Create a spacing funtion that allows for space between numbers drawn by the Turle.""" alexa.penup() alexa.setheading(0) alexa.forward(60) # Question 13 - 11 def move_turle_zero_position(alexa): """Move Python turtle to the zero start position of each number that has just been drawn for set up for next number(the top left cormer of each number).""" alexa.penup() alexa.right(180) alexa.forward(45) alexa.forward(2) alexa.right(90) alexa.forward(45) # Question 13 - 12 def forward_2_then_45_(alexa): """Move Turtle forward with no lines drawn to position for next drawn move.""" alexa.penup() alexa.forward(2) alexa.forward(45) def delay_turtle(): """Delay start of Python Turtle module. This gives the user time to read instructions & usefull info to user on what to expect from the behavior of the program.""" import time for i in range(1): print("*** Note - Python Turtle will commence in 5 seconds.***") print("To exit the Python Turtle screen, click on the Turle sand-box when drawing is complete.") print("This will allow the rest of the code in this module to execute...\nHappy code viewing!") time.sleep(5) # Shared function for question 12 & 13 def tidy_user_input(user_str): """Tidy up user string input, check if string can be converted to integers.""" numbers_to_draw = user_str.strip(" ") numbers_to_draw = numbers_to_draw.replace(" ", "") if numbers_to_draw.isdigit(): return numbers_to_draw else: user_input = input("Hmmmmm, that's not a number. Please try again: ") return tidy_user_input(user_input) def main(): #Question 12 print("Play the roll your own dice game.") number_of_sides = input("Please enter in the number of faces on your dice, it must have at lest four sides: ") print(toss_dice(number_of_sides)) print("\n") delay_turtle() # # Question 13 import turtle screen = turtle.Screen() alexa = turtle.Turtle() alexa.shape("turtle") alexa.speed(4) alexa.penup() alexa.pendown() print("\n") print("Python Turtle wants to draw out your number like a seven-segment-indicator!") # Question 13 - 2 user_str = input("Please give the Python Turtle a number you want her to draw, eg. 415, or 2, or even 0169: ") cleaned_input = tidy_user_input(user_str) turtle_draw_numbers(alexa, cleaned_input) screen.exitonclick() main()
def draw_polygon(side_length, number_sides, alexa): """ draw a polygon""" angle = 360/number_sides for i in range(number_sides): turtle.forward(side_length) turtle.left(angle) def main(): import turtle wn = turtle.Screen() alexa = turtle.Turtle() draw_polygon(40, 3, alexa) main()
""" Write a Python function to print a geometric progression (Links to an external site.) Links to an external#site. of a given first term (a)(start), common ratio (r)(stop) and number of terms(n)(step). A geometric progression is a sequence of numbers where each term after the first is found by multiplying the previous one by a fixed, non-zero number called the common ratio. Use your function to generate all the powers of 2 from 2 to 512 like in one line like 2, 4, 8, ..... 512 "a" is the start number "r" the stop number "n" is the step by number """ def geo_progression_1(a, r, n): """ Prints a gemoteric series of numbers """ term = a for i in range(1, n): # here n is how nth term print(term, end =", ") term *= r # Every term is r times the previous term def geo_progression_2(a, r, end): """ Prints a gemoteric series of numbers """ term = a while term <=512: # here end means the last or the nth term print(term, end =", ") term *= r def main(): geo_progression1(2, 2, 10) geo_progression2(2, 2, 512) main()
array1= [{"test1":21, "test2":22},{"test1":21, "test2":22},{"test1":21, "test2":22},{"test1":21, "test2":22}] wholelist1=[] for x in array1: templist1=[] templist2=[] templist3=[] templwholelist1=[] for values in x.keys(): templist1+=[values] for keys in x.values(): templist2+=[keys] for y in range(len(x)): if y <len(x)-1: templwholelist1+=[str(templist1[y])+":"+str(templist2[y])+", "] if y==len(x)-1: templwholelist1+=[str(templist1[y])+":"+str(templist2[y])] wholelist1+=[templwholelist1] print(wholelist1) #print(wholelist1)
# -*- coding: utf-8 -*- def mensagem_e_chave(): texto = open(sys.argv[1], 'r').read() chave = open(sys.argv[2], 'r').read() chave_map = " " j = 0 for i in range(len(texto)): if ord(texto[i]) == 32: # Por que 32? chave_map += " " else: if j < len(chave): chave_map += chave[j] j += 1 else: j = 0 chave_map += chave[j] j += 1 # print(chave_map) return mensagem, chave_map def criando_tabela_de_Vigenere(): table = [] for i in range(26): table.append([]) for row in range(26): for column in range(26): if (row + 65) + column > 90: table[row].append(chr((row + 65) + column - 26)) else: table[row].append(chr((row + 65) + column)) for row in table: for column in row: print(column, end = ' ') print(end = "\n") return table def mensagemCifrada( mensagemFinal, chave_mapeada ): table = criando_tabela_de_Vigenere() textoEncriptado = " " for i in range(len(mensagemFinal)): if mensagemFinal[i] == chr(32): textoEncriptado += " " else: row = ord(mensagemFinal[i] - 65) column = ord(chave_mapeada[i]) - 65 textoEncriptado += table[row][column] print(" Mensagem Encriptada: []".format(textoEncriptado)) def itr_count(chave_mapeada, mensagemFinal): counter = 0 result = " " def mensagemDecifrada( mensagemFinal, chave_mapeada): table = criando_tabela_de_Vigenere() textoDecriptado = " " for i in range(len(mensagemFinal)): if mensagemFinal[i] == chr(32): textoDecriptado += " " else: textoDecriptado += chr(65 + itr_count(ord(chave_mapeada[i]), ord(mensagemFinal[i]))) print(" Mensagem Decriptada: []".format(textoDecriptado)) def main(): print("Chave e Mensagem podem apenas serem alfabéticas.") processo = int(input(" 1 - Encriptar.\n 2 - Decriptar.\n Escolha 1 ou 2.")) if processo == 1: print(" --- Encriptação --- ") mensagemFinal, chaveFinal = mensagem_e_chave() mensagemCifrada( mensagemFinal, chave_mapeada ) elif processo == 2: print(" --- Decriptação --- ") MensagemFinal, chaveFinal = mensagem_e_chave() mensagemDecifrada(mensagemFinal, chave_mapeada) else: print(" Escolha errada! ") if __name__ == "__principal__": main()
# 包含min的栈 # 定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数 ##### 时间复杂度应为O(1)。#### ###################################################################### # -*- coding:utf-8 -*- class Solution: def __init__(self): self.stack = [] self.minstack = [] def push(self, node): self.stack.append(node) if not self.minstack: self.minstack.append(node) elif node < self.minstack[0]: self.minstack[0] = node # write code here def pop(self): if not self.stack: return None if len(self.stack) == 1: self.minstack.pop() return self.stack.pop() if self.stack[-1] > self.minstack: return self.stack.pop() else: self.minstack[0] = self.stack[0] for i in range(len(self.stack)-1): if self.stack[i] < self.minstack[0]: self.minstack[0] = self.stack[i] return self.stack.pop() # write code here def top(self): if not self.stack: return None return self.stack[-1] # write code here def min(self): if not self.stack: return None return self.minstack[0] # write code here ######################################################################
# 快速排序,基准点左右交换,有序时效果变为冒泡排序,时间:O(nlogn)-O(n^2);空间:O(logn)。 def quick_sort(array,left,right): if left >= right: return array key = array[left] low = left high = right while left < right: while left < right and array[right] >= key: right = right - 1 array[left] = array[right] while left < right and array[left] <= key: left = left + 1 array[right] = array[left] array[right] = key quick_sort(array,low,right-1) quick_sort(array,right+1,high) return array if __name__ == '__main__': a = [13,65,97,76,38,27,49] sorted_a = quick_sort(a,0,len(a)-1)
# 旋转数组的最小数字 # 把一个数组最开始的若干个元素搬到数组的末尾, # 我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转, # 输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转, # 该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。 ###################################################################### # -*- coding:utf-8 -*- class Solution: def minNumberInRotateArray(self, rotateArray): # 暴力法 # for i in range(len(rotateArray)): # if rotateArray[i] > rotateArray[i+1]: # return rotateArray[i+1] # 双指针二分查找 left = 0 right = len(rotateArray) - 1 while left + 1 < right: mid = int((left + right) / 2) if rotateArray[mid] >= rotateArray[left]: left = mid else: right = mid return min(rotateArray[left], rotateArray[right]) # write code here ###################################################################### s = Solution() array = [11,12,13,14,15,16,17,18,19,20,21,22,23,44,55,66,77,88,1,2,3,4,5,6,7,8,9,10] res = s.minNumberInRotateArray(array) # 注意非减数列
# 给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。 # # 返回被除数 dividend 除以除数 divisor 得到的商。 # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/divide-two-integers # 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ###################################################################### def divide(dividend, divisor): sign = (dividend > 0) ^ (divisor > 0) dividend = abs(dividend) divisor = abs(divisor) count = 0 # 把除数不断左移,直到它大于被除数 while dividend >= divisor: count += 1 divisor <<= 1 result = 0 while count > 0: count -= 1 divisor >>= 1 if divisor <= dividend: result += 1 << count # 这里的移位运算是把二进制(第count+1位上的1)转换为十进制 dividend -= divisor if sign: result = -result return result if -(1 << 31) <= result <= (1 << 31) - 1 else (1 << 31) - 1 ###################################################################### dividend = 45 divisor = 2 result = divide(dividend,divisor) print(result)
# 将两个有序链表合并为一个新的有序链表并返回。 # 新链表是通过拼接给定的两个链表的所有节点组成的。 ###################################################################### def mergeTwoLists(l1,l2): # head = ListNode(0) # dummy = head # while l1 is not None and l2 is not None: # if l1.val < l2.val: # dummy.next = ListNode(l1.val) # l1 = l1.next # dummy = dummy.next # else: # dummy.next = ListNode(l2.val) # l2 = l2.next # dummy = dummy.next # dummy.next = l2 if l2 else l1 # return head.next #递归 if l1 is None: return l2 elif l2 is None: return l1 elif l1.val < l2.val: l1.next = mergeTwoLists(l1.next, l2) return l1 else: l2.next = mergeTwoLists(l1, l2.next) return l2 ###################################################################### class ListNode: def __init__(self, x): self.val = x self.next = None def ToListNode(l): reason = ListNode(0) list = reason for num in l: list.next = ListNode(int(num)) list = list.next return reason.next ###################################################################### L1 = [1,2,4] L2 = [1,3,4] L1 = ToListNode(L1) L2 = ToListNode(L2) result = mergeTwoLists(L1,L2) print(result)
# -*- coding:utf-8 -*- class Solution: def FindContinuousSequence(self, tsum): if tsum < 3: return [] small = 1 big = 2 middle = (tsum + 1)>>1 curSum = small + big output = [] while small < middle: if curSum == tsum: output.append(range(small, big+1)) big += 1 curSum += big elif curSum > tsum: curSum -= small small += 1 else: big += 1 curSum += big return output # num = 2 # res = [] # while tsum / num - (num // 2) > 0: # if num % 2 == 0: # if tsum / num - 0.5 == tsum // num: # s = tsum // num # res.insert(0,range(s - (num-1)//2,s + num//2+1)) # else: # if tsum / num == tsum // num: # s = tsum // num # res.insert(0,range(s - num//2, s + num // 2+1)) # num = num + 1 # return res # write code here if __name__ == '__main__': s = Solution() r = s.FindContinuousSequence(3) print(r)
# 顺时针打印矩阵 # 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字, # 例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 # 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. ###################################################################### # -*- coding:utf-8 -*- class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): i = 0 j = -1 l = 0 circle = 1 res = [] set_i = [0, 1, 0, -1] set_j = [1, 0, -1, 0] row, column = len(matrix), len(matrix[0]) total_number = row * column row = row - 1 se = 0 while total_number > 0: setting = se % 4 if circle % 2 == 1: while l < column: i = i + set_i[setting] j = j + set_j[setting] res.append(matrix[i][j]) l = l + 1 total_number = total_number - 1 column = column - 1 else: while l < row: i = i + set_i[setting] j = j + set_j[setting] res.append(matrix[i][j]) l = l + 1 total_number = total_number - 1 row = row - 1 circle = circle + 1 se = se + 1 l = 0 return res # write code here ######################################################################
# 一个黑板上写着一个非负整数数组 nums[i] 。 # 小红和小明轮流从黑板上擦掉一个数字,小红先手。 # 如果擦除一个数字后,剩余的所有数字按位异或运算得出的结果等于 0 的话,当前玩家游戏失败。  # (另外,如果只剩一个数字,按位异或运算得到它本身;如果无数字剩余,按位异或运算结果为0。) # 换种说法就是,轮到某个玩家时,如果当前黑板上所有数字按位异或运算结果等于 0,这个玩家获胜。 # 假设两个玩家每步都使用最优解,当且仅当小红获胜时返回 true。 ###################################################################### def xorGame(nums): re = 0 for i in nums: re = re ^ i if re == 0: return True else: if len(nums) % 2 == 0: return True else: return False pass ###################################################################### # 小红必胜的可能性为,先手异或为0,或nums中的元素为偶数,其他才有可能小明胜利。 nums = [1,1,2,3] result = xorGame(nums)
# Based on Mark Pilgrim - Dive Into Python 3 import re ROMAN_NUMS = ("I", "V", "X", "L", "C", "D", "M") ROMAN_NUM_MAP = (("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C", 100), ("XC", 90), ("L", 50), ("XL", 40), ("X", 10), ("IX", 9), ("V", 5), ("IV", 4), ("I", 1)) ROMAN_REPAT = re.compile(""" ^ # start of string M{0,3} # thousands, 1-3 M (CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), # 0-300 (0-3 C), or # 500-800 (D + 1-3 C) (XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), # 0-30 (0-3 X), or # 50-80 (L + 0-3 X) (IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0-3 I), # or 5-8 (V + 0-3 I) $ # end of string """, re.VERBOSE) def to_roman(val): """ Converts an integer to a roman numeral. Example: >>> to_roman("2013") 'MMXIII' """ integer, result = int(val), "" if not (0 < integer < 4000): raise ValueError("Value must be between 0 and 4000") for roman_num, roman_integer in ROMAN_NUM_MAP: while integer >= roman_integer: result += roman_num integer -= roman_integer return result def from_roman(s, accept_lower=False): """ Converts a roman numeral to an integer. Examples: >>> from_roman("MMXIII") 2013 >>> from_roman("mmxiii", True) 2013 """ if not s: raise ValueError("Empty string") result, i = 0, 0 if accept_lower: s = s.upper() if not ROMAN_REPAT.search(s): raise ValueError("Invalid roman numeral") for roman_num, roman_integer in ROMAN_NUM_MAP: while s[i:i+len(roman_num)] == roman_num: result += roman_integer i += len(roman_num) return result
""" Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index. Example 1: Input: nums = [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: Input: nums = [2,3,0,1,4] Output: 2 Constraints: 1 <= nums.length <= 104 0 <= nums[i] <= 1000 """ class Solution: def jump(self, nums: List[int]) -> int: # 记录到每个位置需要多少步 if not nums: return 0 dp = [float("inf")] * len(nums) dp[0] = 0 for i, step in enumerate(nums): for j in range(i+1, i+step+1): if j < len(dp): dp[j] = min(dp[i]+1, dp[j]) return dp[-1]
""" 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 ) 示例 1: 输入: ["CQueue","appendTail","deleteHead","deleteHead"] [[],[3],[],[]] 输出:[null,null,3,-1] 示例 2: 输入: ["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"] [[],[],[5],[2],[],[]] 输出:[null,-1,null,null,5,2] """ class CQueue: def __init__(self): self.stack = [] self.temp = [] def appendTail(self, value: int) -> None: self.stack.append(value) def deleteHead(self) -> int: if not self.stack: return -1 while self.stack: self.temp.append(self.stack.pop()) res = self.temp.pop() while self.temp: self.stack.append(self.temp.pop()) return res # Your CQueue object will be instantiated and called as such: # obj = CQueue() # obj.appendTail(value) # param_2 = obj.deleteHead()