text
stringlengths
37
1.41M
#Programming exercises chapter 3 # exercise 10 # A program to determine the length of a ladder def main(): print("The length of a ladder required to reach a given height") import math from math import pi height = eval(input("Enter the height of the house: ")) angle = eval(input(" Enter the angle of the ladder in degrees: ")) radians = (pi / 180) * angle length = height / radians print("The length is:", length) main()
# KMtoM # THis is a program that converts distances measured in kilometers to miles def main(): kilometers = eval(input("What is the length in kilometers? ")) miles = 0.62 * kilometers print("the lenght in miles is: ", miles) main()
# Programming exercises chapter 5 # exercise 9 # A program that counts the numbers of words in a sentence def main(): print("A program that counts the numbers of words") words = input("Enter a sentence: ") count = 0 for string in words.split(): count = count + 1 print("There are", count, "words in your text") main()
# Programming exercises chapter 7 # exercise 9 # A program for computing easter dates in the years 1982-2048 def main(): year = eval(input("Enter a year between 1982 and 2048: ")) if 1982 <= year <= 2048: a = year % 19 b = year % 4 c = year & 7 d = (19 * a + 24) % 30 e = (2 * b + 4 * c + 6 * d + 5) % 7 day = 22 + d + e else: print("Please enter a year between 1982 - 2048: ") if day > 31: print("Easter falls into April", day - 31, "in the year", year) else: print("Easter falls into March", day, "in the year", year) main()
# Programming exercises chapter 11 #exercise 10 # sieve of eratosthenes import math def main(): number = int(input("Please enter a number: ")) primes = [] for i in range(2,number+1): primes.append(i) i = 2 while(i <= int(math.sqrt(number))): if i in primes: for x in range(i*2, number+1, i): if x in primes: primes.remove(x) i = i+1 print("All the prime numbers before",number,"are", primes) main() # does not remove stuff yet.
# Programming exercises chapter 3 # exercise 13 # A program to sum a series of numbers entered by the user def main(): print("The sum of a series of numbers.") n = int(input("How many numbers are to be summed: ")) sum = 0 for i in range(n): x = eval(input("Enter a natural number: ")) sum = x + sum print("Sum of",n ,"numbers is", sum) main()
# Programming exercises chapter 7 # exercise 2 def main(): score = eval(input("Enter your points: ")) if score == 5: print("A") elif score == 4: print("B") elif score == 3: print("C") elif score == 2: print("D") elif score <= 1: print("F") main()
#Programming exercises chapter 3 # exercise 5 # A program to calculate the cost of an order at the Konditorei coffee shop. def main(): print("A calculation for the cost of an order at the Konditorei.") pound = eval(input("How many pounds of coffee are you ordering: ")) total = pound * 10.50 + pound * 0.86 + 1.50 print("The total cost is:", total, ("Euros")) main()
x = 0 while x <= 5: print(x) x = x + 1 counties = ["Arapahoe", "Denver", "Jefferson"] for county in counties: print(county) numbers = [0,1,2,3,4] for num in numbers: print(num) for i in range(len(counties)): print(counties[i]) counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438} for county in counties_dict: print(county) for county in counties_dict.keys(): print(county) # for key, value in dictionary_name.items(): # print(key, value) for county, voters in counties_dict.items(): print(county, voters) voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}] for county_dict in voting_data: print(county_dict) for county_dict in voting_data: for value in county_dict.values(): print(value) for county, voters in counties_dict.items(): print(county + " county has " + str(voters) + " registered voters.") # These two are the same code for county, voters in counties_dict.items(): print(f"{county} county has {voters} registered voters.") #candidate_votes = int(input("How many votes did the candidate get in the election? ")) #total_votes = int(input("What is the total number of votes in the election? ")) #message_to_candidate = ( # f"You received {candidate_votes} number of votes. " # f"The total number of votes in the election was {total_votes}. " # f"You received {candidate_votes / total_votes * 100}% of the total votes.") #print(message_to_candidate) # f'{value:{width}.{precision}}'
import math class Buffer(object): def __init__(self, source): self.index = 0 self.source = source self.lines = [] self.current_line = () self.current() def pop(self): current = self.current() self.index += 1 return current @property def more_on_line(self): return self.index < len(self.current_line) def current(self): while not self.more_on_line: self.index = 0 try: self.current_line = next(self.source) self.lines.append(self.current_line) except StopIteration: self.current_line = () return None return self.current_line(self.index) def __str__(self): """Return recently read contents; current element marked with >>.""" # Format string for right-justified line numbers n = len(self.lines) msg = '{0:>' + str(math.floor(math.log10(n))+1) + "}: " #Up to three previous lines and current line are included in output s = '' for i in range(max(0, n-4), n-1): s += msg.format(i+1) + ' '.join(map(str, self.lines[i])) + '\n' s += msg.format(n) s += ' '.join(map(str, self.current_line[:self.index])) s += ' >> ' s += ' '.join(map(str, self.current_line[self.index:])) return s.strip() class InputReader(object): """An InputReader is an iterable that prompts the user for input.""" def __init__(self, prompt): self.prompt = prompt def __iter__(self): while True: yield input(self.prompt) self.prompt = ' ' * len(self.prompt)
from collections import namedtuple CitiesRow = namedtuple("Row", ["latitude", "longitude", "name"]) cities = [CitiesRow(38, 122, "Berkeley"), CitiesRow(42, 71, "Cambridge"), CitiesRow(43, 93, "Minneapolis")] DistancesRow = namedtuple("Row", ["name", "distance"]) def select(cities_row): latitude, longitude, name = cities_row return DistancesRow(name, 60*abs(latitude-38))
empty = 'empty' def mutable_link(): """Return a functional implementation of a mutable linked list.""" contents = empty def dispatch(message, value = None): nonlocal contents if message == 'len': return len_link(contents) elif message == 'getitem': return getitem_link(contents, value) elif message =='push_first': contents = link(value, contents) elif message == 'pop_first': f = first(contents) contents = rest(contents) return f elif message == 'str': return join_link(contents, ", ") return dispatch def to_mutable_link(source): """Return a functional list with the same contents as source""" s = mutable_link() for element in reversed(source): s('push_first', element) return s
#__*__ encoding:utf8 __*__ """12. Leia vários códigos do jogador (1 ou 2) que ganhou o ponto, em uma partida de pingue-pongue, e responda quem ganha a partida. A partida chega ao final se: · Um dos jogadores chega a 21 pontos e a diferença de pontos entre os jogadores é maior ou igual a 2. · Se a primeira não for atendida, ganha aquele que, com mais de 21 pontos, consiga colocar uma diferença de 2 pontos sobre o adversário.""" def main(): ponto_jogador1 = 0 ponto_jogador2 = 0 diferenca1 = 0 diferenca2 = 0 while True: codigo = input('Digite o codigo (1 ou 2) quem ganhou o ponto: ') if codigo == 1: ponto_jogador1 = ponto_jogador1 + 1 elif codigo == 2: ponto_jogador2 = ponto_jogador2 + 1 diferenca1 = ponto_jogador1 - ponto_jogador2 diferenca2 = ponto_jogador2 - ponto_jogador1 if ponto_jogador1 == 21 and diferenca1 >= 2: print('O ganhador foi o jogador 1') print('Fim') break elif ponto_jogador2 == 21 and diferenca2 >= 2: print('O ganhador foi o jogador 2') print('Fim') break else: if ponto_jogador1 >= 21 and diferenca1 >= 2: print('O ganhador foi o jogador 1') print('Fim') break elif ponto_jogador2 >= 21 and diferenca2 >= 2: print('O ganhador foi o jogador 2') print('Fim') break if __name__ == '__main__': main()
def main(): idade = input('digite sua idade: ') soma_idade_otimo = 0 qtd_otimo = 0 qtd_regular = 0 qtd_total = 0 qtd_bom = 0 while idade > 0: op = int(input('digite sua opniao: ')) qtd_total = qtd_total + 1 if op == 1: soma_idade_otimo = soma_idade_otimo + idade qtd_otimo = qtd_otimo + 1 elif op == 2: qtd_bom = qtd_bom + 1 elif op == 3: qtd_regular = qtd_regular + 1 idade = input('digite sua idade: ') #Apurar os resultados media_idade_otimo = soma_idade_otimo / float(qtd_otimo) percetual_bom = (qtd_bom / float(qtd_total)) * 100.0 #Resultados print 'A media das idades das pessoas que responderam otimo = %.2f' % media_idade_otimo print 'a quantidade de pessoas que respondeu regular = %d' % qtd_regular print 'o percentual de pessoas que respondeu bom = %.1f %%' % percetual_bom if __name__ == '__main__': main()
"""43. Um sistema de equacoes lineares do tipo , pode ser resolvido segundo mostrado abaixo Escreva um algoritmo que leia os coeficientes a, b, c, d, e e f, calcule e escreva os valores de x e y.""" a = input ('Digite o valor de a: ') b = input ('\nDigite o valor de b: ') c = input ('\nDigite o valor de c: ') d = input ('\nDigite o valor de d: ') e = input ('\nDigite o valor de e: ') f = input ('\nDigite o valor de f: ') x = (c * e - b * f) / (a * e - b * d) y = (a * f - c * d) / (a * e - b * d) print ('\nO valor de x e %.2f ') % (x) print ('\nO valor de y e %.2f ') % (y)
from Questao06_funcoes import * def main(): bd_alunos = [] bd_alunos += inicializar_alunos() while True: menu = ' 1 - Listar \n 2 - Buscar \n 0 - Sair \n Opcao: ' opcao = int(input(menu)) if opcao == 1: while True: menu1 = ' 1 - Listar tabela com as notas, media e situacao \n'\ ' 2 - Listar tabela com contagem e percentual por situacao \n'\ ' 3 - Listar tabela ordenada por nota em ordem decrescente \n'\ ' 0 - Sair \n Opcao: ' resposta = int(input(menu1)) if resposta == 1: listar_notas_media_situacao(bd_alunos) elif resposta == 2: listar_contagem_e_percentual_por_situação(bd_alunos) elif resposta == 3: menu2 = ' 1 - Listar todos \n 2 - Listar um quantidade desejada \n'\ ' 0 - Sair \n Opcao: ' chave = int(input(menu2)) if chave == 1: listar_tabela_ordenada_por_nota_decrescente_todos(bd_alunos) elif chave == 2: quantidade_desejadas = int(input('Quantidade que deseja listar: ')) listar_tabela_ordenada_por_nota_decrescente_quantidade_desejadas(bd_alunos,quantidade_desejadas) elif chave == 0: break elif resposta == 0: break elif opcao == 2: while True: menu3 = ' 1 - Buscar alunos por parte do nome\n'\ ' 2 - Buscar alunos por faixa de nota\n'\ ' 3 - Buscar alunos por media considerando apenas os alunos Ativos\n'\ ' 0 - Sair \n Opcao: ' escolha = int(input(menu3)) if escolha == 1: parte_nome = input('Parte do nome: ') buscar_alunos_por_parte_nome(bd_alunos,parte_nome) elif escolha == 2: faixa_nota = float(input('Faixa de notas:')) buscar_alunos_por_faixa_nota(bd_alunos,faixa_nota) elif escolha == 3: faixa_nota_a = float(input('Faixa de medias: ')) buscar_alunos_A_por_media_(bd_alunos,faixa_nota_a) elif escolha == 0: break elif opcao == 0: salvar_alunos(bd_alunos) break if __name__ == '__main__': main()
"""13. Leia N e uma lista de N numeros e escreva o maior numero da lista.""" def main(): numero_n = input('Digite o valor de N: ') maior = 0 for i in range(1,numero_n+1): lista_numero_n = input('Digite um numero: ') if i == 1: maior = lista_numero_n else: if lista_numero_n > maior: maior = lista_numero_n print maior if __name__ == '__main__': main()
def main(): n_1 = 1 n_2 = 1 total = 0 for i in range(50): print('%d/%d' % (n_1, n_2)) total = total + (n_1/n_2) n_1 += 2 n_2 += 1 print('Total : %.2f.' % total) if __name__ == '__main__': main()
#__*__ encoding:utf8 __*__ """16. O Hipermercado Tabajara está com uma promoção de carnes que é imperdível. Confira: Até 5 Kg Acima de 5 Kg File R$ 4,90 por Kg R$ 5,80 por Kg Alcatra R$ 5,90 por Kg R$ 6,80 por Kg Picanha R$ 6,90 por Kg R$ 7,80 por Kg Para atender a todos os clientes, cada cliente poderá levar apenas um dos tipos de carne da promoção, porém não há limites para a quantidade de carne por cliente. Se compra for feita no cartão Tabajara o cliente receberá ainda um desconto de 5% sobre o total a compra. Escreva um programa que peça o tipo e a quantidade de carne comprada pelo usuário e gere um cupom fiscal, contendo as informações da compra: tipo e quantidade de carne, preço total, tipo de pagamento, valor do desconto e valor a pagar.""" def main(): tipo_carne = raw_input('Digite o tipo de carne: ') quantidade_carne = input('Digite a quantidade de carne: ') tipo_pagamento = raw_input('Digite o tipo de pagamento cartao ou dinheiro: ') print(' Cupom Fiscal \n') print(' Hipermecado Tabajara \n') preco_total_desconto = 0 preco_total_sem_desconto = 0 desconto = 0 if tipo_pagamento == 'cartao': print(' A compra teve descontos\n') if tipo_carne == 'File' or tipo_carne == 'file': if quantidade_carne <= 5: preco_total_sem_desconto = quantidade_carne * 4.9 elif quantidade_carne > 5: preco_total_sem_desconto = quantidade_carne * 5.8 desconto = preco_total_sem_desconto * 0.05 preco_total_desconto = preco_total_sem_desconto - desconto print(' Tipo de carne comprada %s') % tipo_carne print(' A quantidade de comprada %.2f') % quantidade_carne print(' O preco total %.2f') % preco_total_sem_desconto print(' O tipo de pagamento %s') % tipo_pagamento print(' O valor do desconto %.2f') % desconto print(' O total a pagar eh %.2f ') % preco_total_desconto elif tipo_carne == 'Alcatra' or tipo_carne == 'alcatra': if quantidade_carne <= 5: preco_total_sem_desconto = quantidade_carne * 5.9 elif quantidade_carne > 5: preco_total_sem_desconto = quantidade_carne * 6.8 desconto = preco_total_sem_desconto * 0.05 preco_total_desconto = preco_total_sem_desconto - desconto print(' Tipo de carne comprada %s') % tipo_carne print(' A quantidade de comprada %.2f') % quantidade_carne print(' O preco total %.2f') % preco_total_sem_desconto print(' O tipo de pagamento %s') % tipo_pagamento print(' O valor do desconto %.2f') % desconto print(' O total a pagar eh %.2f ') % preco_total_desconto elif tipo_carne == 'Picanha' or tipo_carne == 'picanha': if quantidade_carne <= 5: preco_total_desconto = quantidade_carne * 5.9 elif quantidade_carne > 5: preco_total_sem_desconto = quantidade_carne * 6.8 desconto = preco_total_sem_desconto * 0.05 preco_total_desconto = preco_total - desconto print(' Tipo de carne comprada %s') % tipo_carne print(' A quantidade de comprada %.2f') % quantidade_carne print(' O preco total %.2f') % preco_total_sem_desconto print(' O tipo de pagamento %s') % tipo_pagamento print(' O valor do desconto %.2f') % desconto print(' O total a pagar eh %.2f ') % preco_total_desconto elif tipo_pagamento == 'dinheiro': print(' A compra nao teve descontos\n') if tipo_carne == 'File' or tipo_carne == 'file': if quantidade_carne <= 5: preco_total_sem_desconto = quantidade_carne * 4.9 elif quantidade_carne > 5: preco_total_sem_desconto = quantidade_carne * 5.8 print(' Tipo de carne comprada %s') % tipo_carne print(' A quantidade de comprada %.2f') % quantidade_carne print(' O preco total %.2f') % preco_total_sem_desconto print(' O tipo de pagamento %s') % tipo_pagamento print(' O total a pagar eh %.2f ') % preco_total_sem_desconto elif tipo_carne == 'Alcatra' or tipo_carne == 'alcatra': if quantidade_carne <= 5: preco_total_sem_desconto = quantidade_carne * 5.9 elif quantidade_carne > 5: preco_total_sem_desconto = quantidade_carne * 6.8 print(' Tipo de carne comprada %s') % tipo_carne print(' A quantidade de comprada %.2f') % quantidade_carne print(' O preco total %.2f') % preco_total_sem_desconto print(' O tipo de pagamento %s') % tipo_pagamento print(' O total a pagar eh %.2f ') % preco_total_sem_desconto elif tipo_carne == 'Picanha' or tipo_carne == 'picanha': if quantidade_carne <= 5: preco_total_sem_desconto = quantidade_carne * 5.9 elif quantidade_carne > 5: preco_total_sem_desconto = quantidade_carne * 6.8 print(' Tipo de carne comprada %s') % tipo_carne print(' A quantidade de comprada %.2f') % quantidade_carne print(' O preco total %.2f') % preco_total_sem_desconto print(' O tipo de pagamento %s') % tipo_pagamento print(' O total a pagar eh %.2f ') % preco_total_sem_desconto if __name__ == '__main__': main()
def calcula_salario(qtd_horas, valor_hora): salario = qtd_horas * valor_hora return salario def main(): print '$$$ Calcula Salario $$$' valor_hora_prof1 = input('Valor do hora Prof1: ') qtd_horas_prof1 = input('Horas Prof1: ') valor_hora_prof2 = input('Valor do hora Prof2: ') qtd_horas_prof2 = input('Horas Prof2: ') salario_prof1 = calcula_salario(qtd_horas_prof1, valor_hora_prof1) salario_prof2 = calcula_salario(qtd_horas_prof2, valor_hora_prof2) #Compara os salarios print 'Professor 1 ganha R$ %.2f' % salario_prof1 print 'Professor 2 ganha R$ %.2f' % salario_prof2 if salario_prof1 > salario_prof2: print 'Professor 1 ganha mais.' elif salario_prof1 < salario_prof2: print 'Professor 2 ganha mais.' else: print 'Salario sao iguais.' if __name__ == '__main__': main()
"""4. Leia o valor do dolar e um valor em dolar, calcule e escreva o equivalente em real (R$).""" cotacao = input("Digite a cotacao: ") valor_dolar = input("Digite o valor em dolar: ") valor_reais = cotacao * valor_dolar print "O valor %.2f dolares com cotacao a %.2f equivale a %.2f reais" %(valor_dolar, cotacao, valor_reais)
def verifica_data(dia,mes,ano): if dia > 0 and dia <= 31: if mes > 0 and mes <= 12: if ano > 0: return "data valida" return "data invalida" def main(): print 'programa verifica data valida:' dia = int(raw_input('digite o dia: ')) mes = int(raw_input('digite o mes: ')) ano = int(raw_input('digite o ano: ')) resultado = verifica_data(dia,mes,ano) print resultado if __name__ == '__main__': main()
#__*__ encoding:utf8 __*__ """1. Leia uma velocidade em m/s, calcule e escreva esta velocidade em km/h. (Vkm/h = Vm/s * 3.6)""" def calcula_velocidade(velocidade): velocidade_total = velocidade * 3.6 return velocidade_total def main(): velocidade = input ('Digite a velocidade em m/s: ') velocidade_total = 0 velocidade_total = calcula_velocidade(velocidade) print velocidade_total if __name__ == '__main__': main()
""" Numero pares entre 1 e N """ def main(): qtd = input('N: ') for i in range(2, qtd+1, 2): print i if __name__ == '__main__': main()
#__*__ encoding:utf8 __*__ """9. Leia um número e exiba o dia correspondente da semana. (1-Domingo, 2- Segunda etc.), se digitar outro valor deve aparecer valor inválido.""" def main(): numero = input('Digite um numero: ') if numero == 1: print('Domingo') elif numero == 2: print('Segunda') elif numero == 3: print('Terca') elif numero == 4: print('Quarta') elif numero == 5: print('Quinta') elif numero == 6: print('Sexta') elif numero == 7: print('Sabado') else: numero = input('Digite um numero valido de 1 a 7:') if numero == 1: print('Domingo') elif numero == 2: print('Segunda') elif numero == 3: print('Terca') elif numero == 4: print('Quarta') elif numero == 5: print('Quinta') elif numero == 6: print('Sexta') elif numero == 7: print('Sabado') if __name__ == '__main__': main()
def main(): palavra = raw_input('Palavra: ') letra = raw_input('Letra: ') contador = 0 for l in palavra: if letra == l: contador += 1 print 'Qtd = %d' % contador if __name__ == '__main__': main()
"""17. Leia valores inteiros em duas variaveis distintas e se o resto da divisao da primeira pela segunda for 1 escreva a soma dessas variaveis mais o resto da divisao; se for 2 escreva se o primeiro e o segundo valor sao pares ou impares; se for igual a 3 multiplique a soma dos valores lidos pelo primeiro; se for igual a 4 divida a soma dos numeros lidos pelo segundo, se este for diferente de zero. Em qualquer outra situacao escreva o quadrado dos numeros lidos.""" def main(): valor1 = input ('Digite o primeiro valor: ') valor2 = input ('\nDigite o segundo valor: ') if valor1 % valor2 == 1 : soma = valor1 + valor2 resto = valor1 % valor2 print ('\nA soma dos dois valores e %d e o resto da divisao e %d ') % (soma,resto) elif valor1 % valor2 == 2 : if valor1 % 2 == 0 and valor2 % 2 == 0 : print ('\nO primeiro e o segundo numero sao pares ') elif valor1 % 2 == 1 and valor2 % 2 == 1 : print ('\nO primeiro e o segundo numero sao impares ') else : if valor1 % 2 == 1 : print ('\nO primeiro numero e impar e o segundo numero e par ') else : print ('\nO primeiro numero e par e o segundo numero e impar ') elif valor1 % valor2 == 3 : soma = valor1 + valor2 multiplicacao = soma * valor1 print ('\nA multiplicacao da soma dos numeros pelo primeiro numero e %d ') % (multiplicacao) elif valor1 % valor2 == 4 : soma = valor1 + valor2 if valo2 != 0 : divisao = soma / valor2 print ('\nA divisao da soma dos numeros pelo segundo numero e %d ') % (divisao) else : quadrado1 = valor1 ** 2 quadrado2 = valor2 ** 2 print ('\nO quadrado do primeiro numero e %d e o quadrado do segundo numero e %d') % (quadrado1,quadrado2) if __name__ == '__main__': main()
"""26. Leia um numero inteiro de dias, calcule e escreva quantas semanas e quantos dias ele corresponde.""" dias = input ('Digite um valor inteiro de dias: ') semanas = dias / 7 dias1 = dias % 7 print ('\nO equivalente em semanas e dias de %d dias e %d semanas e %d dias ') % (dias,semanas,dias1)
"""17. Leia o valor da base e altura de um retangulo, calcule e escreva sua area. (area = base * altura)""" base = input ('Digite o valor da base de um retangulo : ' ) altura = input ('Digite o valor da altura de um retangulo: ') area = base * altura print ('\nA area do retangulo e %.2f') % (area)
#__*__ encoding:utf8 __*__ """4. Leia uma frase e gere uma nova frase, duplicando cada caractere da frase digitada.""" def main(): frase = raw_input('Digite uma frase: ') nova_frase = '' for letra in frase: nova_frase += frase.replace(frase,letra*2) print nova_frase if __name__ == '__main__': main()
#By E. def main(): num1, num2 = input('N1: '), input('N2: ') resultado = mmc(num1, num2) print 'MMC = %d' % resultado def mmc(numero1, numero2): multiplo = 1 while True: if multiplo % numero1 == 0 and multiplo % numero2 == 0: return multiplo else: multiplo = multiplo + 1 if __name__ == '__main__': main()
"""29. Escreva um algoritmo que calcula o retorno de um investimento financeiro. O usuario deve informar quanto sera investido por mes e qual sera a taxa de juros mensal. O algoritmo deve informar o saldo do investimento apos um ano (soma das aplicacoes mensais + juros compostos), e perguntar ao usuario se deseja calcular o ano seguinte, sucessivamente. Por exemplo, caso o usuario deseje investir R$ 100,00 por mes, e tenha uma taxa de juros de 1% ao mes, o algoritmo forneceria a seguinte saida: Saldo do investimento apos 1 ano: 1268.25 Deseja processar mais um ano (S/N) ?""" def main(): while True: quantidade_de_anos = input('\nDigite a quantidade de anos do seu investimento sendo 0 para sair: ') quantidade_de_meses = quantidade_de_anos * 12 if quantidade_de_anos == 0: break else: investimento_mes = input('\nDigite o quanto sera investido: ') taxa_juro_mensal = input('\nDigite qual sera a taxa de juros mensal: ') taxa_juro_mensal = float(taxa_juro_mensal) taxa_juro_mensal = taxa_juro_mensal / 100 saldo_investimento_ano = investimento_mes * ((1 + taxa_juro_mensal) ** quantidade_de_meses) print('\nO saldo do investimento apos um ano eh %.2f ') % saldo_investimento_ano ano_seguinte = raw_input('\nDeseja processar mais um ano (SIm/sim ou NAo/nao): ') if ano_seguinte == 'SIM' or ano_seguinte == 'sim': saldo_investimento_ano = investimento_mes * (1 + taxa_juro_mensal) ** (quantidade_de_meses + 12) print('\nO saldo do investimento apos um ano mais o ano seguinte ao ano eh %.2f ') % saldo_investimento_ano continue if __name__ == '__main__': main()
"""15. Leia o valor da base e altura de um triangulo, calcule e escreva sua area. (area=(base * altura)/2)""" base = input ('Digite o valor da base de um triangulo: ' ) altura = input ('\nDigite a altura de um triangulo: ') area = (base * altura) / 2 print ('\nA area do triangulo e %.2f') % (area)
def main(): palavra = raw_input('Frase: ') for i in range(len(palavra)): contador = 0 for j in range(i+1, len(palavra)): if palavra[i] == palavra[j]: print 'Letra %s Repetida' % palavra[i] if __name__ == '__main__': main()
""" Progressao Geometrica """ def main(): inicio = input('Inicio: ') limite = input("Limite: ") razao = input("Razao: ") atual = 1 print atual, ultimo = atual for i in range(inicio, limite + 1): atual = ultimo * razao if atual <= limite: print atual, ultimo = atual else: break if __name__ == '__main__': main()
"""11. Leia LimiteSuperior e LimiteInferior e escreva todos os numeros primos entre os limites lidos.""" from math import sqrt as raiz def main(): limite_inferior = input('Digite o limite inferior: ') limite_superior = input('\nDigite o limite superior: ') print('Os numeros primos entre %d e %d ') % (limite_inferior,limite_superior) fim = limite_superior for i in range(1, fim + 1): raiz_quadrada = raiz (i) raiz_quadrada = int (raiz_quadrada) quadrado_numero = raiz_quadrada ** 2 if i > limite_inferior and i < limite_superior: if i != 1 and quadrado_numero != i : if i == 2 or i % 2 != 0 : if i == 2 or i % 3 != 0 or i == 3 : if i == 2 or i % 5 != 0 or i == 5 : if i == 2 or i % 7 != 0 or i == 7 : if i == 2 or i % 9 != 0 : print i if __name__ == '__main__': main()
"""15. Leia a quantidade de horas aula dadas por dois professores e o valor por hora recebido por cada um. Escreva na tela qual dos professores tem salario total maior.""" def main(): horas_prof1 = input ('Digite a quantidade de horas aula dadas pelo professor 1: ') valor_horas_prof1 = input ('\nDigite o valor da hora aula dada pelo professor 1: ') horas_prof2 = input ('\nDigite a quantidade de horas aula dadas pelo professor 2: ') valor_horas_prof2 = input ('\nDigite o valor da hora aula dada pelo professor 2: ') salario_prof1 = horas_prof1 * valor_horas_prof1 salario_prof2 = horas_prof2 * valor_horas_prof2 if salario_prof1 > salario_prof2 : print ('\nO professor 1 tem um salario maior que o professor 2 ') else : print ('\nO professor 2 tem um salario maior que o professor 1 ') if __name__ == '__main__': main()
def main(): quantidade_teste = int(input('Quantidade de teste: ')) for i in range(quantidade_teste): valores = input('Valores de X e Y: ').split(' ') valor_x = int(valores[0]) valor_y = int(valores[1]) funcao_r = ((3*valor_x)**2) + (valor_y**2) funcao_b = (2*(valor_x**2)) + ((5*valor_y)**2) funcao_c = (-100*valor_x) + (valor_y**3) if funcao_r > funcao_b and funcao_r > funcao_c: print('Rafael ganhou') elif funcao_b > funcao_c: print('Beto ganhou') else: print('Carlos ganhou') if __name__ == '__main__': main()
# # Zaimplementuj iterator zwracający jedynie samogłoski z zadanego ciągu znaków: # ​ # Przykładowe użycie: # for char in Vowels('ala ma kota a kot ma ale'): # class Vowels: def __init__(self, sentence: str): self.sentence = sentence self.vowels = ['a', 'ą', 'e', 'ę', 'i', 'o', 'u', 'y'] def __iter__(self): self.counter = 0 return self def __next__(self) -> str: if self.counter >= len(self.sentence): raise StopIteration tmp = self.sentence[self.counter] while tmp not in self.vowels: self.counter += 1 tmp = self.sentence[self.counter] else: self.counter += 1 return tmp for char in Vowels('ala ma kota a kot ma ale'): print(char)
x = list(range(1, 11)) print(x) print([el ** 3 for el in x]) print([el ** 3 for el in x if el % 2 ==0]) print({el ** 3 for el in x if el % 2 ==0}) # zbiór print({el: el ** 3 for el in x if el % 2 ==0}) # slownik print(tuple(el ** 3 for el in x if el % 2 ==0)) # tuple # zadania print([x / 10 for x in range(11)])
def more_than(example_text, counter): results = set() for sign in set(example_text): if example_text.count(sign) > counter: results.add(sign) return results print(more_than('ala ma kota a kot ma ale', 2)) print(more_than('aaa bbb', 2)) def test_more_than(): assert more_than('aaa', 2) == {'a'} assert more_than('aaa bbb', 2) == {'a', 'b'}
word = 'podaj slowo lub zdanie:' dict1 = dict() for sign in word: dict1[sign] = dict1.get(sign, 0) + 1 for znak, ilosc in dict1.items(): print(f'{znak} -> {ilosc}') from collections import defaultdict zliczenia = defaultdict(int) for znak in word: zliczenia[znak] += 1 print("333: ", zliczenia)
# ### Zadanie 1.1 | Interakcja i proste obliczenia (ok. 2 godz.) # ​ # Napisz program, który prosi użytkownika (przez `input()`), żeby podał, ile kosztuje kilo ziemniaków. Niech program # policzy i wyświetli, ile trzeba będzie zapłacić za pięć kilo ziemniaków. # ​ # Potem napisz program, który prosi użytkownika (przez `input()`), żeby podał, # ile kosztuje kilo ziemniaków i ile kilo chce kupić. # Niech program policzy i wyświetli, ile trzeba będzie zapłacić za te ziemniaki. # ​ # Potem napisz program, który prosi użytkownika (przez `input()`), # żeby podał, ile kosztuje kilo ziemniaków, ile kilo ziemniaków chce kupić, # ile kosztuje kilo bananów i ile kilo bananów chce kupić. # Niech program policzy i wyświetli, ile trzeba będzie zapłacić za te ziemniaki i banany razem. # I niech program sprawdzi i powie, za co trzeba będzie zapłacić więcej - za banany czy za ziemniaki. cena_za_kilo = float(input('podaj cene za kilo: ')) ilosc = float(input('podaj ilosc do zakupu:')) print(f'cena za kilo = {cena_za_kilo} a cena za 5kg = {cena_za_kilo * 5}') print(f'cena za kilo = {cena_za_kilo} a cena za 5kg = {cena_za_kilo * ilosc}')
# В этом модуле описывается функция, которая возвращает список имен брендов. Имена брендов в этом списке пишутся # ЗАГЛАВНЫМИ буквами! Список формируется на основе значений, указанных построчно в файле Database\Config\list_brands.txt def getBrandNames(): BRANDS = [] with open('Database\Config\list_brands.txt', 'r') as brandFile: for brand in brandFile.readlines(): BRANDS.append(brand.strip().upper()) return BRANDS
import Structure import Player import Bot import random class Main: isPlayerTurn = False isBotTurn = False playerSymbol = '' botSymbol = '' def __init__(self, row, col, defVal, botname): self.board = Structure.Board(row, col, defVal) playerName = input('Enter your Name to continue\n') self.player = Player.Player(playerName) self.bot = Bot.Bot(botname) print('----------------------------\n') self.decideTurn() def decideTurn(self): t = random.randint(0, 1) if t == 0: print(f"{self.bot.name} will start first") self.isBotTurn = True self.botSymbol = 'O' self.playerSymbol = 'X' else: print(f"{self.player.name} will start first") self.isPlayerTurn = True self.playerSymbol = 'O' self.botSymbol = 'X' def startGame(self): while True: if self.isBotTurn: # Write your lines here self.bot.isMyTurn(self.botSymbol, self.board.returnAvailablePosition(), self.board) self.isBotTurn = False self.isPlayerTurn = True if self.isPlayerTurn: # Write your lines here print("Choose any number from 0 to 8") position = self.player.takePlayerInput(self.board) self.board.inputPlayerSelection(position, self.playerSymbol) self.isPlayerTurn = False self.isBotTurn = True if self.board.isWinCase(self.botSymbol if not self.isBotTurn else self.playerSymbol): if not self.isBotTurn: print(f"{self.bot.name} is the winner...") break else: print(f"{self.player.name} is the winner...") break else: if len(self.board.listOfAvailableIndexes) == 0: print("It's a draw") break m = Main(3, 3, '_', 'Susy') m.startGame()
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by weizhenjin on 17-2-7 def b(fn): return lambda s: r'<b>%s<\b>' % fn(s) def em(fn): return lambda s: r'<em>%s<\em>' % fn(s) @b @em def greet(name): return 'Hello %s' % name def sayhi(name): return 'Hi %s' % name sayhi = em(sayhi) sayhi = b(sayhi) def main(): print(greet('jack')) print(sayhi('tom')) if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by weizhenjin on 17-2-22 def as_pandas(cursor): """Return a pandas `DataFrame` out of an impyla cursor. This will pull the entire result set into memory. For richer pandas-like functionality on distributed data sets, see the Ibis project. Parameters ---------- cursor : The cursor object that has a result set waiting to be fetched. Returns ------- DataFrame """ from pandas import DataFrame for metadata in cursor.description: print(metadata) names = [metadata[0] for metadata in cursor.description] return DataFrame.from_records(cursor.fetchall(), columns=names) def main(): pass if __name__ == '__main__': main()
from socket import * import sys msg = "\r\n I love computer networks!" endmsg = "\r\n.\r\n" # Choose a mail server (e.g. Google mail server) and call it mailServer mailServer = 'localhost' # using private testing SMTP server mailPort = 1010 # port number # Create socket called clientSocket and establish a TCP connection with mailServer clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((mailServer, mailPort)) recv = clientSocket.recv(1024).decode() print('Conn cmd response: ' + recv) if recv[:3] != '220': print('220 reply not received from server.') # Send HELO command and print server response. heloCommand = 'HELO Server\r\n' clientSocket.send(heloCommand.encode()) recv1 = clientSocket.recv(1024).decode() print('HELO cmd response: ' + recv1) if recv1[:3] != '250': print('250 reply not received from server.') # Send MAIL FROM command and print server response. mailFromCommand = 'MAIL FROM: <TeamCCD@SJSUcmpe.edu>\r\n' # From address clientSocket.send(mailFromCommand.encode()) recv1 = clientSocket.recv(1024).decode() print('MAIL FROM cmd response: ' + recv1) if recv1[:3] != '250': print('250 reply not received from server') # Send RCPT TO command and print server response. # rcptToCommand = 'RCPT TO: <raymond.chin@sjsu.edu>\r\n' # To address rcptToCommand = 'RCPT TO: <' + input('Recipient email address: ') + '>\r\n' clientSocket.send(rcptToCommand.encode()) recv1 = clientSocket.recv(1024).decode() print('RCPT TO cmd response: ' + recv1) if recv1[:3] != '250': print('250 reply not received from server') # Send DATA command and print server response. dataCommand = 'DATA\r\n' print(dataCommand) clientSocket.send(dataCommand.encode()) recv1 = clientSocket.recv(1024).decode() print('DATA cmd response: ' + recv1) if recv1[:3] != '354': print('354 reply not received from server') # Send message data. subject = input('Enter subject: ') print('Enter message body. When finished, press \'Enter, Ctrl + d\':\n') message = sys.stdin.read() # Message ends with a single period. # clientSocket.send((subject + msg + endmsg).encode()) clientSocket.send(( "From: " + mailFromCommand[12:-3] + "\r\n" + "Subject: " + subject + "\r\n" + "To: " + rcptToCommand[10:-3] + "\r\n" + "\n" + message + endmsg).encode()) recv1 = clientSocket.recv(1024).decode() print('MESSAGE CONTENT response: ' + recv1) if recv1[:3] != '250': print('250 reply not received from server') # Send QUIT command and get server response. quitCommand = 'QUIT\r\n' print(quitCommand) clientSocket.send(quitCommand.encode()) recv1 = clientSocket.recv(1024).decode() print('QUIT cmd response: ' + recv1) if recv1[:3] != '221': print('221 reply not received from server') pass clientSocket.close() # close socket; unsafe # enable for script # if __name__ == '__main__': # main()
''' PLANNNING print("Let's find out who your bestie is in BTS!") print('What do you like doing in your free time?') print("Please type in a letter based on the selection below.\n" + "Fishing 1\n" + "Taking a walk in the park 3 Gaming 5 Sleeping 7 Travel to other countries 9 What is your favorite food? Seafood 1 Meat 3 Ramen 5 Lamb skewers 7 If you could be anyone of these, which would you be? Tennis player 1 Police Officer 3 Farmer 5 Office worker 7 Which is your favorite movie? Forrest Gump 1 The Big Short 3 Call Me By Your Name 5 Eternal Sunshine of the Spotless Mind 7 Jin - 2 Jhope -7 Yoongi - 11 Namjoon 14 Jimin - 17 Taehyung- 18 Jungkook 19 END PLANNING ''' ## BTS QUIZ CODE Left to Right: V, Yoongi, Jin, Jhope, Namjoon/RM, Jimin, Jungkook :) total=0 print('Let us find out who your bestie is in BTS!') print('What do you like doing in your free time?') print('Please type in a letter based on the selection below.\n A.Fishing\n B.Taking a walk in the park\n C.Gaming\n D.Sleeping\n E. Travel to other countries') free_time=input() if free_time=='A': total2=total+1 elif free_time=='B': total2=total+3 elif free_time=='C': total2=total+5 elif free_time=='D': total2=total+7 else: total2=total+9 print('What is your favorite food?') print('Please type in a letter based on the selection below.\n A.Seafood\n B.Meat\n C.Ramen\n D.Lamb Skewers') favfood=input() if favfood=='A': total2=total2+1 elif favfood=='B': total2=total2+3 elif favfood=='C': total2=total2+5 else: total2=total2+7 print('If you could be anyone of these, which would you be?') print('Please type in a letter based on the selection below.\n A.Tennis Player\n B.Police Officer\n C.Farmer\n D.Office worker') profession=input() if profession=='A': total2=total2+1 elif profession=='B': total2=total2+3 elif profession=='C': total2=total2+5 else: total2=total2+7 print('Which is your favorite movie?') print('Please type in a letter based on the selection below.\n A.Forrest Gump\n B.The Big Short\n C.Call Me By Your Name\n D.Eternal Sunshine of the Spotless Mind') movie=input() if movie=='A': total2=total2+1 elif movie=='B': total2=total2+3 elif movie=='C': total2=tota2l+5 else: total2=total2+7 if total2 < 7: print('Jin') if 6<total2<11: print('Jhope') if 10<total2<14: print ('Yoongi') if 13<total2<18: print ('Namjoon') if 17<total2<20: print ('Jimin') if 19<total2<22: print ('V') if 21<total2: print ('Jungkook')
# Person Class class Person: # Constructor def __init__(self, id, fname, lname): self.id = id self.fname = fname self.lname = lname # Display first name and last name of person. def displayDetails(self): print("Name:", self.fname, self.lname) # Student Class class Student(Person): # Constructor def __init__(self, id, fname, lname): Person.__init__(self, id, fname, lname) # Display first name and last name of student. def displayDetails(self): print("Student Name:", self.fname, self.lname) # Faculty Class class Faculty(Person): # Constructor def __init__(self, id, fname, lname): Person.__init__(self, id, fname, lname) # Display first name and last name of faculty. def displayDetails(self): print("Faculty Name:", self.fname, self.lname) # Book Class class Book: # Constructor def __init__(self, id, name, author=''): self.id = id self.name = name self.author = author # Library Class class Library: available_books = [] issued_books = [] students = [] facultys = [] # Constructor def __init__(self): self # Add Book method which will add books to available_books array. def addBook(self, book: 'Book'): Library.available_books.append(book) # Add Student method which will add student to students array. def addStudent(self, student: 'Student'): Library.students.append(student) # Add Faculty method which will add faculty to facultys array. def addFaculty(self, faculty: 'Faculty'): Library.facultys.append(faculty) # Display all AvailableBooks def displayAvailableBooks(self): for book in self.available_books: print(book.name) # Display all Students def displayStudents(self): for student in self.students: student.displayDetails() # Display all Faculty members def displayFacultys(self): for faculty in self.facultys: faculty.displayDetails() # Issue a book to student def issueBook(self, book: 'Book'): self.issued_books.append(book) self.available_books.remove(book) # Return book from student def returnBook(self, book: 'Book'): self.issued_books.remove(book) self.available_books.append(book) # Creating 2 students s = Student(1, "Murali", "C") s1 = Student(2, "Murali1", "C1") # Creating 2 faculty members f = Faculty(1, "Krishna", "C") f1 = Faculty(2, "Krishna1", "C1") # Creating 3 books b = Book(1, "Java", "sai") b1 = Book(2, "C#", "C") b2 = Book(3, "Python", "Ch") # Creating library class lib = Library() # Adding students to library lib.addStudent(s) lib.addStudent(s1) # Adding faculty to library lib.addFaculty(f) lib.addFaculty(f1) # Adding books to library lib.addBook(b) lib.addBook(b1) lib.addBook(b2) # Displaying operations print("Displaying all Students : ") lib.displayStudents() print("------------------------------------") print("Displaying all Faculty : ") lib.displayFacultys() print("------------------------------------") print("Displaying all Available Books : ") lib.displayAvailableBooks() print("------------------------------------") lib.issueBook(b) print("Displaying all Available Books after issuing Java : ") lib.displayAvailableBooks() print("------------------------------------") lib.returnBook(b) print("Displaying all Available Books after returning Java : ") lib.displayAvailableBooks()
import math def is_accurate_enough(num1, num2, accuracy): # we use abs so we don't have to care about the order of the 2 numbers if (abs(num1 - num2) < accuracy): return True else: return False def calculate_e(accuracy): # we initialize e_previous to a dummy value # so we can enter in the while e_previous = -10 e_current = 0 i = 0 while (is_accurate_enough(e_previous, e_current, accuracy) == False): fact = math.factorial(i) e_previous = e_current e_current = e_current + (1 / fact) i += 1 return e_current precision_number = float(input("Please give me the accuracy of the approximation of e to be calculated: ")) approximation_e = calculate_e(precision_number) print("approximation of e : " + str(approximation_e))
# MAINMENU Main script to run the bacterial analysis program utilizing # the functions of the other files imported from the same directory ## # Usage: mainMenu() ## # Author: Thomas B. Frederiksen, s183729@student.dtu.dk, 2020 import os.path folder = os.path.dirname(os.path.abspath(__file__)) os.chdir(folder) from DataStatistics import dataStatistics, printStatOptions from dataLoad import dataLoad from PrintAndUserInput import * from DataPlotFunktion import * from Filter import * #Initiliaze variables print("Welcome to the python Bacteria Data Analysis program") dataLoaded = False dataFiltered = False bacteria = 0 l_lim = 0 u_lim = 0 dataChoice = 1 dataNotLoaded = "Data has not been loaded. Please load data to perform calculations" bacteriaTypes = {0:'All Bacteria', 1:'Salmonella enterica', 2: 'Bacillus cereus', 3: 'Listeria', 4: 'Brochothrix thermosphacta'} while True: printMenu() #If the data has been filtered, inform the user if(dataFiltered): print("\n\nFiltered data available") print("Current data filter parameters: ") print("Bacteria Type:",bacteriaTypes[bacteria]) print("Lower and Upper limit [{:.2f}, {:.2f}]".format(l_lim,u_lim)) #Prompt user for a menu choice, and act upon the choice choice = inputChoiceNum("Please choose an option: ", "Menu") if(choice == 1): while True: try: #Load datafile if it is a valid filename, otherwise #reprompt for valid filename filename = inputChoiceStr("Please enter the name of the datafile to load: ") if(os.path.isfile(filename)): data = dataLoad(filename) dataLoaded = True break else: print("\nFile not found. Please enter valid filename") except: print("\nError while loading datafile") elif(choice == 2): #If data has not been loaded, inform the user load data if not(dataLoaded): print(dataNotLoaded) else: while True: try: #Prompt the user for the type of filter they want bacteria, l_lim, u_lim, dataFiltered = filterChoice(bacteria, l_lim, u_lim, dataFiltered) newDat = dataFilter(data,bacteria,l_lim,u_lim) break except ValueError: print("Error when filtering the data") pass elif(choice == 3): #If data has not been loaded, inform the user load data if not(dataLoaded): print(dataNotLoaded) else: while True: try: #Present statistical calculation options print("\nStatistical calculation options: ") printStatOptions() #Prompt if the calculation should be based on the #original or filtered data if(dataFiltered): dataChoice = inputChoiceNum("Would you like to calculate statistics of the original data (1) or the filtered data (2): ", "Filtered data") statisticChoice = inputChoiceStr("Please enter a statistic to calculate: ") #Calculate statistic if(dataChoice == 2): statType,statistic = dataStatistics(newDat,statisticChoice) break else: statType,statistic = dataStatistics(data,statisticChoice) break if(statistic == "Error"): raise ValueError() else: break except ValueError: print("\nStatistic not found \nPlease enter one of the following valid statistics: \n") pass #Present statistic calculated print(statType,statistic, "\n") elif(choice == 4): #If data has not been loaded, inform the user load data if not(dataLoaded): print(dataNotLoaded) elif(dataFiltered): while True: try: #Prompt if the plot should be generated from the #original or filtered data dataChoice = inputChoiceNum("Would you like to plot the original data (1) or the filtered data (2): ", "Filtered data") if(dataChoice == 2): dataPlot(newDat) break else: dataPlot(data) break except ValueError: print("Error when creating plots") pass else: dataPlot(data) print("\nGenerating plots...") #Exit the program, by breaking the loop elif(choice == 5): print("Goodbye") break
class planet(object): def __init__(self, name, color, planetType): self.name = name self.color = color self.planetType = planetType def print(self): return f"Name: {self.name}, Color: {self.color}, Planet Type: {self.planetType}"
#!/bin/python3 import os import sys # Complete the totalForecastInaccuracy function below. def totalForecastInaccuracy(t, f): first = [1,2,3,4,5,6,7] second = [1,2,3,4,5,6,7] three = map(lambda x, y: x+y,first,second) print(9) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = list(map(int, input().rstrip().split())) f = list(map(int, input().rstrip().split())) result = totalForecastInaccuracy(t, f) fptr.write(str(result) + '\n') fptr.close()
class Person: def __init__(self,name,age,telephone): self.name=name self.age=age self.telephone=telephone def pick_up(self,person): print(f"{self.name} pick up {person}") class Telephone: def __init__(self, brand,color,price,owner): self.brand = brand self.color = color self.price = price self.owner = owner def call(self,person): print(f"{self.owner} calling {person.name}") person.pick_up(self.owner) def take_a_picture(self,side): print(f"Open {side} camera") class Student(Person): def __init__(self, name,age,telephone): super().__init__(name, age,telephone) self.duty = "Study"
""" Public Data Hacking Total number of registered automobiles in Romania in 2017 1. Top 5 counties by number of registered cars 2. Top 5 car brands in a user defined county, and also the percentage compared to the whole country. 3. A lot of possibilities... Mostly an excuse to play with Python's list comprehensions, Counters, default(dict) and csv files. """ import requests import csv import os from collections import Counter, defaultdict def read_url(file_name, url): # download the file r = requests.get(url) csv_file = open(file_name, 'wb') csv_file.write(r.content) csv_file.close() def read_file(file_name): # read the file and return it as a list (of OrderedDict type objects) with open(file_name, 'r') as csv_file: reader = csv.DictReader(csv_file) reader.fieldnames[0] = 'JUDET' # fixing some weird reading mistake cars = list(reader) # print(reader.fieldnames) return cars def top_counties(cars): # top 5 counties by number of cars print('Number of cars in 2017 by county:\n{}'.format('#'.rjust(33, '#'))) counties = Counter() for row in cars: counties[row['JUDET']] += int(row['TOTAL_VEHICULE']) for name, count in counties.most_common(5): print(f'{name}: {count}') print() def county_and_brand(cars, county): # top 5 car brands in a user defined county by_brand = defaultdict(Counter) for row in cars: by_brand[row['JUDET']][row['MARCA']] += int(row['TOTAL_VEHICULE']) # as a point of reference total = Counter() for row in cars: total[row['MARCA']] += int(row['TOTAL_VEHICULE']) print('Top 5 car brands in {0} county:\n{1}'.format(county, '#'.rjust(34, '#'))) for brand, count in by_brand[county].most_common(5): # percentage, a certain brand (in the specified county) compared to the same brand in the whole country percentage = (int(by_brand[county][brand]) / int(total[brand])) * 100 print(f'{brand}: {count}, {percentage:.2f}%') print() def main(): url = 'http://data.gov.ro/dataset/b93e0946-2592-4ed7-a520-e07cba6acd07/resource/' \ '4f434c30-0afe-4101-bacd-58b4d95a998e/download/parcauto2017.csv' file_name = 'parcauto2017.csv' # if the file does not exist if not os.path.isfile(file_name): read_url(file_name, url) # read from the file into a list, not efficient but that is not the point of this exercise auto = read_file(file_name) # cars, trucks, motorcycles, etc. # only cars cars = [row for row in auto if row['CATEGORIE_NATIONALA'] == 'AUTOTURISM'] # top 5 counties by number of cars top_counties(cars) # top 5 car brands in Brasov county county_and_brand(cars, 'BRASOV') if __name__ == '__main__': main()
#import os # #x=[d for d in os.listdir('.')] #print(x) #输出任意目录下的文件(例如 C:\) import os #def fun(): # return [d for d in os.listdir('.')] #def fun(x,y): # L=[] # for d in os.listdir(x): # if d != y: # L.append(d) # return L # # #if __name__ == '__main__': # path=input('Please input a path:') # file=input('Please input a file:') # x=fun(path,file) # print(x) #def fun(*Args): # L=[] # for i in Args: # print(i) # return L # # #if __name__ == '__main__': # a=0 # fun(1, 2, 3, 'wwm', 'xcyk',a) #def fun(*Args): # L=[] # for i in Args: # L.append(i) # return L # # #if __name__ == '__main__': # a=0 # x = fun(1, 2, 3, 'wwm', 'xcyk',a) # print(x) def Add(x, y=0, z=0): sum = x + y + z return sum if __name__ == '__main__': x1 = Add(1, 2, 3) x2 = Add(1) print(x1, x2)
b=input("Please input one number:") a=int(b) if a>=0: print(a) else: print(-a)
import random def Sieves(): n1=random.randint(1, 6) n2=random.randint(1, 6) return n1,n2 def run(): sum1=0 sum2=0 for i in range(10): s1,s2=Sieves() print("(第%d次)玩家1:筛子A:%d 筛子B:%d 总分:%d"%(i+1,s1,s2,sum1+s1+s2)) sum1=sum1++s1+s2 c1,c2=Sieves() print("(第%d次)玩家2:筛子A:%d 筛子B:%d 总分:%d"%(i+1,c1,c2,sum2+c1+c2)) sum2=sum2+c1+c2 if sum1>sum2: print('玩家1赢了') elif sum1 == sum2: print("平局") else: print('玩家2赢了') if __name__ == '__main__': run()
##Nhan Nguyen class BankingAccount: def __init__(self): self.balance = 0 print(15* " ","Welcome to Illinois TechCash Service") def get_balance(self): return self.balance def deposit(self): #deposit to balance amount_d = float(input("Enter amount to be Deposited: ")) amount_w = 0 self.balance += amount_d print("\nAmount Deposited= ${:,.2f}".format(amount_d)) #current_time = datetime.datetime.now().strftime("%B %d,%Y: %H:%M:%S") #f = open("transaction.txt", "w+") #f.write("%s" %(current_time)) ##L = [current_time, 10*" ", amount_d,10*" ", amount_w ,10*" ",self.balance, 10*" ", self.interest] ##f.writelines(L) #f.close() def withdraw(self): ##withdrawn from balance amount_w = float(input("Enter amount to be Withdrawed: ")) amount_d = 0 if self.balance >= amount_w: self.balance -=amount_w print("\nYou withdrawed= ${:,.2f}".format(amount_w)) else: print("\nInsufficient Balance. ") #current_time = datetime.datetime.now() #f = open("transaction.txt", "w+") #L = [current_time, 10*" ", amount_d,10*" ", amount_w ,10*" ",self.balance, 10*" ", self.interest] #f.writelines(L) #f.close() def display(self): print("Available Balance= ${:,.2f}\n".format(self.balance)) def interest(self): ##calculate interest accrued rate = 1 ##percentage time = 1 ##years interest_accrued = (self.balance * rate)/100 future_balance = interest_accrued + self.balance print("After 1 year with 1% in interest accrued, you will have= ${:,.2f}\n".format(future_balance)) def menu(self): ##dislay menu print("") print(31 * "-", "menu", 31 * "-") print("1. Account Balance") print("2. Amount Withdrawn") print("3. Amount Deposite") print("4. Interest Accrued") print("5. Exit") print(69 * "-")
#closures:-function returning func def power(x): def base(a): return a**x return base var=power(7) print(var(4))
##any and all l=[2,3,4,6,8,10] a=[] for i in l: a.append(i%2==0) print(all(a))
##label 1 ##label 2 ## ##add sub div mul ## ##result in entry box import tkinter as tk from tkinter import ttk from tkinter import * win=tk.Tk() win.title("Calculator") win.geometry('600x400+500+200') win.configure(background="blue") ##win.wm_attributes('-transparentcolor','black') ## ##filename = PhotoImage(file = "pic.gif") ##background_label = Label(win, image=filename) ##background_label.place(x=0, y=0, relwidth=1, relheight=1) ##input label1=ttk.Label(win,text="First Number:") label1.grid(row=0,column=0,padx=5,pady=5) num1=tk.IntVar() number1=ttk.Entry(win,textvariable=num1) number1.grid(row=0,column=1,padx=5,pady=5) label2=ttk.Label(win,text="Second Number:") label2.grid(row=1,column=0,padx=5,pady=5) num2=tk.IntVar() number2=ttk.Entry(win,textvariable=num2) number2.grid(row=1,column=1,padx=5,pady=5) label3=ttk.Label(win,text="Answer:") label3.grid(row=3,column=0,padx=5,pady=5) ans=tk.IntVar() Answer=ttk.Entry(win,textvariable=ans) Answer.grid(row=3,column=1,padx=5,pady=5) def add(): a=num1.get() b=num2.get() ans.set(a+b) ##addbtn addbtn=ttk.Button(win,text="Add", command=add) addbtn.grid(row=2,column=0,padx=5,pady=5) def sub(): a=num1.get() b=num2.get() ans.set(a-b) ##subbtn subbtn=ttk.Button(win,text="Sub", command=sub) subbtn.grid(row=2,column=1,padx=5,pady=5) def mul(): a=num1.get() b=num2.get() ans.set(a*b) ##mulbtn mulbtn=ttk.Button(win,text="Mul", command=mul) mulbtn.grid(row=2,column=2,padx=5,pady=5) def div(): a=num1.get() b=num2.get() ans.set(a/b) ##divbtn divbtn=ttk.Button(win,text="Divide", command=div) divbtn.grid(row=2,column=3,padx=5,pady=5) win.mainloop()
def fact(a): if a==1: return 1 else: return a * fact(a-1) num=int(input("NUMBER:")) print(fact(num)) #print (x)
##comprehension l=[i for i in range(1,11)] print (l) l1=[i for i in range(1,11) if i%2==0 ] print (l1) d={i:i**3 for i in range(1,11)} print (d) s={i for i in range(1,15,2)} print (s) g=(i for i in range(2,20,2)) ##generator print (g) for i in g: print (i, end=" ")
list = [("student1", "A"),("student2", "B"),("student3","A"),("student4","F"),("student5","D"),("student6","B")] dict={} dict['A'] = [] dict['B'] = [] dict['C'] = [] dict['D'] = [] dict['F'] = [] while list: dict[list[0][1]].append(list.pop(0)[0]) print(dict)
number = input() if len(number) < 4: while len(number) < 4: number = "0" + number part1 = number[0:2] part2 = number[3] + number[2] if int(part1) == int(part2): print(1) else: print(0)
def min4(a, b, c, d): min1 = min(a, b) min2 = min(c, d) return min(min1, min2) a = input() b = input() c = input() d = input() print(min4(a, b, c, d))
now = int(input()) max = 0 i = 0 while now != 0: if now == max: i += 1 elif now > max: max = now i = 1 now = int(input()) print(i)
n = int(input()) k = 0 while 2**k < n: k += 1 else: print(k)
# coding: utf-8 # Author: gjwei """ 冒泡排序法 """ def bubble_sort(nums): has_sorted = False for i in range(0, len(nums)): if has_sorted: break has_sorted = True for j in range(0, len(nums) - i - 1): if nums[j + 1] < nums[j]: has_sorted = False nums[j], nums[j + 1] = nums[j + 1], nums[j]
# coding: utf-8 # 从1到n整数中,1出现的次数 def count1s(n): if n == 0: return 0 if n < 10: return 1 n = str(n) head = int(n[0]) tail = int(n[1:]) if head == 1: return count1s(10 ** (len(n) - 1) - 1) + tail + 1 + count1s(tail) else: return head * count1s(10 ** (len(n) - 1) - 1) + 10 ** (len(n) - 1) + count1s(n % (10 ** (len(n) - 1)))
# coding: utf-8 # Author: gjwei class Heap(object): """大根堆""" def __init__(self, nums): self.heap = nums def sink(self, index): while 2 * index + 1 < len(self.heap): c = 2 * index + 1 # Compare parent to the larger child if c + 1 < len(self.heap) and self.heap[c + 1] > self.heap[c]: c += 1 if self.heap[index] < self.heap[c]: self.heap[index], self.heap[c] = self.heap[c], self.heap[index] index = c else: break return def swim(self, index): while index > 0 and self.heap[(index - 1) // 2] < self.heap[index]: pi = (index - 1) >> 1 self.heap[pi], self.heap[index] = self.heap[index], self.heap[pi] index = pi # 对排序算法 def shift_down(nums, start, end): root = start while True: index = root * 2 + 1 if index > end: break if index + 1 < end and nums[index + 1] > nums[index]: index += 1 if nums[root] < nums[index]: nums[root], nums[index] = nums[index], nums[root] root = index else: break def heap_sort(nums): # 创建大根堆 for start in range((len(nums) - 2) >> 1, -1, -1): shift_down(nums, start, len(nums) -1 ) # 堆排序 for end in range(len(nums) - 1, 0, -1): nums[0], nums[end] = nums[end], nums[0] # 将最大的数移到最后的位置 shift_down(nums, 0, end - 1) return nums # python heapq # python only have build in min-heap if __name__ == '__main__': a = [9,2,1,7,6,8,5,3,4] print(heap_sort(a))
# coding: utf-8 # Author: gjwei """ 选择排序:每次选择出数据中最小的元素,和第一个元素进行交换。然后从剩下的元素中选择最小的,和第二个元素交换位置 依次进行下去 """ def select_sort(nums): for i in range(len(nums)): min_index = i for j in range(i, len(nums)): if nums[j] < nums[min_index]: min_index = j nums[i], nums[min_index] = nums[min_index], nums[i] return nums
# coding: utf-8 def power(num, k): if k < 0: return 1 / power(nums, -k) result = 1 while k > 0: if k & 1 == 1: result *= num k -= 1 else: result *= result k //= 2 return result print(power(5, 3))
# coding: utf-8 # Author: gjwei def swap_nums(a, b): a = a - b b = a + b a = b - a return a, b def swap_nums_2(a, b): a = a ^ b b = a ^ b a = a ^ b return a, b
""" title: Error_Catch_Pratice author: sxv3240 date: 1/7/2019 2:36 PM """ # try: # print(4 +spam +4) # # except NameError as error: # print("Hey,that's not cool!", error) # # try: # print("2" + spam + 15) # except (NameError, TypeError): # print("Very sorry, we are unable to evaluate your request. Please correct errors and re-evaluate.") # # try: # print("2" + spam + 15) # except TypeError as e: # print("You gave the wrong type there buddy!", e) # except NameError as e: # print("That variable name does not exist!", e) try: eval('x===x') except SyntaxError as e: print("Very sorry, we are unable to evaluate your request. Please correct errors and re-evaluate.", e) try: print(10/0) except ZeroDivisionError as e: print(e) try: print(4 + spam) except (NameError, TypeError): print("Very sorry, we are unable to evaluate your request. Please correct errors and re-evaluate.") try: print(2+"2") raise TypeError except TypeError as e: print("Hello",e)
""" title: macaw_math author: sxv3240 date: 1/7/2019 1:32 PM """ import math # percent_of_weight = 1/3 # coconut_weight = 1450 # macaw_weight = 900 # number_of_macaws = coconut_weight / (macaw_weight * percent_of_weight) # # print(math.ceil(number_of_macaws)) # name = input("What's your name?") # print(f"Hello ,{name}!I hope you are having a good day!") # print(type(name)) age = input("How old are you") new_age =int(age)+5 print(f"Five year from ,you will {new_age}") print(new_age)
#!/usr/bin/env python3 # Challenge 3 solution # One small letter, surrounded by EXACTLY three big bodyguards on each of its sides. #################################### # Dependencies: # 1. Beautiful Soup # 2. UrlLib # 3. re #################################### import bs4 from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as Soup from bs4 import Comment import re #url of the page url = "http://www.pythonchallenge.com/pc/def/equality.html" # opening up connection and grabbing the page uClient = uReq(url) page_html= uClient.read() uClient.close() # parsing page for comments using beautiful soup page_soup = Soup(page_html,'html.parser') comments = page_soup.find_all(string = lambda text:isinstance(text,Comment)) url = "" # Parsing each line ofcomments and matching the regec for "aABCdEFGh" # so that it matches those strings which have EXACTLY 3 Uppercase letter either side for c in comments: string = re.findall('[^A-Z][A-Z]{3}[a-z][A-Z]{3}[^A-Z]',c) for i in string: url+=i[4] # merging the smaller character from each match into a string to form the url clue. print(url) # Next level URL is : newUrl = "http://www.pythonchallenge.com/pc/def/"+url+".html" print(newUrl)
''' This problem was asked by Facebook. Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability. ''' import numpy as np arr = list(map(int, input().split())) #simulate input stream for i in arr: if np.random.randint(2) == 0: print(i) #Probability that an element gets picked is 50/50
#!/usr/bin/python # -*- coding: utf-8 -*- """ Signs a URL using a URL signing secret """ ##对签名进行验证代码 import hashlib import hmac import base64 import urllib.parse def sign_url(input_url=None, secret=None): """ Sign a request URL with a URL signing secret. Usage: from urlsigner import sign_url signed_url = sign_url(input_url=my_url, secret=SECRET) Args: input_url - The URL to sign secret - Your URL signing secret Returns: The signed request URL """ if not input_url or not secret: raise Exception("Both input_url and secret are required") url = urllib.parse.urlparse(input_url) # We only need to sign the path+query part of the string url_to_sign = url.path + "?" + url.query # Decode the private key into its binary format # We need to decode the URL-encoded private key decoded_key = base64.urlsafe_b64decode(secret) # Create a signature using the private key and the URL-encoded # string using HMAC SHA1. This signature will be binary. signature = hmac.new(decoded_key, url_to_sign.encode('utf-8'), hashlib.sha1) # Encode the binary signature into base64 for use within a URL encoded_signature = base64.urlsafe_b64encode(signature.digest()) original_url = url.scheme + "://" + url.netloc + url.path + "?" + url.query # Return signed URL bytes.decode(encoded_signature) #str(encoded_signature,encoding='utf-8') return original_url,encoded_signature if __name__ == "__main__": #input_url = input("URL to Sign: ") input_url='https://maps.googleapis.com/maps/api/staticmap?center=39.93944692354029,116.39745889999995&zoom=11&format=png&maptype=roadmap&size=480x360&key=AIzaSyAadVAdjp_hGd21y9y-R6wQ0IcOcHcrl9c' #secret = input("URL signing secret: ") secret='Bfmu0RYkRyvVwZP5DGV8FqKdKfI=' a,b=sign_url(input_url, secret) c=a + "&signature=" + bytes.decode(b) print (c)
import unittest from HW07_Neil_Gupte import HW07 from typing import * class AnagramListTest(unittest.TestCase): """ test anagram list function""" def test_anagram_list(self)->None: a:str="hello" b:str="loleh" self.assertEqual(HW07.anagrams_lst(a,b),True) self.assertEqual(HW07.anagrams_lst("", ""), True) self.assertEqual(HW07.anagrams_lst("yup", "yu"), False) self.assertEqual(HW07.anagrams_lst("12345", "123"), False) self.assertEqual(HW07.anagrams_lst("12345", "12345"), True) class AnagramDictTest(unittest.TestCase): """ test anagram dictionary function""" def test_anagram_dict(self)->None: a:str="hello" b:str="loleh" self.assertEqual(HW07.anagrams_dd(a,b),True) self.assertEqual(HW07.anagrams_dd("", ""), True) self.assertEqual(HW07.anagrams_dd("yup", "yu"), False) self.assertEqual(HW07.anagrams_dd("12345", "123"), False) self.assertEqual(HW07.anagrams_dd("12345", "12345"), True) class AnagramCounterTest(unittest.TestCase): """ test anagram counter function""" def test_anagram_counter(self)->None: a:str="hello" b:str="loleh" self.assertEqual(HW07.anagrams_cntr(a,b),True) self.assertEqual(HW07.anagrams_cntr("", ""), True) self.assertEqual(HW07.anagrams_cntr("yup", "yu"), False) self.assertEqual(HW07.anagrams_cntr("12345", "123"), False) self.assertEqual(HW07.anagrams_cntr("12345", "12345"), True) class CoversAlphabetTest(unittest.TestCase): """ test covers_alphabet function """ def test_covers_alph(self)->None: a:str="AbCdefghiJklomnopqrStuvwxyz" self.assertEqual(HW07.covers_alphabet(a),True) self.assertEqual(HW07.covers_alphabet("AbCdefghiJklomnopqrStuvwxyz12344"), True) self.assertEqual(HW07.covers_alphabet("1bCdefghiJklomnopqrStuvwxz"), False) self.assertEqual(HW07.covers_alphabet(""), False) self.assertEqual(HW07.covers_alphabet("The quick brown fox jumps over the lazy dog"), True) class WebAnalyzerTest(unittest.TestCase): """ test web_analyzer function """ def test_web_analyzer(self)->None: weblogs: List[Tuple[str, str]] = [ ('Nanda', 'google.com'), ('Maha', 'google.com'), ('Fei', 'python.org'), ('Maha', 'google.com'), ('Fei', 'python.org'), ('Nanda', 'python.org'), ('Fei', 'dzone.com'), ('Nanda', 'google.com'), ('Maha', 'google.com'), ] weblogs2: List[Tuple[str, str]] = [ ('Nanda', 'google.com'), ('Maha', 'google.com'), ('Fei', 'python.org'), ('Maha', 'google.com'), ('Fei', 'python.org'), ('Nanda', 'python.org'), ('Fei', 'dzone.com'), ('Nanda', 'google.com'), ('Maha', 'google.com'),('Anil', 'apple.com'),('zoro', 'zoom.com')] weblogs3: List[Tuple[str, str]] = [ ('Nanda', 'google.com'), ('Maha', 'google.com'), ('Fei', 'python.org'), ('Maha', 'google.com'), ('Fei', 'python.org'), ('Nanda', 'python.org'), ('Fei', 'dzone.com'), ('Nanda', 'google.com'), ('Maha', 'google.com'), ('Anil', 'apple.com'), ('Zoro', 'apple.com')] weblogs4: List[Tuple[str, str]] = [ ('Nanda', 'zcash.com'),('Manda', 'zcash.com'),('Onda', 'zcash.com')] summary: List[Tuple[str, List[str]]] = [ ('dzone.com', ['Fei']), ('google.com', ['Maha', 'Nanda']), ('python.org', ['Fei', 'Nanda']), ] summary2: List[Tuple[str, List[str]]] = [ ('apple.com', ['Anil']), ('dzone.com', ['Fei']), ('google.com', ['Maha', 'Nanda']), ('python.org', ['Fei', 'Nanda']), ('zoom.com', ['zoro'])] summary3: List[Tuple[str, List[str]]] = [ ('apple.com', ['Anil','Zoro']), ('dzone.com', ['Fei']), ('google.com', ['Maha', 'Nanda']), ('python.org', ['Fei', 'Nanda'])] summary4: List[Tuple[str, List[str]]] = [ ('zcash.com', ['Manda','Nanda','Onda']) ] self.assertEqual(HW07.web_analyzer(weblogs), summary) self.assertEqual(HW07.web_analyzer(weblogs2), summary2) self.assertEqual(HW07.web_analyzer(weblogs3), summary3) self.assertEqual(HW07.web_analyzer(weblogs4), summary4) if __name__=='__main__': unittest.main(exit=False,verbosity=2)
#! /usr/bin/python3 entero = int(input('Digite un numero entero: ')) entero2 = entero + 1 caracter = input('Digite un caracter: ') while entero > 0: entero = entero - 1 while entero < entero2: for x in range(entero): print(caracter,end='') print() entero = entero + 1
import sqlite3 import os class main: def checkuser(obj): user_id = obj.getId() password=obj.getPassword() if os.path.exists("Mydb"): db=sqlite3.connect("Mydb") cursor = db.cursor() cursor.execute('''SELECT id,password,name FROM users WHERE id=? AND password=?''', (user_id,password,)) user = cursor.fetchall() if len(user)>0: return user[0][2] else: return False else: db=sqlite3.connect("Mydb") cursor = db.cursor() cursor.execute(''' CREATE TABLE users(id TEXT PRIMARY KEY,name TEXT,password TEXT,user_type TEXT, user_status TEXT,contact INTEGER ,DOB TEXT, email TEXT )''') cursor.execute('''INSERT INTO users(id,name,password,user_type,user_status,contact,DOB,email) VALUES(?,?,?,?,?,?,?,?)''', ("1", "Rajat","admin","Admin","Active",8123432126,"12-09-1996","srajat490@gmail.com")) db.commit() db=sqlite3.connect("Mydb") cursor = db.cursor() cursor.execute('''SELECT id,password,name FROM users WHERE id=? AND password=?''', (user_id,password,)) user = cursor.fetchall() if len(user)>0: return user[0][2] else: return False def returnid(): db=sqlite3.connect("Mydb") cursor = db.cursor() cursor.execute("SELECT * FROM users ORDER BY id DESC") result = cursor.fetchone() return int(result[0])+1 def addUsers(obj): db=sqlite3.connect("Mydb") cursor = db.cursor() cursor.execute('''SELECT id FROM users WHERE id=? ''', (obj.getId())) user = cursor.fetchall() if len(user)==1: return False else: cursor.execute('''INSERT INTO users(id,name,password,user_type,user_status,contact,DOB,email) VALUES(?,?,?,?,?,?,?,?)''', (obj.getId(), obj.getName(),obj.getPassword(),obj.getuser_type(), obj.getuser_status(),obj.getcontact(),obj.getdob(),obj.getemail())) db.commit() return True def search(u_id): db=sqlite3.connect("Mydb") cursor = db.cursor() cursor.execute('''SELECT name,user_type,user_status,contact,DOB,email FROM users WHERE id=? ''',(u_id,)) out=cursor.fetchone() if out==None: return False else: return out def all_user(): db=sqlite3.connect("Mydb") cursor = db.cursor() cursor.execute('''SELECT id,name,user_type,user_status,contact,DOB,email FROM users''') u_l=cursor.fetchall() return u_l def delete(u_id): db=sqlite3.connect("Mydb") cursor = db.cursor() cursor.execute('''SELECT name,user_type,user_status,contact,DOB,email FROM users WHERE id=? ''',(u_id,)) out=cursor.fetchone() if out==None: return False else: cursor.execute('''DELETE FROM users WHERE id = ? ''', (u_id,)) db.commit() return True def update(obj1): db=sqlite3.connect("Mydb") cursor = db.cursor() cursor.execute('''UPDATE users SET name=?,user_status=?,contact=?,DOB=?,email=? WHERE id = ? ''', (obj1.getName(),obj1.getuser_status(),obj1.getcontact(),obj1.getdob(),obj1.getemail(),obj1.getId())) out=cursor.rowcount db.commit() if out==1: return True else: return False
def f(a, b): a += b return a x = 1 y = 2 f(x, y) x, y a = [1, 2] b = [3, 4] f(a, b) a, b t = (10, 20) u = (30, 40) f(t, u) t, u
"""Example 7-8""" class Averager: def __init__(self): self.series = [] def __call__(self, new_value): self.series.append(new_value) total = sum(self.series) return total/len(self.series) avg = Averager() avg(10) avg(11) avg(12)
"""Example 16-13 A coroutine to compute a running average >>> coro_avg = averager() 1 >>> from inspect import getgeneratorstate >>> getgeneratorstate(coro_avg) 2 'GEN_SUSPENDED' >>> coro_avg.send(10) 3 10.0 >>> coro_avg.send(30) 20.0 >>> coro_avg.send(5) 15.0 """ from collections import namedtuple Result = namedtuple('Result', 'count average') def averager(): total = 0.0 count = 0 average = None while True: term = yield if term is None: break total += term count += 1 average = total/count return Result(count, average)
""" This the declarative model for the first scenario to test and compare several algorithms. In this planning domain, an automomous agent must travel through a 2D grid-map avoiding obastacles which have been modeled as dead-ends. That is to say, states from which it is impossible to leave thus the agent will never reach the goal. The initial state is known and the objective is to find the optimal (or near-optimal) policy that drives the agent from the inital state to the goal This benchmark has been modeled as an Stochastic Shortest Path (SSP) in other words, a discounted infinite horizon MDP with negative rewards to simulate costs. """ ##-------------------------------LIBRARIES----------------------------------## from StateClass import State from GridFunctions import Grid2State from ValueIteration import VI ##-----------------DEFINITION OF THE PLANNING DOMAIN------------------------## # ----------------- # |S0 |S1 |S2 |S3 | # |S4 |S5 |S6 |S7 | # |S8 |S9 |S10|S11| # ----------------- H = 3 # Height W = 4 # Width n_obs = 2 # Number of obstacles n_states = H*W # Number of states, including: # -Initial, Goal, Obstacles. # Initialization of States states = [] for i in range (0,n_states): states.append(State(i,H,W)) # 1) Initial State states[0].initial = True # S0 will be the initial state # 2) Goal State states[11].goal = True # S11 will be the goal # 3) Obstacles states[2].obstacle = True # S2 will be an obstacle states[9].obstacle = True # S9 will be an obstacle ##---------------DEFINITION OF THE TRANSITION-COST MODEL--------------------## def Cost(listOfStates, dest): nominalCost = -0.05 obstacleCost = -5 goalCost = 0 if listOfStates[dest].goal: return goalCost elif listOfStates[dest].obstacle: return obstacleCost else: return nominalCost for s in states: # Stay action definition ------------------------------------------------ if s.obstacle: s.transitions["Stay"] = {s.number: [1, -5]} elif s.goal: s.transitions["Stay"] = {s.number: [1, 0]} else: s.transitions["Stay"] = {s.number: [1, -0.05]} # NORTH action definition ------------------------------------------------ if s.obstacle: s.transitions["North"] = {s.number: [1, Cost(states, s.number)]} elif s.goal: s.transitions["North"] = {s.number: [1, Cost(states, s.number)]} elif s.top: s.transitions["North"] = {s.number: [1, Cost(states, s.number)]} elif not s.top and s.left : #Compute destination states d1 = Grid2State(s.vPos-1, s.hPos, H, W) #Upper state d2 = Grid2State(s.vPos-1, s.hPos+1, H, W) #up-right state s.transitions["North"] = {d1: [0.9, Cost(states, d1)], d2: [0.1, Cost(states, d2)]} elif not s.top and s.right : #Compute destination states d1 = Grid2State(s.vPos-1, s.hPos, H, W) #Upper state d2 = Grid2State(s.vPos-1, s.hPos-1, H, W) #up-left state s.transitions["North"] = {d1: [0.9, Cost(states, d1)], d2: [0.1, Cost(states, d2)]} else: #Compute destination states d1 = Grid2State(s.vPos-1, s.hPos, H, W) #Upper state d2 = Grid2State(s.vPos-1, s.hPos-1, H, W) #up-left state d3 = Grid2State(s.vPos-1, s.hPos+1, H, W) #up-right state s.transitions["North"] = {d1: [0.8, Cost(states, d1)], d2: [0.1, Cost(states, d2)], d3: [0.1, Cost(states, d3)]} # SOUTH action definition ------------------------------------------------ if s.obstacle: s.transitions["South"] = {s.number: [1, Cost(states, s.number)]} elif s.goal: s.transitions["South"] = {s.number: [1, Cost(states, s.number)]} elif s.bottom: s.transitions["South"] = {s.number: [1, Cost(states, s.number)]} elif not s.bottom and s.left : #Compute destination states d1 = Grid2State(s.vPos+1, s.hPos, H, W) #down state d2 = Grid2State(s.vPos+1, s.hPos+1, H, W) #down-right state s.transitions["South"] = {d1: [0.9, Cost(states, d1)], d2: [0.1, Cost(states, d2)]} elif not s.bottom and s.right : #Compute destination states d1 = Grid2State(s.vPos+1, s.hPos, H, W) #down state d2 = Grid2State(s.vPos+1, s.hPos-1, H, W) #down-left state s.transitions["South"] = {d1: [0.9, Cost(states, d1)], d2: [0.1, Cost(states, d2)]} else: #Compute destination states d1 = Grid2State(s.vPos+1, s.hPos, H, W) #down state d2 = Grid2State(s.vPos+1, s.hPos-1, H, W) #down-left state d3 = Grid2State(s.vPos+1, s.hPos+1, H, W) #down-right state s.transitions["South"] = {d1: [0.8, Cost(states, d1)], d2: [0.1, Cost(states, d2)], d3: [0.1, Cost(states, d3)]} # East action definition ------------------------------------------------ if s.obstacle: s.transitions["East"] = {s.number: [1, Cost(states, s.number)]} elif s.goal: s.transitions["East"] = {s.number: [1, Cost(states, s.number)]} elif s.right: s.transitions["East"] = {s.number: [1, Cost(states, s.number)]} elif not s.right and s.top : #Compute destination states d1 = Grid2State(s.vPos, s.hPos+1, H, W) #right state d2 = Grid2State(s.vPos+1, s.hPos+1, H, W) #down-right state s.transitions["East"] = {d1: [0.9, Cost(states, d1)], d2: [0.1, Cost(states, d2)]} elif not s.right and s.bottom : #Compute destination states d1 = Grid2State(s.vPos, s.hPos+1, H, W) #right state d2 = Grid2State(s.vPos-1, s.hPos+1, H, W) #up-right state s.transitions["East"] = {d1: [0.9, Cost(states, d1)], d2: [0.1, Cost(states, d2)]} else: #Compute destination states d1 = Grid2State(s.vPos, s.hPos+1, H, W) #right state d2 = Grid2State(s.vPos+1, s.hPos+1, H, W) #down-right state d3 = Grid2State(s.vPos-1, s.hPos+1, H, W) #up-right state s.transitions["East"] = {d1: [0.8, Cost(states, d1)], d2: [0.1, Cost(states, d2)], d3: [0.1, Cost(states, d3)]} # West action definition ------------------------------------------------ if s.obstacle: s.transitions["West"] = {s.number: [1, Cost(states, s.number)]} elif s.goal: s.transitions["West"] = {s.number: [1, Cost(states, s.number)]} elif s.left: s.transitions["West"] = {s.number: [1, Cost(states, s.number)]} elif not s.left and s.top : #Compute destination states d1 = Grid2State(s.vPos, s.hPos-1, H, W) #left state d2 = Grid2State(s.vPos+1, s.hPos-1, H, W) #down-left state s.transitions["West"] = {d1: [0.9, Cost(states, d1)], d2: [0.1, Cost(states, d2)]} elif not s.left and s.bottom : #Compute destination states d1 = Grid2State(s.vPos, s.hPos-1, H, W) #left state d2 = Grid2State(s.vPos-1, s.hPos-1, H, W) #up-left state s.transitions["West"] = {d1: [0.9, Cost(states, d1)], d2: [0.1, Cost(states, d2)]} else: #Compute destination states d1 = Grid2State(s.vPos, s.hPos-1, H, W) #left state d2 = Grid2State(s.vPos+1, s.hPos-1, H, W) #down-left state d3 = Grid2State(s.vPos-1, s.hPos-1, H, W) #up-left state s.transitions["West"] = {d1: [0.8, Cost(states, d1)], d2: [0.1, Cost(states, d2)], d3: [0.1, Cost(states, d3)]} ##----------------------------------Solution--------------------------------## epsilon = 0.01 discount = 0.95 maxIter = 150 V0 = [0]*n_states [policy , V, i, Res] = VI(states, discount, epsilon, maxIter, V0)
#!/usr/bin/env python3 # Created by Ryan Nguyen # Created on January 2021 # This program uses functions to create # a mailing address def Construct_address(addressee, street_number, street_name, city, province, postal, apartment=None): # puts the mailing address together address = addressee + "\n" # process if apartment is not None: address = address + apartment + "-" address = address + street_number + " " + street_name + "\n" + \ city + " " + province + " " + postal # output return address def main(): # gets input and displays final output apartment = None addressee = input("Enter addressee: ") question = input("Do you have an apartment number? (yes/no): ") if question == 'yes': apartment = input("Enter apartment number: ") elif question != 'no': apartment = 'invalid' street_number = input("Enter street number: ") street_name = input("Enter street name: ") city = input("Enter city: ") province = input("Enter province: ") postal = input("Enter postal code: ") print("") # call function if apartment != 'invalid': if apartment is not None: full_address = Construct_address(addressee, street_number, street_name, city, province, postal, apartment) else: full_address = Construct_address(addressee, street_number, street_name, city, province, postal) else: print("Please enter yes or no: Do you have an apartment number?") # output print(full_address) if __name__ == "__main__": main()
""" Problem Link: https://practice.geeksforgeeks.org/problems/sort-a-stack/1 Given a stack, the task is to sort it such that the top of the stack has the greatest element. Input: The first line of input will contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains an integer N denoting the size of the stack. Then in the next line are N space separated values which are pushed to the the stack. Output: For each test case output will be the popped elements from the sorted stack. Constraints: 1<=T<=100 1<=N<=100 Example(To be used only for expected output): Input: 2 3 3 2 1 5 11 2 32 3 41 Output: 3 2 1 41 32 11 3 2 Explanation: For first test case stack will be 1 2 3 After sorting 3 2 1 When elements popped : 3 2 1 """ if __name__=='__main__': t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().strip().split())) sorted(arr) for e in range(len(arr)): print(arr.pop(0), end=" ") print() ''' Please note that it's Function problem i.e. you need to write your solution in the form of Function(s) only. Driver Code to call/invoke your function is mentioned above. ''' # your task is to complete this function # function sort the stack such that top element is max # funciton should return nothing # s is a stack def sorted(s): # Code here tempStack = [] while s: temp = s.pop() while tempStack and tempStack[-1] > temp: s.append(tempStack.pop()) tempStack.append(temp) while tempStack: s.append(tempStack.pop())
""" Given a stream of characters consisting only '0' and '1', print the last index of the '1' present in it. Input stream may either be sorted in decreasing order or increasing order. If not present than print "-1". Input: First line of the input contains the number of test cases (T) , T lines follow each containing a stream of characters. Output: Corresponding to every test case , output the last index of 1 present. Example: Input: 2 00001 1 Output: 4 0 """ t = int(input()) while t > 0: s = input() print(s.rfind('1')) t -= 1
""" Problem Link: https://practice.geeksforgeeks.org/problems/missing-number-in-array/0 Given an array C of size N-1 and given that there are numbers from 1 to N with one element missing, the missing number is to be found. Input: The first line of input contains an integer T denoting the number of test cases. For each test case first line contains N, size of array. The ssubsequent line contains N-1 array elements. Output: Print the missing number in array. Constraints: 1 ≤ T ≤ 200 1 ≤ N ≤ 107 1 ≤ C[i] ≤ 107 Example: Input: 2 5 1 2 3 5 10 1 2 3 4 5 6 7 8 10 Output: 4 9 Explanation: Testcase 1: Given array : 1 2 3 5. Missing element is 4. """ for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) actual_sum = n*(n+1)//2 arr_sum = sum(arr) print(actual_sum-arr_sum)
""" Problem Link: https://practice.geeksforgeeks.org/problems/alone-in-couple/0 In a party everyone is in couple except one. People who are in couple have same numbers. Find out the person who is not in couple. Input: The first line contains an integer 'T' denoting the total number of test cases. In each test cases, the first line contains an integer 'N' denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array. (N is always odd) Output: In each seperate line print number of the person not in couple. Constraints: 1<=T<=30 1<=N<=500 1<=A[i]<=500 N%2==1 Example: Input: 1 5 1 2 3 2 1 Output: 3 """ for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) res = 0 for i in arr: res ^= i print(res)
""" Problem Link: https://practice.geeksforgeeks.org/problems/element-appearing-once2552/1 Given a sorted array A[] of N positive integers having all the numbers occurring exactly twice, except for one number which will occur only once. Find the number occurring only once. Example 1: Input: N = 5 A = {1, 1, 2, 5, 5} Output: 2 Explanation: Since 2 occurs once, while other numbers occur twice, 2 is the answer. Example 2: Input: N = 7 A = {2, 2, 5, 5, 20, 30, 30} Output: 20 Explanation: Since 20 occurs once, while other numbers occur twice, 20 is the answer. Your Task: You don't need to read input or print anything. Your task is to complete the function search() which takes two arguments(array A and integer N) and returns the number occurring only once. Expected Time Complexity: O(Log(N)). Expected Auxiliary Space: O(1). Constraints 0 < N <= 10^6 0 <= A[i] <= 10^9 """ class Solution: def search(self, A, N): unique_element = A[0] for index in range(1, N): unique_element ^= A[index] return unique_element
""" Given an integer array, for each element in the array check whether there exist a smaller element on the next immediate position of the array. If it exist print the smaller element. If there is no smaller element on the immediate next to the element then print -1. Input: The first line of input contains an integer T denoting the number of test cases. The first line of each test case contains an integer N, where N is the size of array. The second line of each test case contains N integers sperated with a space which is input for the array arr[ ] Output: For each test case, print the next immediate smaller elements for each element in the array. Sample Input 2 5 4 2 1 5 3 6 5 6 2 3 1 7 Sample Output 2 1 -1 3 -1 -1 2 -1 1 -1 -1 """ for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) for i in range(n-1): if arr[i] > arr[i+1]: print(arr[i+1],end=' ') else: print(-1,end=' ') print(-1,end=' ') print()
""" Problem Link: https://practice.geeksforgeeks.org/problems/series-gp/0 Given the first 2 terms A and B of a Geometric Series. The task is to find the Nth term of the series. Input: First line contains an integer, the number of test cases 'T'. T testcases follow. Each test case in its first line contains two positive integer A and B (First 2 terms of GP). In the second line of every test case it contains of an integer N. Output: In each seperate line print the Nth term of the Geometric Progression. Print the floor ( floor(2.3)=2 ) of the answer. Constraints: 1 <= T <= 30 -100 <= A <= 100 -100 <= B <= 100 1 <= N <= 5 Example: Input: 2 2 3 1 1 2 2 Output: 2 2 Explanation: Testcase 2: The second term of series whose common ratio is 2 will be 2. """ for _ in range(int(input())): a,b = map(int,input().split()) n = int(input()) r = b/a print(int(a*(r**(n-1))))
""" Problem Link: https://practice.geeksforgeeks.org/problems/consecutive-elements/0 For a given string delete the elements which are appearing more than once consecutively. All letters are of lowercase. Input: The first line contains an integer 'T' denoting the total number of test cases. In each test cases, a string will be inserted. Output: In each seperate line the modified string should be output. Constraints: 1<=T<=31 1<=length(string)<=100 Example: Input: 1 aababbccd Output: ababcd """ for _ in range(int(input())): s = list(input()) index = 0 for i in range(len(s)-1): if s[i] != s[i+1]: s[index] = s[i] index += 1 s[index] = s[-1] print("".join(s[:index+1]))
""" Problem Link: https://practice.geeksforgeeks.org/problems/pascal-triangle/0 Given a positive integer K, return the Kth row of pascal triangle. Pascal's triangle is a triangular array of the binomial coefficients formed by summing up the elements of previous row. Example : 1 1 1 1 2 1 1 3 3 1 For K = 3, return 3rd row i.e 1 2 1 Input: First line contains an integer T, total number of test cases. Next T lines contains an integer N denoting the row of triangle to be printed. Output: Print the Nth row of triangle in a separate line. Constraints: 1 ≤ T ≤ 50 1 ≤ N ≤ 25 Example: Input: 1 4 Output: 1 3 3 1 """ for _ in range(int(input())): line = int(input()) no = 1 for i in range(1,line+1): print(no,sep=' ',end=' ') no = no * (line-i)//i print()
""" Problem Link: https://practice.geeksforgeeks.org/problems/finding-middle-element-in-a-linked-list/1 Given a singly linked list of N nodes. The task is to find middle of the linked list. For example, if given linked list is 1->2->3->4->5 then output should be 3. If there are even nodes, then there would be two middle nodes, we need to print second middle element. For example, if given linked list is 1->2->3->4->5->6 then output should be 4. Input: First line of input contains number of testcases T. For each testcase, first line of input contains length of linked list and next line contains data of nodes of linked list. Output: For each testcase, there will be a single line of output containing data of middle element of linked list. User Task: The task is to complete the function getMiddle() which takes head reference as the only argument and should return the data at the middle node of linked list. Constraints: 1 <= T <= 100 1 <= N <= 100 Example: Input: 2 5 1 2 3 4 5 6 2 4 6 7 5 1 Output: 3 7 Explanation: Testcase 1: Since, there are 5 elements, therefore 3 is the middle element at index 2 (0-based indexing). """ # Node Class class node: def __init__(self, val): self.data = val self.next = None # Linked List Class class Linked_List: def __init__(self): self.head = None def insert(self, val): if self.head == None: self.head = node(val) else: new_node = node(val) temp = self.head while(temp.next): temp=temp.next temp.next = new_node def createList(arr, n): lis = Linked_List() for i in range(n): lis.insert(arr[i]) return lis.head if __name__=='__main__': t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().strip().split())) head = createList(arr, n) print(findMid(head).data) ''' Please note that it's Function problem i.e. you need to write your solution in the form of Function(s) only. Driver Code to call/invoke your function is mentioned above. ''' # your task is to complete this function # function should return index to the any valid peak element def findMid(head): # Code here slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow
""" Problem Link: https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/maximize-the-earning-137963bc-323025a6/ """ def rupeesEarned(buildings,cost): height = -1 count = 0 for building in buildings: if building > height: count += 1 height = building return count*cost for _ in range(int(input())): n,r = map(int,input().split()) buildings = list(map(int,input().split())) print(rupeesEarned(buildings,r))