blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0c2755a032e50dfceb223b05ba8779b1c994f868 | BrendanStringer/CS021 | /Assignment 07.0/lineNumbers.py | 1,437 | 4.125 | 4 | #Brendan L. Stringer
#CS 021
#lineNumbers.py
#This program will print this function with line numbers while handling errors gracefully.
def main():
#Open error handling
try:
#Get the file name from the user
programName = input('Enter the program name you want to read from. ')
#Open the file to read from
readProgram = open(programName, 'r')
#Strip the .py file extension
programName = programName.rstrip('py')
#Open the file to write to
writeProgram = open('ln_' + programName + 'txt', 'w')
#Initialize the line counter
count = 1
#Print the contents of programName
for line in readProgram:
#Write the line of code to the write file
writeProgram.write(str(count) + ': ' + line)
#Advance the line counter
count += 1
#Close the files
readProgram.close()
writeProgram.close()
#Here is all the errors are handled
except NameError as err:
print('\n')
print('Please check the syntax of your file name.')
print('The error message is displayed below.')
print(err)
print('\n')
except IOError as err:
print('\n')
print('The file you specified does not exist.')
print('Please check the syntax of your input.')
print('The error message is displayed below.')
print(err)
print('\n')
except Exception as err:
print('\n')
print('There was an unknown error.')
print('The error message is displayed below.')
print(err)
print('\n')
#Run the main funciton
main() | true |
1262ac082637bbbd483480e84920d45cd709a9c4 | lucasoliveiraprofissional/Cursos-Python | /Curso em Video/desafio063b.py | 623 | 4.21875 | 4 | '''Escreva um programa que leia um numero
n inteiro qualquer o mostre na tela os n
primeiros elementos de uma sequencia de
fibonacci'''
'''Precisei fazer desafio063b.
Tentei pensar no algoritmo fibonacci
em Python e não consegui.'''
n= int(input('Quantos termos voce quer mostrar? '))
t1= 0
t2= 1
print('{} → {}'.format(t1, t2), end='')
cont= 3
#vai começar desse modo pois já temos os
#termo 1 e 2
while cont <= n:
t3= t1 + t2
print(' → {}'.format(t3), end='')
cont += 1
t1= t2
t2= t3
#para fazer com que os termos vão andando
#e pegando sempre o proximo valor.
print(' → Fim')
| false |
2d2ae56fd77181bb65ade1822ed477353638f009 | lucasoliveiraprofissional/Cursos-Python | /Curso em Video/aula018.py | 919 | 4.15625 | 4 | '''Na verdade é aula017(Parte 2) - Listas, mas quis nomear assim.'''
teste= list()
teste.append('Gustavo')
teste.append(40)
print(teste)
galera= list()
galera.append(teste)
'''Como no exemplo antes da aula pratica,
o correto a se fazer nesse caso é:
galera.append(teste[:]) nas 2x que damos append'''
'''é possível dar print de apenas alguns dados separados da lista.
Neste caso por exemplo só o nome, ou só a idade.'''
galera= [['João',19],['Ana',33],['Joaquim',13],['Maria',45]]
for p in galera:
print(f'{p[0]} tem {p[1]} anos de idade.')
'''É possível usar uma lista auxiliar e gravar esses dados dela
em uma lista fixa:'''
galera= list()
dado= list()
for c in range(0, 3):
dado.append(str(input('Nome: ')))
dado.append(int(input('Idade: ')))
galera.append(dado[:])
dado.clear()
print(galera)
for p in galera:
if p[1] >= 21:
print(f'{p[0]} é maior de idade.')
| false |
a7a299da0a25649757f860b0430dfff034c071b6 | lucasoliveiraprofissional/Cursos-Python | /Ignorancia Zero/aula015.py | 629 | 4.21875 | 4 | '''Dizemos que um número natural é triangular se ele é produto
de três números naturais consecutivos.
Ex.: 120 é triangular, pois 4.5.6 == 120.
Dado um inteiro não-negativo n, verificar se n é triangular.'''
#40 por ex é triangular?
#a menor possibilidade que temos é:
#1x2x3 == 6, precisamos ir testando 1 a 1 até
#chegar ao número desejado.
#2x3x4 == 24
#3x4x5 == 60
num= int(input('Digite um numero inteiro não negativo: '))
i= 1
while i * (i + 1) * (i + 2) < num:
i+= 1
if i * (i + 1) * (i + 2) == num:
print('{} é triangular'.format(num))
else:
print('{} não é triangular'.format(num))
| false |
e1db6f3966fed82a233ed700be4945d18abf181f | lucasoliveiraprofissional/Cursos-Python | /Curso em Video/desafio098.py | 533 | 4.1875 | 4 | '''Faça um programa que tenha uma função
chamada contador(), que receba três parâmetros:
início, fim e passo e realize a contagem.
Seu programa tem que realizar três contagens
através da função criada:
A) De 1 até 10, de 1 em 1
B) De 10 até 0, de 2 em 2
C) Uma contagem personalizada.'''
def contador(inicio, fim, passo):
if i < f:
#programa principal:
i= int(input('Digite o numero de inicio: '))
f= int(input('Digite o numero do fim: '))
p= int(input('Digite o numero do passo: '))
contador(i, f, p) | false |
b664415631a3dc04ecfcc31675099fb8e22a85ad | lucasoliveiraprofissional/Cursos-Python | /Ignorancia Zero/aula022.py | 872 | 4.15625 | 4 | '''A função print: formatação'''
'''O depto Estadual de Meteorologia lhe contratou para desenvolver
um programa que leia um conjunto indeterminado de temperaturas,
e informe ao final a menor e a maior temperatura informadas, bem
como a média das temperaturas.'''
num= int(input('Digite o número de temperaturas registradas: '))
soma= maior= menor= float(input('Digite a temperatura 1: '))
#como o usuario ja digitou a primeira, iniciaremos o for
#a partir da segunda.
for i in range(2, num+1):
temp= float(input('Digite a temperatura {}: '.format(i)))
if temp > maior:
maior= temp
if temp < menor:
menor= temp
soma += temp
print('A maior temperatura é: {:.2f}ºC'.format(maior))
print('A menor temperatura é: {:.2f}ºC'.format(menor))
print('A média das temperaturas é: {:.2f}ºC'.format(soma/num)) | false |
b8d070a8b66aca58658b541b2d892ed297cdfc3f | lucasoliveiraprofissional/Cursos-Python | /Ignorancia Zero/aula029.py | 1,277 | 4.25 | 4 | '''For loops e listas'''
'''dá para fazer loops com o range assim também:
numeros= [1,2,3,4]
for i in range(len(numeros)):
print(numeros[i])
ou
for i in numeros:
print(i)
O range é uma sequencia de numeros.
O vetor é uma sequencia de dados, que nesse caso são numeros.
Entao, nesse caso não é preciso usar o range, pois ambos são
sequencia de numeros.
'''
'''Faça um programa que peça as quatro notas de 10 alunos, calcule e armazene num vetor
a média de cada aluno, imprima o número de alunos com média maior ou igual a 7.0'''
'''Dica: quando há um numero determinado de loops que serão feitos, crie uma variavel
que receberá esse número de loops, para se preciso, alterá-la rapida de facilmente
no inicio do programa onde está a declaração de variáveis.
Nesse caso é a alunos= 10'''
alunos= 10
medias= []
for i in range(1, alunos+1):
#para receber as 4 notas:
notas= 0
for j in range(1, 5):
notas+= float(input('Digite a nota {} de 4 do aluno {} de {}: '.format(j, i, alunos)))
notas /= 4
medias.append(notas)
#para fazer o processamento das notas >= 7
num= 0
for media in medias:
if media >= 7.0:
num+= 1
print('O número de alunos com média maior ou igual a 7.0 é: {}'.format(num))
| false |
c9b36c239162728b033a8c3f28653e8227feaf61 | lucasoliveiraprofissional/Cursos-Python | /Curso em Video/desafio102b.py | 878 | 4.46875 | 4 | '''Crie um programa que tenha uma função fatorial()
que receba dois parâmetros: o primeiro que indique o
número a calcular e o 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.'''
'''Fiz versão b pois gostaria de saber como ele
solucionaria isso.'''
def fatorial(n, show= False):
"""
Calcula o fatorial de um número.
:param n: O número a ser calculado.
:param show: (opcional), Mostrar ou não a conta.
:return: O valor do Fatorial de um número n.
"""
f= 1
for c in range(n, 0, -1):
if show:
print(c, end='')
if c > 1:
print(' x ', end='')
else:
print(' = ', end='')
f *= c
return f
# Programa Principal:
print(fatorial(5, show= False))
help(fatorial)
'''O interessante é que o parâmetro opcional para funções booleanas é o False'''
| false |
c2f490da17fb75c0c0c939686a03ccf422ab4c80 | lucasoliveiraprofissional/Cursos-Python | /Ignorancia Zero/aula047_ex4.py | 2,188 | 4.3125 | 4 | '''
Faça um programa que faça 5 perguntas para uma pessoa sobre um crime.
As perguntas são:
a. "Telefonou para a vítima?"
b. "Esteve no local do crime?"
c. "Mora perto da vítima?"
d. "Devia para a vítima?"
e. "Já trabalhou com a vítima?"
O programa deve no final emitir uma classificação sobre a participação da pessoa
no crime.
Se a pessoa responder positivamente a 2 questões ela deve ser classificada como
"Suspeita", entre 3 e 4 como "Cúmplice" e 5 como "Assassino".
Caso contrário, ele será classificado como "Inocente".
'''
global suspeito, a, b, c, d, e
def main():
a= input('a. Telefonou para a vítima? [s/n]: ')
while tudoMaiusculo(a) != 'S' or tudoMaiusculo(a) != 'N':
a= ('Resposta inválida! Digite novamente [s/n]: ')
pergunta(a)
b = input('a. Esteve no local do crime? [s/n]: ')
while tudoMaiusculo(b) != 'S' or tudoMaiusculo(b) != 'N':
b= ('Resposta inválida! Digite novamente [s/n]: ')
pergunta(b)
c = input('a. Mora perto da vítima? [s/n]: ')
while tudoMaiusculo(c) != 'S' or tudoMaiusculo(c) != 'N':
c= ('Resposta inválida! Digite novamente [s/n]: ')
pergunta(c)
d = input('a. Devia para a vítima? [s/n]: ')
while tudoMaiusculo(d) != 'S' or tudoMaiusculo(d) != 'N':
d= ('Resposta inválida! Digite novamente [s/n]: ')
pergunta(d)
e = input('a. Já trabalhou com a vítima? [s/n]: ')
while tudoMaiusculo(e) != 'S' or tudoMaiusculo(e) != 'N':
e= ('Resposta inválida! Digite novamente [s/n]: ')
pergunta(e)
juiz()
def juiz():
global suspeito
if suspeito <= 1:
print('Inocente')
elif suspeito == 2:
print('Suspeita')
elif 4 >= suspeito <= 3:
print('Cúmplice')
else:
print('Assassino')
def pergunta(string):
global suspeito
if tudoMaiusculo(string) == 'S':
suspeito += 1
else:
suspeito += 0
return suspeito
def tudoMaiusculo(string):
maiusculo= ''
for char in string:
if 'a' <= char <= 'z':
char= chr(ord(char) - (ord('a') - ord('A')))
maiusculo += char
return maiusculo
main() | false |
35a9e034328dd5b62623c8f0d0815c840cea1a17 | lucasoliveiraprofissional/Cursos-Python | /Curso em Video/desafio099.py | 485 | 4.125 | 4 | '''Faça um programa que tenha uma função
chamada maior(), que receba vários
parâmetros com valores inteiros.
Seu programa tem que analisar todos os
valores e dizer qual deles é o maior.'''
valor= 0
def maior(num):
mai= 0
if valor > mai:
mai= valor
while True:
valor= int(input('Digite um número: '))
maior(valor)
resp= str(input('Quer continuar? [S/N] ')).strip().upper()[0]
if resp == 'N':
break
print(f'O maior valor é: {mai}') | false |
ee55fc8d29595d66d91dc6cc6ca850d0e36cceb1 | lucasoliveiraprofissional/Cursos-Python | /Curso em Video/desafio027.py | 2,484 | 4.15625 | 4 | '''Fazer um programa que leia o nome completo de uma pessoa
mostrando em seguida o primeiro e o último nome separadamente'''
'''De acordo com a aula 09 o len pode ser usado
O len pode ser usado para medir a quantidade de qualquer coisa
Por exemplo, saber a quantidade de sobrenomes que uma pessoa tem:
quant= nome.split() - poderia ter evitado essa variável quant,
mas para ficar mais explícito, estou fazendo ess exemplo assim
(len(quant)-1)
fiz len-1 porque temos que considerar que o primeiro nome da pessoa
não pode ser considerado um sobrenome.
essa linha será exibida no print como a quantidade de sobrenomes que
a pessoa tem.
no desafio 022, fiz o seguinte:
print('A quantidade de caracteres do seu primeiro nome é: {0}\n'.
format(len(nome.split()[0])))
peguei/separei/isolei o nome.split, o indice 0 desse vetor, que nesse caso é o nome
e, num parenteses antes dele, que será feito depois do split,
contei a quantidade de caracteres dentro desse indice 0 do vetor nome.
o que eu tenho que fazer para exibir o sobrenome da pessoa, uma das formas de se fazer
que é a que eu farei:
vou fazer um nome.split
depois contar com o len a quantidade de elementos que tem dentro de nome.split.
Se no total, tiverem 4 elementos dentro de nome.split,
tenho que considerar 04 indo do índice 0 ao 3, porém não
04 como sendo o último índice do vetor, pois o último índice do
vetor é 03.
Sendo assim, para fazer qualquer coisa com o último sobrenome,
tenho que fazer a contagem de todos os elementos de nome.split
e no fim subtrair 01 dessa conta. Aí sim estarei trabalhando
com o último elemento daquele vetor.
len(nome.split()-1) - assim me refiro ao último elemento
nome.split()[(len(nome.split()-1))]
assim eu digo que, após separar o nome, vou trabalhar com o índice que
refere-se ao seu último elemento.
format(nome.split()[(len(nome.split()-1))] - assim ficará o format
(não sei se precisa dentro do [] desse primento parenteses que engloba
o len-1), mas vou testar mesmo assim, pode ser que não precise
print('último= {}\n'.format(nome.split()[(len(nome.split())-1))]))
'''
nome= str(input('Digite seu nome completo: ')).strip()
print('\nprimeiro: {}'.format(nome.split()[0]))
print('último: {}'.format(nome.split()[(len(nome.split())-1)]))
'''Consegui sozinho!!!, acho que esse foi o mais difícil
Tentei transformar o split em int(nome.split()), mas isso não daria certo
por isso usei o len, que pega a quantidade de algo, já em int''' | false |
71a77e24fac05791295ce177336b767ec4784dd1 | lucasoliveiraprofissional/Cursos-Python | /Ignorancia Zero/aula041.py | 712 | 4.375 | 4 | '''Lambda:'''
def soma(x, y, z):
return x+y+z
a= soma
a(1, 2, 3)
f= (lambda x, y, z: x + y + z)
print(f'{f(1, 2, 3)}')
'''O Lambda nesse caso tem a mesma função que a função soma().
Ou seja, ele adere a função que atribuimos a ele.
O lambda precisa de uma variável.'''
'''sintaxe:
variavel = (lambda <argumentos da expressão>: <o que voce quer que retorne>)'''
'''Soma por exemplo não precisa de uma variavel.
Eu posso fazer uma soma(1, 2, 3) a qualquer momento no meu código.'''
'''Lambda fornece funções fáceis e simples que retornam um valor.'''
'''Lambda é chamado também de função anonima, pois ele não tem
nome definido como o soma()'''
'''Podem existir lambdas aninhados.''' | false |
7f635de8ddceb6a05dceee152a8a65e7cef811ce | lucasoliveiraprofissional/Cursos-Python | /Curso em Video/desafio094b.py | 2,378 | 4.25 | 4 | '''Crie um programa que leia nome, sexo
e idade de várias pessoas, guardando os
dados de cada pessoa em um dicionário e
todos os dicionários em uma lista. No
final, mostre:
A) Quantas pessoas foram cadastradas;
B) A média de idade do grupo;
C) Uma lista com todas as mulheres;
D) Uma lista com todas as pessoas
com idade acima da média.'''
'''Fiz versão B pois vacilei,
demorei para praticar python'''
galera= list()
pessoa= dict()
soma= media= 0
mulheres= list()
'''Como serão várias pessoas, há
necessidade de loop nisso.'''
while True:
pessoa['nome'] = str(input('Nome: '))
while True:
'''Para limpar o registro anterior.'''
pessoa.clear()
pessoa['sexo'] = str(input('Sexo [M/F]: ')).upper()[0]
if pessoa['sexo'] in 'MF':
break
else:
print('Digite o sexo corretamente na próxima vez!')
pessoa['idade']= int(input('Idade: '))
soma+= pessoa['idade']
if pessoa['sexo'] in 'F':
mulheres.append(pessoa['nome'])
galera.append(pessoa.copy())
while True:
resp= str(input('Deseja continuar? [S/N] ')).upper()[0]
if resp in 'SN':
break
print('Responda apenas S ou N.')
if resp == 'N':
break
print('')
'''A) quantas pessoas são cadastradas:'''
print(f'Ao todo temos {len(galera)} pessoas cadastradas.')
'''B) media das idades:'''
media= soma / len(galera)
print(f'A média das idades é de {media:.2f} anos.')
'''C) As mulheres cadastradas: '''
print(f'As mulheres cadastradas foram: ', end='')
for p in galera:
print(f'{p["nome"]} ', end='')
'''D) Lista de pessoas que estão acima da média: '''
print('As pessoas acima da média são: ', end='')
for p in galera:
if p['idade'] >= media:
print(' ')
for k, v in p.items():
print(f'{k} = {v}')
print('')
print('Encerrado')
'''O único detalhe é que eu queria calcular a média das idades
no print, sem precisar da variável soma, mas eu não ia acertar
tão fácil.'''
'''Ele estava com a ideia para mostrar as mulheres, mas não
funcionou:
For pra cada pessoa em galera:
for p in galera:
if p['sexo'] in 'Ff':
print(f'{p["nome"]} ', end='')
print('')
Eu tive que pegar e adicionar em uma lista as mulheres,
na medida que elas eram cadastradas. Essa foi a única
alteração do código.
''' | false |
e0ba92ef4dfd6872b4c95cf4f3865cddc7804207 | lucasoliveiraprofissional/Cursos-Python | /Curso em Video/desafio087.py | 728 | 4.125 | 4 | '''Aprimore o desafio anterior, mostrando
no final:
A) A soma de todos os valores pares
digitados.
B) A soma dos valores da terceira
coluna.
C) O maior valor da segunda linha.'''
matriz= [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
somapar= 0
terceira= 0
maior= [0, 0, 0]
for l in range(0, 3):
for c in range(0, 3):
matriz[l][c]= int(input(f'Digite um valor para [{l}, {c}]: '))
if matriz[l][c] % 2 == 0:
somapar += matriz[l][c]
if c == 2:
terceira += matriz[l][c]
if l == 1:
maior.append(matriz[l][c])
print(f'\nA soma de todos os valores pares é: {somapar}')
print(f'A soma dos valores da terceira coluna é: {terceira}')
print(f'O maior valor da segunda linha é: {max(maior)}') | false |
ceafeb6cb38c693e7a94b10eec4ea6f73ff1af33 | lucasoliveiraprofissional/Cursos-Python | /Ignorancia Zero/aula025.py | 760 | 4.5 | 4 | '''Introdução a listas'''
lista= [1,2,3,4,5,6,7,8,9]
print(lista[3])
print(lista[0])
#lista dentro de for:
#vai do elemento 0 ao 5
for i in range(6):
print(lista[i])
#existem indices negativos, a lista será exibida
#de tras pra frente
lista[-1]
#adicionar elementos na lista:
lista += [7]
print(lista)
#adicionar outra lista dentro da existente:
lista += [0, 0, 0]
print(lista)
#somar elementos dentro da lista:
soma= lista[6] + lista[2]
print(soma)
#mudar valores de elementos:
lista[2]= 7.7
print(lista[2])
#lista a partir de variaveis:
a, b, c, d = 1, 2, 3, 4
lista= [a,b,c,d]
print(lista)
#uma lista do fim ate o começo:
lista[::-1]
#podemos atribuir a uma variavel uma sublista ou uma lista já existente
a= lista[::-1]
print(a)
| false |
8880cace46a63a86d7fa2123f1d3ae72a547f49e | lucasoliveiraprofissional/Cursos-Python | /Ignorancia Zero/aula020.py | 760 | 4.1875 | 4 | '''Fazer um programa que colete 3 notas e calcule em seguida
a mensagem reprovado ou aprovado tem que aparecer se a nota
for menor ou maior igual a 7
se a média for 10, tem que ser aprovado com distincao'''
media= float(input('Digite a primeira nota:'))
media+= float(input('Digite a segunda nota:'))
media+= float(input('Digite a terceira nota:'))
media /= 3
if media == 10:
print('Aprovado com distinçao')
elif media >= 7:
print('Aprovado.')
print('Media {}'.format(media))
else:
print('Reprovado')
print('Media {}'.format(media))
#ou do seguinte jeito:
'''
if media >= 7 and media != 10:
print('Aprovado.')
elif media < 7:
print('Aprovado.')
print('Media {}'.format(media))
else:
print('Aprovado com distincao')
''' | false |
a50a134604ae4f19b800c271b1e043370450f4b5 | lucasoliveiraprofissional/Cursos-Python | /Curso em Video/desafio057.py | 435 | 4.1875 | 4 | '''Faça um programa que leia o sexo de uma
pessoa, mas só aceite os valores 'M' ou 'F'.
Caso esteja errado, peça a digitação novamente
até ter um valor correto.'''
sexo = str(input('Digite o sexo da pessoa: ')).upper()
while sexo not in 'MmFf':
sexo = str(input('Digite corretamente o sexo da pessoa: ')).upper()[0]
print('Fim')
'''Essa sintaxe tem que ser desse jeito. Não funcionou de outro modo,
o [0] não precisa.''' | false |
499ab1b66cf951fbbfc2268ef617232c35541d7f | lucasoliveiraprofissional/Cursos-Python | /Curso em Video/desafio049.py | 318 | 4.15625 | 4 | '''Refaça o desafio 009, mostrando a tabuada
de um número que o usuário escolher, só que
agora utilizando um laço for.'''
numero= int(input('Digite um número para saber sua tabuada: '))
print('')
for multiplicador in range(0, 11):
print('{} X {} = {}'.format(numero, multiplicador, numero * multiplicador)) | false |
8d4c3e11716be5289318221a0df5085f4a5b1103 | lucasoliveiraprofissional/Cursos-Python | /Ignorancia Zero/aula013ex3.py | 833 | 4.25 | 4 | '''
Dada uma sequencia de numeros inteiros não-nulos
seguida por 0, imprimir seus quadrados.
'''
'''
n = int(input('Digite o numero: '))
while n != 0:
n = int(input('Digite o numero: '))
print(n*n)
'''
'''Exercicios de casa: Soma de números positivos inteiros
e sequencia de numeros inteiros ímpares'''
#EXERCÍCIO DE CASA 01:
'''
n = int(input("Digite um número inteiro positivo: "))
x=0
soma=0
if n > 0:
while x < n:
soma += (n-x)
x+=1
print("A soma dos %d primeiros inteiros positivos é %d." %(n,soma))
else:
print("Digite apenas números inteiros positivos.")
'''
#EXERCÍCIO DE CASA 02:
'''
n = int(input("Digite um número inteiro positivo: "))
y=0
x=1
if n > 0:
while y < n:
print(x)
y+=1
x+=2
else:
print("Digite somente números inteiros positivos.")
''' | false |
3e91d39bf109e808b7ac8fb8181b5743a23c59e4 | lucasoliveiraprofissional/Cursos-Python | /Ignorancia Zero/aula026.py | 1,064 | 4.46875 | 4 | '''listas dentro de listas, adicionar novos elementos a listas(append)'''
#lista dentro de outra
#lista= [1,2,3,4,[1,2,3,4]]
#obter um dos elementos de uma lista assim:
#lista[4][2]
#criando várias listas dentro de uma:
#lista= [[[1, 2], [3, 4]], [5, 6]]
#lista[0] é [[1, 2], [3, 4]]
#lista[1] é [5, 6]
#lista[0][0] é [1, 2]
#lista[0][0][0] é 1
#lista[0][1][1] é 4
#lista += lista[0]
#= [[[1, 2], [3, 4]], [5, 6], [1, 2], [3, 4]]
#lista de tamanho n:
'''Faça um programa que leia um vetor de 5 numeros inteiros e mostre-os'''
#vetor é uma lista vazia
vetor= []
for i in range(1, 6):
num= int(input('Digite o numero {} de 5: '.format(i)))
vetor.append(num)
#assim conseguimos inserir um valor dentro do vetor, vai como parametro
#da funcao append o valor que o usuario for digitar, o valor que é incrementado
#no for ou o valor que quisermos.
print(vetor)
'''Método append acrescenta elementos depois do último elemento existente na lista.
Caso não haja nenhum, o elemento que será adicionado irá ao indice 0 da lista.''' | false |
c4739c56bf96b1885687de89f8f767596360b9b9 | EmilySerota/restaurant_ratings | /wordcount.py | 679 | 4.21875 | 4 | def wordcount(file_name):
"""takes in a file and prints out the set of words and the number of times each word occurs in the text file"""
word_counts = {} #create empty dictionary
all_words = [] #create empty list that will store words
import string
with open(file_name) as file:
for line in file:
line = line.rstrip()
words = line.split(" ")
all_words.extend(words) #put words into a single list
for word in all_words:
word = word.lower()
word = word.strip(string.punctuation)
word_counts[word] = word_counts.get(word, 0) + 1
for word in word_counts:
print(word, word_counts[word])
wordcount("test.txt") | true |
3bcb3562f256126aaca1a8186b6baddfb775a65c | seesee7164/FreeLanceWork | /Merge_Special.py | 1,917 | 4.15625 | 4 | # This is a special version of mergesort addapted for use in String_Full_Census
# The biggest difference is that it takes in a list containing tuples and
# sorts those from largest to smallest and sorting alphabetically amongst ties
# This function compares two string and returns true if the first one goes
# before the second alphabetically and false otherwise
def SortAlphabetically(string1, string2):
s1 = string1
s2 = string2
while(len(s1) > 0):
ascii1 = int(ord(s1[0]))
if ascii1 <= 122 and ascii1 >= 97:
ascii1 -= 32
ascii2 = int(ord(s2[0]))
if ascii2 <= 122 and ascii2 >= 97:
ascii2 -= 32
if ascii1 < ascii2:
return True
elif ascii1 > ascii2:
return False
s1 = s1[1:]
s2 = s2[1:]
return True
def mergesplit(List):
if len(List) > 2:
mid = len(List)//2
return mergesort(mergesplit(List[:mid]), mergesplit(List[mid:]))
elif len(List) == 2:
if List[0][1] > List[1][1]:
return List
elif List[0][1] == List[1][1]:
if SortAlphabetically(List[0][0],List[1][0]):
return List
else:
return [List[1],List[0]]
else:
return [List[1],List[0]]
else:
return List
def mergesort(List1, List2):
ret = []
while len(List1) > 0 and len(List2) > 0:
if List1[0][1] > List2[0][1]:
ret.append(List1[0])
List1.pop(0)
elif List1[0][1] == List2[0][1]:
if SortAlphabetically(List1[0][0],List2[0][0]):
ret.append(List1[0])
List1.pop(0)
else:
ret.append(List2[0])
List2.pop(0)
else:
ret.append(List2[0])
List2.pop(0)
if len(List1) > 0:
return ret + List1
else:
return ret + List2 | true |
c90535cb0a857fbe2310f0d80c37375b00ea3423 | poratGalpo/Desgin_patterns | /Singleton.py | 2,115 | 4.1875 | 4 | """
This code implements the singleton design patterns.
Ruler is a class that creates a single instance only,
if a second (third..fourth..etc.) instance is created, the first instance is returned.
"""
active_classes = {}
import random
def createRuler(x):
"""
This method is responsible for deferring between instances of Ruler class
:param x: str.
:return: string containing x
"""
return "This is ruler number {0}".format(x)
class Ruler():
"""
Ruler is the singleton class we wish to create only once
_instance will be the instance it of Ruler
"""
_instance = None
def create_instance(self,x):
return self.__new__(x)
def __new__(cls,x, *args, **kwargs):
if cls._instance == None:
Ruler._instance = createRuler(x)
return Ruler._instance
def singleton(cls):
global active_classes
def inner(*args, **kwargs):
if cls not in active_classes:
instance = cls(*args, **kwargs)
active_classes[cls] = instance
return active_classes[cls]
return inner()
@singleton
class Ruler2():
"""
Ruler2 creates is instance in a much more elegant manner
it uses a outer function as a decorator and a global variable that keeps track of
all the instances already created
"""
def __init__(self):
"""
To see if the instance is really the same, let us randomize some number upon instance creation
:return: None
"""
self.x = random.randint(0,100)
def __call__(self, *args, **kwargs):
return self.x
def __str__(self):
return str(self.x)
if __name__ == '__main__':
"""
Checking if the class we created correctly
"""
test_instance = Ruler()
ruler1 = test_instance.create_instance('6')
ruler2 = test_instance.create_instance('7')
abc = Ruler()
ruler3 = abc.create_instance('8')
print "Ruler1 : {0} \n Ruler2: {1}".format(ruler1,ruler3)
ruler3_prime = Ruler2()
ruler4_prime = Ruler2()
print "Ruler3 : {0} \n Ruler4: {1}".format(ruler3_prime,ruler4_prime)
| true |
b4d8ea697b8f4d74824ffc12d934f4da8c6044a1 | eeshita19/hacktober2021 | /palindrome.py | 781 | 4.53125 | 5 |
# This program performs palindrome check for a string #
# function which return reverse of a string
def isPalindrome(s):
# Calling reverse function
if len(s) <= 1 :
return True
if s[0] == s[len(s) - 1] :
return isPalindrome(s[1:len(s) - 1])
else :
return False
# Driver code
Palindrome_input_Variable = [ ' AnnA ' , ' SoloS ' , ' RotatoR ' , ' RadaR ' , ' SagaS ' , ' RotoR ' , ' TenT ' , ' RepapeR ' , ' CiviC ' , ' KayaK ' , ' Lever ' , ' MadaM ' , ' RacecaR ' , ' StatS ' , ' Redder ' , ' Wow ' , ' MoM ' , ' RefeR ' , ' NooN '] print( " PALINDROME CHECK PROGRAM " )
for i in Palindrome_input_Variable:
ans = isPalindrome(i)
if ans == 1:
print( " The given string ", "'" , i , "' ","is a palindrome")
else:
print( " The given string " , "'" , i , "' ","is not a palindrome")
| false |
47671f7f3d4ec36fac4e0410002f4d61cccf8822 | MarkusMueller-DS/Python-the-hard-way | /BMI.py | 579 | 4.5 | 4 | # Calculate BMI
print('Welcome to BMI calculator')
print('please input your data!')
height = float(input('How tall are you? (in m) '))
weight = float(input('How much do you weigh? (in kg) '))
BMI = weight / (height * height)
print(f'You have a BMI of {round(BMI)}')
if BMI <= 18.5:
print(f'With a BMI of {round(BMI)} you are Underweight')
elif BMI <= 24.9:
print(f'With a BMI of {round(BMI)} you are Normal to healthy weight')
elif BMI <= 29.9:
print(f'With a BMI of {round(BMI)} you are Overweight')
else:
print(f'With a BMI of {round(BMI)} you are Obese')
| false |
565be41d6018f0c8e5dc307eedf902627af970ed | serembon/codewars-python-kata | /6_kyu/Duplicate Encode.py | 1,056 | 4.125 | 4 | """
The goal of this exercise is to convert a string to a new string where each character in the new string is "("
if that character appears only once in the original string, or ")" if that character appears more than once in
the original string. Ignore capitalization when determining if a character is a duplicate.
```
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("
```
"""
# My solution
def duplicate_encode1(word):
iter_word = str(word.lower())
check_list = []
formatted_list = []
position = 0
for i in iter_word.lower():
position += 1
if i not in check_list and i not in (iter_word[position:]):
check_list.append(i)
i = '('
formatted_list.append(i)
else:
check_list.append(i)
i = ')'
formatted_list.append(i)
return ''.join(map(str, formatted_list))
# Best way
def duplicate_encode2(word):
return "".join(["(" if word.lower().count(c) == 1 else ")" for c in word.lower()])
| true |
de8c63d1fa8d65a499090cce37ba2bb3cb246182 | serembon/codewars-python-kata | /5_kyu/Rot13.py | 694 | 4.5625 | 5 | """ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the
alphabet. ROT13 is an example of the Caesar cipher.
Create a function that takes a string and returns the string ciphered with Rot13. If there are numbers or special
characters included in the string, they should be returned as they are. Only letters from the latin/english alphabet
should be shifted, like in the original Rot13 "implementation".
Please note that using ```encode``` is considered cheating."""
# My and best way solution
def rot13(message):
return ''.join([chr(ord(n) + (13 if 'Z' < n < 'n' or n < 'N' else -13)) if n.isalpha() else n for n in message])
| true |
5a3883f4a51dc66f862320b57695c6abd3e1249f | Caspeezie/TDDAssignments | /pi.py | 318 | 4.40625 | 4 | radius = input ("Type in value of radius: ")
print (radius, type(radius))
radius=int (radius)
print (radius, type (radius))
circumference1 = 2 * 3.142 *radius
print (circumference1, type (circumference1))
import math
circumference2 = 2 * math.pi *radius
print (circumference2, type (circumference2))
| false |
54646772013106a31d15fd1f0c77271f94a9e053 | mrpandrr/My_scripts | /Past Code/test_empty.py | 357 | 4.1875 | 4 |
choice = raw_input("\nPlease enter a 1 or 2 or nothing to quit: ")
if choice:
choice = int(choice)
if choice == 1:
print "You entered a 1!"
else:
if choice == 2:
print "You entered a 2!"
else:
print "You don't follow directions very well, do you?"
else:
print "Good bye!"
| true |
e2f4d287c528196661cb41ae45bc122b87811f1c | mrpandrr/My_scripts | /2.1.31/a116_traversing_turtles_AH.py | 1,067 | 4.25 | 4 | # a117_traversing_turtles.py
# Add code to make turtles move in a circle and change colors.
import turtle as trtl
# create an empty list of turtles
my_turtles = []
# use interesting shapes and colors
turtle_shapes = ["arrow", "turtle", "circle", "square", "triangle", "classic","arrow","circle"]
turtle_colors = ["red", "blue", "green", "orange", "purple","gold","pink","orange"]
for s in turtle_shapes:
t = trtl.Turtle(shape=s)
# setting last color in turtle_colors as turtle's color and then removing
# that color from turtle_colors
t.color(turtle_colors.pop())
t.penup()
my_turtles.append(t)
#Start at 0,0
#Variables equal = startx starty
startx = 0
starty = 0
heading = 90 #starting direction
# Loop go to 0,0 and right 45 forwrard 50 and then add 50 to x and y
for t in my_turtles:
t.pensize(10)
t.turtlesize(3)
t.goto(startx, starty)
t.setheading(heading)
t.pendown()
t.right(45)
t.forward(125)
# Adds spacing for variables
startx = t.xcor()
starty = t.ycor()
heading = t.heading()
wn = trtl.Screen()
wn.mainloop() | true |
c62c1db0cdcd968827e2d3950c4d017b38282fcf | newbility77/leet_python | /source/test_Q35_search_insert_position.py | 1,422 | 4.125 | 4 | """
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
"""
import unittest
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums or target <= nums[0]:
return 0
if target > nums[-1]:
return len(nums)
s, e = 0, len(nums) - 1
while s + 1 < e:
m = (s + e) // 2
nm = nums[m]
if nm == target:
return m
elif nm < target:
s = m + 1
else:
e = m - 1
if nums[s] == target:
return s
if nums[e] == target:
return e
return s + 1
class TestSolution(unittest.TestCase):
def test_search_insert(self):
sol = Solution()
self.assertEqual(2, sol.searchInsert([1, 3, 5, 6], 5))
self.assertEqual(1, sol.searchInsert([1, 3, 5, 6], 2))
self.assertEqual(4, sol.searchInsert([1, 3, 5, 6], 7))
self.assertEqual(0, sol.searchInsert([1, 3, 5, 6], 0))
| true |
e09f5296e851734edb6bad68c9450b78bd739ed5 | newbility77/leet_python | /source/test_Q7_reverse_interger.py | 1,034 | 4.28125 | 4 | """
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
"""
import unittest
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
xc = abs(x)
rev = 0
while xc != 0:
rev = rev * 10 + xc % 10
xc = xc // 10
rev = -rev if x < 0 else rev
return 0 if rev < -2**31 or rev > 2**31 - 1 else rev
class TestReverseInteger(unittest.TestCase):
def test_reverse_integer(self):
sol = Solution()
self.assertEqual(-321, sol.reverse(-123))
self.assertEqual(21, sol.reverse(120))
self.assertEqual(0, sol.reverse(1999999999))
| true |
3168145e2eaf6e5881dcf6240d57daf1f2c7c9dc | AdbreZz/quiz_adventure | /quiz.py | 1,558 | 4.125 | 4 | # Our quiz!
score = 0
name = ""
def quiz():
global name
name = input("Name: ")
question1()
question2()
question3()
replay = input("Try again (Y/N): ")
if replay.lower() == "y":
quiz()
def question1():
global score
global name
print("So", name, "which football player won the Ballon d'Or last year?")
answer = input("Answer: ")
if answer.lower() in "cristiano ronaldo":
print("Correct!")
score = score + 1
else:
print("Wrong!")
def question2():
global score
global name
print("Now", name, "which team won the Premier League last season?")
answer = input("Answer: ")
if answer.lower() in "leicester":
print("Correct!")
score = score + 1
else:
print("Wrong!")
def question3():
global score
global name
print("Finally, name one of the three teams who were relegated last season", name + ":")
answer = input("Answer: ")
if answer.lower() in "astonvillanewcastlenorwich":
print("Correct!")
score = score + 1
else:
print("Wrong!")
if score == 3:
print("Congratulations! You are a football expert!")
elif score == 2:
print("Good job! You know your stuff!")
elif score == 1:
print("Not great! You should watch more!")
else:
print("I think you are on the wrong quiz!")
# Leave this at the bottom - it makes quiz run automatically when you
# run your code.
if __name__ == "__main__":
quiz()
| true |
dfebeb8dec008809658829f9952f5c0f905559aa | v910423/Python-Ozon | /HW_4_text wo vowels.py | 894 | 4.25 | 4 | #Простой вариант с переменной translatedText вне функции:
# def translate(text):
# vowels = ["у", "е", "ы", "а", "о", "э", "я", "и", "ю", 'e', 'y', 'u', 'i', 'o', 'a']
# newText = []
# for i in range(len(text)):
# if text[i] not in vowels:
# newText.append(text[i])
# return("".join(newText))
#
# text = input('Enter the text: ')
# translatedText = translate(text)
# print(translatedText)
#Вариант с глобальной переменной translatedText
def translate(text):
vowels = ["у", "е", "ы", "а", "о", "э", "я", "и", "ю", 'e', 'y', 'u', 'i', 'o', 'a']
global translatedText
for letter in text:
if letter not in vowels:
translatedText.append(letter)
translatedText = []
text = input('Enter the text: ')
translate(text)
print("".join(translatedText))
| false |
25b22a561ec931bebaefb15fd487a45f0fb2adb1 | siverka/codewars | /MultiplesOf3or5/multiples_of_3_or_5.py | 475 | 4.40625 | 4 | """
https://www.codewars.com/kata/multiples-of-3-or-5
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.
Note: If the number is a multiple of both 3 and 5, only count it once.
"""
def multiples(number):
var = [i for i in range(number) if i % 3 == 0 or i % 5 == 0]
return sum(var)
| true |
93de390a576af2d687fdbb51663ae92729129eac | yidaiweiren/Python | /study/day8/元组.py | 551 | 4.375 | 4 | #元组
#元组中的元素不允许修改,后期开发中如果需要“不让修改”的值,可以考虑使用元组。不支持赋值
#元组不能使用“增,删,改”这几个功能,只能查询
a=(11,22)
#查看类型
print (type(a))
'''
<class 'tuple'> tuple就是元组
'''
print (a) #正常输出
'''
(11, 22)
'''
b=a #将a的值赋予b
print (b)
'''
(11, 22)
'''
#################################
c,d=a #相当于:c,d=(11,22),c=11,d=22,因为有两个变量在接收值,相当于拆包
print (c)
print (d)
'''
11
22
''' | false |
4cf005a3b3b21ececc5bf0c226e163e2cf829b72 | yidaiweiren/Python | /study2/day2/06生成器/02生成器的第一种创建方式.py | 437 | 4.25 | 4 | '''
生成器的第一种创建方式:将生成式的列表中括号改为元组的圆括号
当使用next()方法调用到最后一个值的洗一个值,程序就会崩掉
'''
a = [x*2 for x in range(10)]
print(a)
#生成器
b = (x*2 for x in range(10))
print(b)
print(next(b))
print(next(b))
print(next(b))
print(next(b))
print(next(b))
print(next(b))
print(next(b))
print(next(b))
print(next(b))
print(next(b))
print(next(b))
| false |
96cc5e6ea60c56db3c4f9dc1d7d78b9fbac4c2bb | slaneslane/PythonExamples | /CoreySchaferPythonCourse/dictionaries.py | 1,771 | 4.15625 | 4 | # dictionaries.py
# based on http://www.youtube.com/watch?v=daefaLgNkw0
student = {1: 'id', 'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
#print(student[1])
#print(student['name'])
#print(student['age'])
#print(student['courses'])
# better use this to not having a KeyError but None if key not found:
def printValues():
print(student.get(1, 'Not Found'))
print(student.get('name', 'Not Found'))
print(student.get('phone', 'Not Found'))
print(student.get('age', 'Not Found'))
print(student.get('courses', 'Not Found'))
print('\n')
printValues()
# change data inside the dictionary:
student['name'] = 'Jane'
student['phone'] = '077072772'
printValues()
# to update more then one value inside of the dictionary:
student.update({'name': 'Jack', 'age': 33, 'phone': '555-5555'})
printValues()
# removing key and value:
del student[1]
print(student)
print('\n')
# removing by pop with returning a value:
age = student.pop('age')
print(student)
print(age)
print('\n')
# looping trough dictionary:
print('Length: {}'.format(len(student)))
print('Keys: {}'.format(student.keys()))
print('Values: {}'.format(student.values()))
print('Items: {}'.format(student.items()))
print('\n')
# looping trough key:
for key in student:
print(key)
print('\n')
# looping trough items:
for key, value in student.items():
print(key, value)
print('\n')
# looping trough items more like generator:
for key, value in student.iteritems():
print(key, value)
print('\n')
# looping trough items using generator:
def studentGenerator():
for key, value in student.iteritems():
yield 'Key: "{}", and its value: "{}"'.format(key, value)
#yield key, value
new_student = studentGenerator()
for ns in new_student:
print(ns)
| true |
5c061ffe663aaeb3f76df3d5c1f6e881c0837b20 | Haplo-Dragon/MIT | /6.0001/problem_sets/ps4/ps4a.py | 2,152 | 4.3125 | 4 | # Problem Set 4A
# Name: Ethan Fulbright
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
"""
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of all permutations of sequence
Example:
>>> get_permutations('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Note: depending on your implementation, you may return the permutations in
a different order than what is listed here.
"""
# Base case - single character is the only permutation of itself
if len(sequence) == 1:
return list(sequence)
# Recursive case
first_character = sequence[0]
permutations = []
candidates = get_permutations(sequence[1:])
for candidate in candidates:
for position in range(len(candidate) + 1):
permutations.append(
candidate[:position] + first_character + candidate[position:])
return permutations
if __name__ == "__main__":
# #EXAMPLE
# example_input = 'abc'
# print('Input:', example_input)
# print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])
# print('Actual Output:', get_permutations(example_input))
# # Put three example test cases here (for your sanity, limit your inputs
# to be three characters or fewer as you will have n! permutations for a
# sequence of length n)
example_input = 'cat'
print('Input:', example_input)
print('Expected Output:', ['cat', 'act', 'atc', 'tac', 'tca', 'cta'])
print('Actual Output:', get_permutations(example_input))
example_input = 'dog'
print('Input:', example_input)
print('Expected Output:', ['dog', 'odg', 'ogd', 'god', 'gdo', 'dgo'])
print('Actual Output:', get_permutations(example_input))
example_input = 'emu'
print('Input:', example_input)
print('Expected Output:', ['emu', 'meu', 'mue', 'ume', 'uem', 'eum'])
print('Actual Output:', get_permutations(example_input))
| true |
12a404c2ef06c7d214da4ed648483e8e9cc37082 | gognlin/NeuralNetworks | /multilayer_perceptron/mlp_example.py | 854 | 4.25 | 4 | """
==============================================
Using multilayer perceptron for classification
==============================================
This uses multi-layer perceptron to train on a digits dataset. The example
then reports the training score.
"""
from sklearn.datasets import load_digits
from multilayer_perceptron import MultilayerPerceptronClassifier
# Load dataset
digits = load_digits()
X, y = digits.data, digits.target
# Create MLP Object
# Please see line 562 in "multilayer_perceptron.py" for more information
# about the parameters
mlp = MultilayerPerceptronClassifier(hidden_layer_sizes = (50, 20), \
max_iter = 200, alpha = 0.02)
# Train MLP
mlp.fit(X, y)
# Report scores
print "Training Score = ", mlp.score(X,y)
print "Predicted labels = ", mlp.predict(X)
print "True labels = ", y
| true |
058005f5f9d5a19a7a04f07de983ef692d1a185d | ravibpibs/assignment | /poweroftwo.py | 263 | 4.3125 | 4 | def is_power_of_two(n):
if n<=0:
return False
else:
return n & (n-1)==0
n=int(input('enter a number:'))
if is_power_of_two(n):
print('{} is a power of two.'.format(n))
else:
print('{} is not a power of two.'.format(n))
| true |
c7d53c2cf9bc973889cc1e9281864486efaf4e13 | wpiao/mycode | /custif/myflix.py | 1,369 | 4.21875 | 4 | #!/usr/bin/env python3
heros = ["Iron man", "Wanda", "Vision", "Captain America", "Falcon", "Ant man", "Hulk", "Thor", "Hawk eye", "Spider man", "Black widow", "Doctor strange"]
answers = ["Iron man", "Captain America", "Spider Man"]
chance = 6
while chance:
first = input(f"Guess my favorite Marvel heros in the following options. {heros}.\n> ").lower()
if first == answers[0].lower():
print(f"Correct! My favorite marvel hero is {first.title()}!")
while chance:
second = input(f"You still have {chance} chances left, so please guess my second favorite marvel hero.\n> ").lower()
chance = chance - 1
if second == answers[1].lower():
print(f"Congratulations! You got it right. My favorite marvel hero is {first.title()} and my second favorite is {second.title()}!")
break
elif chance:
print(f"Wrong! Try gussing my second favorite again. You have {chance} chance left!\n")
else:
print(f"My second favorite mavel hero is {answers[1]}")
break
else:
chance = chance - 1
print(f"Wrong! Try again, you have {chance} chances left!\n")
print(f"Great job on guessing whethere you got it right or not. My favorite marvel hero is {answers[0]} and my second favorite marvel hero is {answers[1]}.")
| true |
10c3310bbea09121a9430d7516aba2f76a6be2cf | ignatyug/python | /Properties/properties.py | 1,401 | 4.15625 | 4 | import sqlite3
def input_year():
max = 2019
min = 1900
while True:
try:
year = int(input('Enter year:\t'))
if min <= year <= max:
return year
else:
print('Year is not in the range')
except ValueError:
print('Not valid year!')
def input_square():
min = 20
max = 1000
while True:
try:
square = int(input('Enter square:'))
if min <= square <= max:
return square
else:
print('Square is not in the range')
except ValueError:
print('Not valid square!')
def input_district():
district = input('Enter district:')
return district
def search(year, square, district):
cursor = sqlite3.connect('Properties').cursor()
for row in cursor.execute('''select price
from properties
where year = ''' + str(year) + ''' AND square = ''' + str(square) + ''' AND district = \'''' + district + '''\'
order by price
limit 1'''):
print(row[0])
return
print('Nay nothing')
def main():
a = ' '
while a.casefold() != 'no':
year = input_year()
square = input_square()
district = input_district()
search(year, square, district)
a = input('If you want to continue, press enter: ')
print('By')
main()
| true |
9230cba9e2d24169bd955ceec298ae29ac82af33 | thomasp05/finalProject-ECSE429-Mutant-Simulator | /src/sut_binarySearch.py | 2,138 | 4.21875 | 4 | import sys
import os
def main():
answer = sutProgram()
print(answer)
# This code was taken from the website Geeks for Geeks
# https://www.geeksforgeeks.org/python-program-for-binary-search/
# Returns index of x in arr if present, else -1
def binarySearch (arr, l, r, x):
# Check base case
if r >= l:
mid = int(l + (r - l)/2)
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it can only
# be present in left subarray
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)
# Else the element can only be present in right subarray
else:
return binarySearch(arr, mid+1, r, x)
else:
# Element is not present in the array
return -1
def sutProgram():
if(len(sys.argv) != 12 ):
#print("\nThis program takes a list of integer arguments seperated by white spaces: \n" +
# "\n\tExample command: python sut.py 2 2 3 5 6 7 10 12 18 88 9")
# print("-1")
# exit()
return -1
else:
# Parse to make sure arguments are integers
for i in range(1, len(sys.argv)):
try:
arg = int(sys.argv[i])
except ValueError:
#print("Argument is not an integer. Please enter an integer and try again")
#print("-1")
return -1
myList = []
for item in sys.argv[1:]:
myList.append(int(item))
arr = myList[:-1]
r = len(myList[:-1])
x = myList[-1]
#Check if the element we are looking for is within the range of the list
if not(x >= arr[0] and x <= arr[-1]):
return -1
#check if array is sorted and call binary search if it is. Return -1 if it is not
flag = 0
i = 1
while i < len(arr):
if(arr[i] < arr[i - 1]):
flag = 1
i += 1
if flag == 1:
return -1
else:
f = binarySearch( arr, 0, r, x)
return f
if __name__ == '__main__':
main()
| true |
33bb6f0b58c628630b098d1d1242e18a3155e4c5 | balaprasanna/MIT-6.00.1.x-2k15 | /if-elif.py | 268 | 4.25 | 4 | x = int(raw_input("Enter an integer"))
if (x%2 == 0):
print("")
if (x%3 == 0):
print("")
print("Div by 2 and 3")
else:
print("")
print("Div by 2 and not by 3")
elif (x%3 == 0) :
print("");
print("Div by 3 not by 2")
| true |
6ae3062004d914b71799b5a251f7c19814bbcf6c | balaprasanna/MIT-6.00.1.x-2k15 | /for-loop-construct.py | 254 | 4.21875 | 4 | x = int(raw_input('ENTER A NUMBER TO FIND CUBE ROOT'))
x = abs(x)
ans = 0
for ans in range(0, x+1):
if (ans**3 == x):
break
if ans**3 != x:
print(str(x) + 'is not a perfect cube')
else:
print('Cube root of ' +str(x) +'is '+ str(ans) ) | true |
8b8374bca5b448328a6f1352ecf658c7961b9833 | sercanhocaoglu/LeetCode | /Parsing A Boolean Expression/Parsing A Boolean Expression.py | 1,626 | 4.15625 | 4 | '''
Return the result of evaluating a given boolean expression, represented as a string.
An expression can either be:
"t", evaluating to True;
"f", evaluating to False;
"!(expr)", evaluating to the logical NOT of the inner expression expr;
"&(expr1,expr2,...)", evaluating to the logical AND of 2 or more inner expressions expr1, expr2, ...;
"|(expr1,expr2,...)", evaluating to the logical OR of 2 or more inner expressions expr1, expr2, ...
Example 1:
Input: expression = "!(f)"
Output: true
Example 2:
Input: expression = "|(f,t)"
Output: true
Example 3:
Input: expression = "&(t,f)"
Output: false
Example 4:
Input: expression = "|(&(t,f,t),!(t))"
Output: false
Constraints:
1. 1 <= expression.length <= 20000
2. expression[i] consists of characters in {'(', ')', '&', '|', '!', 't', 'f', ','}.
3. expression is a valid expression representing a boolean, as given in the description.
'''
# Approach: Using Stack + HashSet
# 时间复杂度:O(n)
# 空间复杂度:O(n)
# 解法详解参考同名 java 文件 Approach 2
class Solution:
def parseBoolExpr(self, expression: str) -> bool:
stack = []
for c in expression:
if c == ')':
seen = set()
while stack[-1] != '(':
seen.add(stack.pop())
stack.pop()
operator = stack.pop()
stack.append(all(seen) if operator == '&' else any(seen) if operator == '|' else not seen.pop())
elif c != ',':
stack.append(True if c == 't' else False if c == 'f' else c)
return stack.pop() | true |
2b3b3a095c215a06d682e5cc6dde467a1cde3bdd | PistachioCake/TAMU-ENGR102 | /Lab11b/a.py | 1,683 | 4.1875 | 4 | # By submitting this assignment, I agree to the following:
# "Aggies do not lie, cheat, or steal, or tolerate those who do"
# "I have not given or received any unauthorized aid on this assignment"
#
# Name: Rushil Udani
# Section: 219
# Assignment: 11b Program 1
# Date: 02 11 2020
from typing import List
def main(names: List[str], costs: List[float], values: List[float]) -> str:
'''Input: three parallel lists of names (str), costs (float), and values
(floats). Ouptut: the name of the factory with the least profit'''
# Get name of factory with minimum profit
min_profit = values[0] - costs[0]
min_name = names[0]
for i, name in enumerate(names):
profit = values[i] - costs[i]
if profit < min_profit:
min_profit = profit
min_name = name
return min_name
# More concisely:
# factories = zip(names, costs, values)
# return min(factories, key=lambda factory:factory[2]-factory[1])[0]
# Test the function
while True:
names = []
costs = []
values = []
print('This will repeatedly ask you to enter the name of a factory, the\n'
'annual cost to operate it, and the value of the products produced\n'
'there. Leave the name blank to stop inputting. Then, it should tell\n'
'you the name of the least profitable factory of this list.\n')
name = input('Enter name:\t')
while name:
names.append(name)
costs.append(float(input('Enter cost:\t')))
values.append(float(input('Enter value:\t')))
name = input('Enter name:\t')
print()
print(main(names, costs, values))
again = input('Would you like to test again? [y/n] ')
if again.rstrip().lower().startswith('y'):
continue
else:
print('Goodbye!')
break
| true |
f727f131c0064e1c6b33d7de7c878dadb1ab02ca | dmil/python-playgroundd | /readwrite.py | 334 | 4.375 | 4 | # 1. reads name.txt into a variable my_name
with open('name.txt') as f:
my_name = f.read()
introduction = "Hello, my name is " + my_name
# 2. writes a new file named hello.txt with the contents
# Hello, my name is <my_name>.
with open('hello.txt', 'w') as f:
f.write(introduction)
f.write('\n')
# by: Dhrumil And Sultan | true |
82a1ecc1867b5a31f05c2b996d6098627aad0e67 | victorrrp/Python-Intermediario | /aula31_curso.py | 2,042 | 4.40625 | 4 | '''Sets em python (conjuntos)
* add(adiciona), update(atualiza), clear(limpa), discard
* union [ | ] (une)
* intersection [ & ] (todos os elementos presentes nos dois sets)
* difference [ - ] (elementos apenas no set da esquerda)
* symmetric_difference [ ^ ] (elementos que estão nos dois sets, mas não em ambos)
A maior diferença entre os sets, listas e tuplas é que os sets só suportam elementos unicos
Não há como acessar um valor específico num set pois o mesmo não tem índice
'''
#set (modo normal)
s1 = {1,2,3,4,5}
print(type(s1))
'''
para efeito de comparação
#tupla
t1 = (1,2,3,4,5)
print(type(t1))
#dicionário
d1 = {'1':'2'}
print(type(d1))
'''
#para criar um set vazio
s1 = set()
#para adicionar valor(add)
s1.add(1)
s1.add(2)
s1.add(3)
#para descartar valor(discard)
s1.discard(3)
#geralmente usa-se sets para eliminar elementos duplicados. ex.:
#pode acontecer de seus elementos voltarem fora de ordem
l1 = [1,1,'Victor',1,2,2,3,6,6,5,4,4,4,5,8, 'Victor', 'Victor']
l1 = set(l1)
l1 = list(l1)
print(l1)
#union no set (mostra todos os elementos excluindo os repetidos. ex.:)
s1 = {1,2,3,4,5}
s2 = {1,2,3,4,5,6}
s3 = s1|s2
print(s3)
#intersection no set (mostra todos os elementos presentes no set. o elemento
#que estiver em apenas um dos sets, é automaticamente eliminado. ex.:)
s1 = {1,2,3,4,5}
s2 = {1,2,3,4,5,6}
s3 = s1 & s2
print(s3)
#difference (mostra somente os elementos únicos no set da esquerda. ex.:)
s1 = {1,2,3,4,5,16,15}
s2 = {1,2,3,4,5,6}
s3 = s1 - s2
print(s3)
#symmetric difference no set (mostra somente os elementos unicos nos dois sets em questão. ex.:)
s1 = {1,2,3,4,5,7,9,11}
s2 = {1,2,3,4,5,6,8,10}
s3 = s1 ^ s2
print(s3)
#fazendo cast com set
l1 = ['Victor', 'Pereira', 'Silva']
l2 = ['Luiz', 'Maria', 'Joao', 'Joao', 'Joao', 'Joao', 'Joao', 'Luiz', 'Joao', 'Joao', 'Joao']
if set(l1) == set(l2):
print('L1 é igual a L2')
else:
print('L1 é diferente de L2') | false |
ed07cec7b5bf2419e3c50a4e83533e125fe57b25 | victorrrp/Python-Intermediario | /aula7_curso.py | 1,365 | 4.375 | 4 | '''Faça um programa que peça ao usuário para digitar um numero inteiro.
Informe se este numero é par ou impar. Caso o usuário não digite um numero
informe que nao é um numero inteiro.'''
num=input('digite um numero inteiro: ')
if num.isdigit():
num=int(num)
if num%2==0:
print('este numero é par')
elif num%2==1:
print('este numero é impar')
else:
print('Isso nao é um numero')
'''Faça um programa que pergunte a hora ao usuário e, baseando-se no horário descrito,
exiba a saudação apropriada. Ex. "Bom dia0-11, Boa tarde 12-17 e Boa noite18-23.'''
hora=(input("informe a hora(0-23): "))
if hora.isdigit():
hora=int(hora)
if hora<0 or hora>23:
print("Horario deve estar entre 0 e 23")
if hora <=11:
print("Bom dia!")
elif hora <=17:
print("Boa tarde!")
else:
print("Boa noite!")
'''Faça um programa que peça o primeiro nome do usuário. Se o nome tiver 4 letras ou
menos escreva "Seu nome é curto"; se tiver entre 5 e 7, escreva
"Seu nome é normal"; se for maior que 6 escreva "Seu nome é muito grande".'''
nome=input("Digite seu primeiro nome: ")
tamanho = len(nome)
if tamanho<=4:
print("Seu nome é curto")
elif tamanho<=6:
print("Seu nome é normal")
else:
print("Seu nome é grande") | false |
07b50f7f8627525eb3b6a69b90e2a3a6f0046e7e | victorrrp/Python-Intermediario | /aula16PT2_curso.py | 940 | 4.15625 | 4 | '''
*Split - Dividir uma string gerando uma lista
*Join - Transformar uma lista numa string
*Enumerate - Enumerar elementos da lista
'''
string1 = 'O Brasil é penta.' # string sem alteraçãos
lista1 = string1.split(' ') # utilizando split
string2 = ','.join(lista1) # utilizando join
print(string1)
print(lista1)
print(string2)
#demonstrando como o enumerate trabalha
lista = [
[0, 'O'],
[1,'Brasil'],
[2,'é'],
[3, 'penta'],
]
for indice, nome in lista:
print(indice, nome)
#utilizando enumerate
string = ['O', 'Brasil', 'é', 'penta']
for indice, valor in enumerate(string):
print(indice, valor)
#lista dentro de lista
lista = [
[1,2],
[3,4],
[5,6],
]
for v in lista:
print(v) #é possivel acessar o indice. ex.: print(v[0], v[1])
#forma de desempacotamento de lista
lista = ['Victor', 'Joao', 'Maria']
n1, n2, n3 = lista
print(n2) | false |
214397cad40607733035abd072a67beb0757ba7f | YLyeliang/now_leet_code_practice | /tree/Subtree_of_another_tree.py | 1,923 | 4.15625 | 4 | # Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
#
# Example 1:
# Given tree s:
#
# 3
# / \
# 4 5
# / \
# 1 2
# Given tree t:
# 4
# / \
# 1 2
# Return true, because t has the same structure and node values with a subtree of s.
#
#
# Example 2:
# Given tree s:
#
# 3
# / \
# 4 5
# / \
# 1 2
# /
# 0
# Given tree t:
# 4
# / \
# 1 2
# Return false.
# 解法一:遍历整个二叉树s,对于每个节点,判断其子树是否与二叉树t相同,如果相同,则返回true,else false. 该方法仍然利用递归方式,
# 判断两棵树是否相同,可以使用遍历的方式,明前当前节点的任务:如果两个节点同时为空,则两者相同,如果两个有一个非空,则不相同。然后剩下的交给递归去执行。
# 时间复杂度来说比较复杂, 因为每个具有相同值的节点均需进行依次判断,需要O(s*t)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
def isMatch(s, t):
if s is None and t is None: return True
if s is None or t is None: return False
if s.val == t.val:
if isMatch(s.left, t.left) and isMatch(s.right, t.right):
return True
else:
return False
if isMatch(s, t):
return True
if s is None:
return False
return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
| false |
876de5f60fe378f0c5025b8af6332290068d61a4 | YLyeliang/now_leet_code_practice | /tree/diameter_of_binary_tree.py | 1,293 | 4.34375 | 4 | # Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
#
# Example:
# Given a binary tree
# 1
# / \
# 2 3
# / \
# 4 5
# Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
#
# Note: The length of path between two nodes is represented by the number of edges between them.
# 分析:这个题目要求的是找到任意两个节点的最长路径。
# 先分析一下,对于每一个节点,它的最长路径=左子树最长路径+右子树最长路径,比如,值为2的节点,其最长路径为4-2-5,左右子树长度均为1.其最长为=1+1
# 比如值为1的节点,长度=2+1=3。
# 这样,就可以在遍历的时候,依次计算每个节点的长度,并取最大值得到最终的结果。
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
self.ans = 0
def depth(p):
if not p: return 0
left, right = depth(p.left), depth(p.right)
self.ans = max(self.ans, left + right)
return 1 + max(left, right)
depth(root)
return self.ans
| false |
37ed1f061303050c1960fce5909dd097fb302f07 | zero-one-group/zot-internship | /anthony/euler/problem_4.py | 812 | 4.34375 | 4 | """
A palindromic number reads the same both ways. The largest palindrome made from
the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
# Turn to string, than do negative indexing
def is_palindrome(n):
return str(n) == str(n)[::-1]
def two_digit_numbers():
return range(10, 100)
max(
x*y
for x in two_digit_numbers()
for y in two_digit_numbers()
if is_palindrome(x*y)
)
# max(
# x*y
# for x in range(10, 100)
# for y in range(10, 100)
# if str(x*y) == str(x*y)[::-1]
# )
def three_digit_numbers():
return range(100, 1000)
max(
x*y
for x in three_digit_numbers()
for y in three_digit_numbers()
if is_palindrome(x*y)
)
# Programming is about building abstractions.
| false |
e4621ae3430c20dac0240a244d559dc442fc31ad | ChengYuqin/Based | /a_03_list1.py | 844 | 4.34375 | 4 | names=['wangshan','zhangyanxia','zhouyiyuan','chengyuqin','zhuyin']
"""#print(names)
print("I want to have a dinner with "+names[0]+", "+names[1]+" and "+names[2])
print("But "+names[1]+" can't attend the dinner!")
names[1]="zhuyin"
names.append('wanglicui')
print("Due to I find a big desk. I want to have a dinner with "+names[0]+", "+names[1]+", "+names[2]+"and "+names[3])
#print("So I want to have a dinner with "+names[0]+", "+names[1]+" and "+names[2])"""
#names.sort()#姓名按照首字母排序了,永久性排序
#names.sort(reverse=True)#反向排序
print("Here is the original list:")
print(names)
print("Here is the sorted list:")
print(sorted(names,reverse=True))#临时排序,也可反排序
print("Here is the reversed list:")
names.reverse()#反向姓名列表。未排序
print(names)
print(len(names))#输出列表长度
| true |
6df775bd13fd9a55f7c8f356272fceb208b9acc1 | yusufceylann/GlobalAIHubPythonHomework | /Homework1.py | 588 | 4.125 | 4 | #calculation of body mass index
a = input("What is your name?")
print("Your name type is:", f'{type(a)}')
b = input("What is your surname?")
print("Your surname type is:", f'{type(a)}')
c = int(input("How old are you?"))
print("Your age type is:", type(c))
d = float(input("How many meters is your height?"))
print("Your height type is:", type(d))
e = float(input("What is your weight?"))
print("Your weight type is:", type(e))
s = float(d/(e**2))
print("Hi %s %s Your Height is: %.2f Weight is: %.2f and Your Age is: %d" % (a,b,d,e,c))
print("Your Body Mass İndex is: {}".format(s))
| true |
63e307b06cd007729ed0100284fd8f40f14ab041 | calsterbenz/wordguesser | /main.py | 2,586 | 4.25 | 4 | #Hangman Program
#Computers and Technology Programming Final
import random
words = ["house", "cars", "family", "stack", "python", "friend", "programming", "apple", "plane", "blueberry", "coffee", "control", "hangman", "final", "project", "taste", "food", "world", "challenge", "difficult", "launch", "grow", "white", "water", "taste", "smell"]
play = True
print("Welcome to the word guessing game! The rules are simple,\nyou get six tries to guess a word by entering in characters.\nHave the word? Type it in if you think you know it, but be careful as it will count against you. Also, you only get one guess at the word.\n")
while(play):
word = random.choice(words)
blank = ""
letterMem = ""
countDown = 6
i = 0
#Creates a value that contains a '*' for every character in the word.
for char in word:
blank += "*"
#Prints the beginning of the game
print("\nAre you ready to play? You better be.\nYour word is " + blank + ".")
#While loop runs 6 times to simulate a hangman
while(i < 6):
if(i >= 1):
print("Letters Used: " + letterMem)
print("Guess a letter or the word. " + str(countDown) + " guesses left.")
uIn = input()
while(uIn in letterMem):
print("\nYou have already tried that letter, try again.")
uIn = input()
letterMem += uIn + " "
#Checks if word was guessed right
if(uIn == word):
print("\nYou gueesed right! You win!")
break
elif(len(uIn) > 1):
print("\nThat was not the word. You lose! The word was " + word + ".")
break
#Checks if the users character they guessed is in the word and looks for repeat letters and replaces them in the correct index
charPos = 0
timesFound = 0
if(uIn in word):
for x in word:
if(x == uIn):
blank = blank[:charPos] + x + blank[charPos+1:]
timesFound += 1
charPos += 1
print("\nCorrect! " + uIn.upper() + " was in the word " + str(timesFound) + " time(s).\nYour word is now " + blank + ".")
elif(i < 5):
print("\nThe letter, " + uIn.upper() + ", is not in the word, try again")
i += 1
countDown -= 1
if(i == 6):
print("\nYou ran out of guesses! You lost. :( The word was " + word.upper() + ".")
elif('*' not in blank):
print("\nYou have won by filling in all the blanks! Congrats!")
break
#End of loop condition
print("Would you like to play again? y for YES, and n for NO")
playCon = input()
if(playCon == 'y'):
play = True
else:
print("\nThanks for playing! Hope to see you soon!")
break
| true |
42e317f9ed2c3cab669314d56385d448b628e780 | calebe-takehisa/repository_Python | /procedural_programming/ex011.py | 771 | 4.28125 | 4 | """
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 2m².
SAÍDA:
Largura da parede:
Altura da parede:
Sua parede tem a dimensão de ll.llxaa.aa e sua área é de m.mm m².
Para pintar essa parede, você precisará de t.tt litros de tinta.
"""
# Minha solução:
largura = input('Largura da parede: ')
altura = input('Altura da parede: ')
area = float(largura) * float(altura)
tinta = float(area)/2
print(f'Sua parede tem a dimensão de {float(largura):.1f}x{float(altura):.1f} e sua área é de {float(area):.1f}m².')
print(f'Para pintar essa parede, você precisará de {float(tinta):.1f}l de tinta.') | false |
ae6fec2c872509067adf59fdb43d4300ff9400c9 | calebe-takehisa/repository_Python | /procedural_programming/ex005.py | 671 | 4.25 | 4 | """
Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e seu antecessor.
SAÍDA:
Digite um número: 2
Analisando o valor 2, seu antecessor é 1 e o sucessor é 3.
"""
# Minha solução:
num = int(input('Digite um número: '))
print(f'Analisando o valor {num}, seu antecessor é {num-1} e o sucessor é {num+1}.')
# Solução do Professor:
n = int(input('Digite um número: '))
a = n - 1
s = n + 1
print('Analisando o valor {}, seu antecessor é {} e o sucessor é {}.'.format(n, a, s))
#ou
m = int(input('Digite um número: '))
print('Analisando o valor {}, seu antecessor é {} e o sucessor é {}.'.format(m, (m-1), (m+1))) | false |
71e44a3bb801e830e7a1810c3c5c43218c56f033 | calebe-takehisa/repository_Python | /procedural_programming/ex002.py | 384 | 4.15625 | 4 | """
Faça um programa que leia o nome de uma pessoa e mostre um mensagem de boas-vindas.
SAÍDA:
Digite seu nome: Calebe
É um prazer te conhecer, Calebe!
"""
# Minha solução:
nome = input('Digite seu nome: ')
print(f'É um prazer te conhecer, {nome}!')
# Solução do Professor:
nome = input('Digite seu nome: ')
print('É um prazer te conhecer, {}!'.format(nome)) | false |
2e0cb97f916ecc17a3b4bf8a8616aed66f3f470d | calebe-takehisa/repository_Python | /procedural_programming/ex065.py | 1,067 | 4.3125 | 4 | """
Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre todos os
valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário se ele quer ou não continuar a
digitar valores.
SAÍDA:
Digite um número:
Quer continuar [S/N] ?
Você digitou X números e a média foi Y.YY
O maior valor foi M e o menor foi N
"""
numeros = []
total = 0
elementos = 0
while True:
try:
numero = int(input('Digite um número: '))
total += numero
elementos += 1
numeros.append(numero)
continua = input('Quer continuar [S/N]? ').lower()
if continua == 's':
continue
elif continua == 'n':
break
else:
print('Digite opções válidas')
except ValueError:
print('Valor inválido')
media = total / elementos
print(f'Você digitou {elementos} números e a média foi {media}')
print(f'O maior valor foi {max(numeros)} e o menor foi {min(numeros)}')
| false |
acaeae77881f2116c58ddcae824b046ea0ab7d46 | calebe-takehisa/repository_Python | /procedural_programming/ex066.py | 742 | 4.15625 | 4 | """
Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar 999,
que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles
(desconsiderando o flag).
SAÍDA:
Digite um valor (999 para parar): 3
Digite um valor (999 para parar): 8
Digite um valor (999 para parar): 1
Digite um valor (999 para parar): 7
Digite um valor (999 para parar): 999
A soma dos 4 valores foi 19!
"""
number = total = elements = 0
while number != 999:
number = int(input('Digite um valor (999 para parar): '))
if number != 999:
total += number
elements += 1
print(f'A soma dos {elements} valores foi {total}!') | false |
eb3a77cdc28faf535f356b6b13d799120a56d047 | evamaina/Python_practice | /Udacity/is_odd.py | 281 | 4.1875 | 4 | def is_odd_number(num):
if num % 2 != 0:
return True
else: # unnecesary else
return False
print(is_odd_number(4))
print(is_odd_number(3))
def is_odd_number(num):
if num % 2 != 0:
return True
return False # without else
print(is_odd_number(4))
print(is_odd_number(3)) | false |
e8115ec9190bc8f36a743f35439377f03c70485b | skynette/code-challenge-day-9 | /darts.py | 623 | 4.15625 | 4 |
"""
concept:
r^2 = (x-h)^2 + (y-k)^2 where h and k are the coordinate for the center of the circle
radius r = sqrt(x^2 + y^2)
"""
from math import sqrt
def score(x, y):
x, y = abs(x), abs(y)
outer_circle = 10
middle_circle = 5
inner_circle = 1
points = 0
radius = sqrt((x**2)+(y**2))
if radius > inner_circle and radius<=middle_circle:
points+=5
return points
elif radius>middle_circle and radius<= outer_circle:
points+=1
return points
elif radius >= 0 and radius <= inner_circle:
points+=10
return points
else:
return points | true |
de14fe2707c48ade9fcffc3ac504f9494c0b3f5d | Clawhead/UWF_2014_spring_COP3990C-2507 | /notebooks/scripts/hw01-solutions/mean_variance.py | 981 | 4.25 | 4 | '''
Course: COP3990C
Name: JET
Date: 1/12/14
Assignment: Homework 1
This program computes the mean and variance of a list of randomly generated integers
'''
# import the random package
import random
# initialize some variables
mean = 0.0
num_of_ints = 100
lower_number = 0
upper_number = 1001
variance = 0.0
# generate a list of random numbers
random_list = random.sample(xrange(lower_number, upper_number), num_of_ints)
# loop though the list and compute the mean
for random_int in random_list:
mean = mean + random_int
mean = mean / num_of_ints
# loop through the list and compute the variance
for random_int in random_list:
variance = variance + random_int * random_int
variance = variance / num_of_ints - mean * mean
# print the results
print 'The mean for the list of ', num_of_ints, ' randomly generated integers is: ', mean
print 'The variance for the list of ', num_of_ints, ' randomly generated integers is: ', variance
| true |
6966a0ddc40365a93527989e158d405da04ca466 | jhesed/learning | /udemy/The Python Mega Course/Section 7 - More Functionalities/coding_exercise_6_merging_text_files.py | 2,170 | 4.15625 | 4 | """
Udemy: The Python Mega Course: Building 10 Real World Applications
Coding Exercise 6: Merge multiple text files to one.
This code contains my own solution for the exercise indicated above,
without refering to Udemy solution
Author: Jhesed Tacadena
Date: 2017-01-24
Section 7 contents:
41. Introduction
42. Modules, Libraries and Packages
43. Commenting and Documenting your Code
44. Working with Dates and Times
45. Coding Exercise 6: Merging Text Files
46. Tips for Exercise 6
47. Solution 6
"""
# -----------------------------------------------------------------------------
# Imports
import os
import datetime
# -----------------------------------------------------------------------------
# Main program
def merge_files(directory="."):
"""
Merge files inside `directory`
Argument:
directory (str): The directory that contains the files to be merged.
Note:
Output file will also be written in `directory`
"""
file_names = os.listdir(directory)
if directory[-1] == '/':
# remove trailing slash, as this will be dynamically appended later on
directory = directory[:-1]
if file_names:
print("(INFO) Files in directory: `{}`".format(file_names))
# Name of the output file
output_file_name = "{}/{}.txt".format(
directory,
datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S-%f"))
with open(output_file_name, 'w') as output_file:
# loop thru all input files in directory
for fname in file_names:
with open("{}/{}".format(directory, fname)) as input_file:
print("(INFO) Opening file: `{}`".format(fname))
for line in input_file:
# Write to output file
output_file.write("{}\n".format(line))
print("(INFO) Done merging files.")
else:
# No files exist, don't do anything
print("(WARNING) No files in directory.")
# Stand alone test
if __name__ == '__main__':
merge_files('res') | true |
5ed7e9351f2aa929543dc89e0d1c41d1c7ecfe0f | ShubhangiKukreti/Data-Structures-Algorithms | /Arrays/Reverse_String.py | 579 | 4.25 | 4 | def reverse(input_string):
if not input_string or len(input_string) < 2 or type(input_string) != "str":
return "Invalid input"
else:
return input_string[::-1]
def reverse_two(input_string):
if not input_string or len(input_string) < 2 or type(input_string) != "str":
return "Invalid input"
else:
i = len(input_string) - 1
new_string = ""
while i >= 0:
new_string += input_string[i]
i -= 1
return new_string
user_input = input(print("Enter a string"))
print(reverse(user_input))
| false |
b5d08656d6a8c24fd0420c460a5ad059eae67301 | ParulProgrammingHub/assignment-1-riyashekann | /prog7.py | 205 | 4.1875 | 4 | def thirdangle(angle1,angle2):
angle3=180-(angle1+angle2)
print "The third angle is",angle3
angle1=input("enter the first angle")
angle2=input("enter the second angle")
thirdangle(angle1,angle2)
| true |
592842b285a6dec6e77e358ce6c7eea165bfb38d | liama482/Hello | /Conditional_State.py | 667 | 4.15625 | 4 | """
temperature = float(input("What is the temperature outside? "))
weather = input("Is it raining or sunny outside? ")
weather = weather.lower() # change to lower case
if temperature < 55:
clothes = "a warm raincoat" if weather == "raining" else "a fleece"
else: # 55 or warmer..
clothes = "an umbrella" if weather == "raining" else "sunglasses"
print("You should bring {0}.".format(clothes))
"""
temperatures = [12, 46, 24, 67, 80, 26, 64, 24, 45, 40]
howitfeels = ["{0} is Brr!".format(temp) if temp < 50 else temp for temp in temperatures]
print(howitfeels)
# ['12 is Brr!', 46, '24 is Brr!', 67, 80, '26 is Brr!', 64, '24 is Brr!', 45, 40]
print(temp)
| true |
abe58c0d67476816c3a38aca8ed6a3f4a0ebae8a | shilpajpatil/MYPYTHON | /arrayoperations.py | 1,362 | 4.59375 | 5 |
import array
def main():
arr=array.array('i',[1,2,3])
#----------------print array element------------------
for i in range(0,3):
print("array can be:",arr[i])
#---------------adding element inside array---------------
arr.append(4);
arr.append(5);
arr.append(6);
arr.append(6)
arr.append(4);
print("after adding element inside array:",arr)
#---------inserting element inside specific position insert(value,position)-----------------
arr.insert(5,15)
arr.insert(3,12)
print("array after adding element at position:",arr)
#-------to pop element from the array -----------------------------
poped=arr.pop(6) #poping element at given position 5
print("poped element from array",poped)
print("array after poping element",arr)
# -----remove function used to remove first occurance of the value---------
arr.remove(4)
print("after removing a element given array:",arr)
#----index function returns index of first occurance of the element---------
index_return=arr.index(6)
print("it returns index of first occrance of that argument",index_return)
print("array after returning the index",arr)
#----reversing an array use reverse function --------------
arr.reverse()
print("reversed array:",arr)
if __name__ == "__main__":
main() | true |
e04184ad51a59e650008d975251dea7cbadd5eba | tsnsoft/TSN_PYTHON3_CONSOLE_EXAMPLES | /Console/lab1-0.py | 1,025 | 4.21875 | 4 | #!/usr/bin/env python3
# coding=utf-8
# Пример решения квадратного уравнения
import math # Подключение математического модуля
try: # Защищенный блок 1
a = float(input("Введите A="))
b = float(input("Введите B="))
c = float(input("Введите C="))
try: # Защищенный блок 2
d = b * b - 4 * a * c
x1 = (-b + math.sqrt(d)) / (2 * a)
x2 = (-b - math.sqrt(d)) / (2 * a)
print('d = ', d)
print('x1 = ', round(x1, 2))
print("x2 = " + format(x2, "#.2f"))
except: # Обработчик ошибок для защищенного блока 1
print("Нет решения!")
except: # Обработчик ошибок для защищенного блока 2
print("Неверные входные данные!")
input("Нажмите Enter для выхода") # Задержка перед выходом из программы
| false |
c890f0bac9dd04c4ec693f64ec9e01ab735596c4 | rachelchalmersCDDO/hello-git | /python-practice/name picker.py | 720 | 4.21875 | 4 | #!/usr/bin/env python
# This programme picks a name at random
import random
insert = True
people = []
print("\n")
print("Welcome to Rachel's name picker ")
print("\n")
print("Please insert all names, then type done")
print("\n")
while insert is True:
name = input()
if name.upper() == "DONE":
insert = False
else:
people.append(name)
print("\n")
print("There are " + str(len(people)) + " people in the office today.")
print("\n")
index = 1
while len(people) > 0:
number = random.randint(0,len(people)-1)
numberwang = random.randint(0,800)
if number == numberwang:
print("That's Numberwang")
print(str(index) + ". " + (people[number].capitalize()))
people.pop(number)
index += 1
else:
exit()
| false |
b17ec364c49c3c2f5e0bec47c71a468dcb4cfb0e | rachelchalmersCDDO/hello-git | /python-practice/arethmetic operations.py | 819 | 4.21875 | 4 | import math
# ARETHMETIC OPERATIONS
print(10 + 3)
print(10 - 3)
print(10 * 3)
# two types of division
# one gives a floating point number
print(10 / 3)
# one gives an integer
print(10 // 3)
# this gives the remainder
print(10 % 3)
# for an exponent/ power
print(10 ** 3)
# augmented/ enhanced assignment operator
# here we are incrementing a number
x = 10
x = x + 3
print(x)
x += 3
print(x)
# OPERATOR PRECEDENCE (bodmas)
x = 10 + 3 * 2 ** 22
print(x)
# MATHS FUNCTIONS
x = 2.9
print(round(x))
print(abs(-2.9))
# for complex maths, import the maths module
# modules in python are separate files with reusable functions (think of a supermarkets section)
# to get ceiling:
print(math.ceil(x))
# to get floor
print(math.floor(x))
# https://docs.python.org/3/library/math.html - look here
| true |
ccb99d6bcd9d8a5c373132960fa9223a5e1b0de5 | palanuj402/Py_lab | /File/q8.py | 400 | 4.3125 | 4 | #Write a python program to find sum and average of elements in list
size=int(input("Enter size of list: "))
l1=[]
print("Enter elements: ")
for i in range(size):
item=int(input())
l1.append(item)
print("List is: ",l1)
#to find sum
sum=0
for i in range(size):
sum=sum+l1[i]
# size=size-1
print("Sum is: ",sum)
avg=float(sum/(size))
print("Average is: ",avg) | true |
0c88217fca808a7d5b772e6b9544cc1ff75ad988 | palanuj402/Py_lab | /File/q10.py | 347 | 4.21875 | 4 | #Write a python program to count occurrences of an element in a list.
size=int(input("Enter size of list: "))
l1=[]
for i in range(size):
item=int(input())
l1.append(item)
x=int(input("Enter element to find occurences: "))
count=0
for j in l1:
if(j==x):
count=count+1
print(x," has ",count," occurences")
| true |
1fa77913a2b729990787171f3603bc9131d6ebc4 | pouxol/NATO-alphabet | /main.py | 492 | 4.28125 | 4 | import pandas
# Create a dictionary in this format:
alphabet = pandas.read_csv("nato_phonetic_alphabet.csv")
alphabet_dict = {row.letter: row.code for (index, row) in alphabet.iterrows()}
# Create a list of the phonetic code words from a word that the user inputs.
input_word = input("Input word: ").upper()
words = []
for letter in input_word:
try:
words.append(alphabet_dict[letter])
except KeyError:
print("You are only allowed to input letters.")
print(words) | true |
7c1d628aa64349a5bd78ba7f0cdc06746290d3db | OmegaWulf/Algorithms | /recipe_batches/recipe_batches.py | 645 | 4.125 | 4 | #!/usr/bin/python
import math
def recipe_batches(recipe, ingredients):
count = 0
for name in recipe.keys():
if name not in ingredients:
return 0
tempCount = int(ingredients[name] / recipe[name])
if count == 0 or tempCount < count:
count = tempCount
return count
if __name__ == '__main__':
# Change the entries of these dictionaries to test
# your implementation with different inputs
recipe = { 'milk': 2}
ingredients = { 'milk': 200 }
print("{batches} batches can be made from the available ingredients: {ingredients}.".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients)) | true |
55028b26121b70c5feee4429cc8d6cc43cb81547 | allusai/IdealSort | /src/features.py | 1,294 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 19 16:13:31 2017
@author: saikalyan
"""
import numpy as np
#Features module: contains useful methods to find features of an array
# Returns the number of elements in the given array
def numElements(array):
# Just returns the length of the array
return len(array)
# Returns a number from -1.0 (completely descending)
# to 1.0 (completely ascending)
def sortScore(array):
score = 0.0
for i in range(0,len(array)-1):
if array[i] < array[i+1]:
score += 1.0
elif array[i] > array[i+1]:
score -= 1.0
#Now normalize the sum
score = score / (len(array)-1)
# print(score)
return score
# Returns the percentage of numbers that are unique
# If n = 10, 0.1 means 1 unique val, 1.0 means all unique vals
def uniqueVals(array):
# Returns an array of the unique numbers, length of
# this new array is how many unique elements there are
u = np.unique(array)
# print(len(u) / len(array))
return len(u) / len(array)
#Tests
sortScore([5,1,7,3,5,3,8,2])
uniqueVals([3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,1,1,1,1])
a = [1,2,3,4,5]
print("Sort Score: ",sortScore(a))
print("Unique Vals: ",uniqueVals(a))
print("Number of Elements: ",numElements(a))
| true |
5cda89378bbc89f4a51615e6ee33c94bec9a03e3 | nem080/Python | /Lista_3/Aula_5_Exercicio_02.py | 592 | 4.1875 | 4 | # Analise o programa abaixo e detalhe passo a passo como o Python (segundo suas prioridades) resolveria a equação.
# x=2
# y=3
# z = 0.5
# print(x + x * x ** (y * x) / z)
print('\nPrioridade de Equação\n')
print('x=2, y=3, z = 0.5')
print('\n(x + x * x ** (y * x) / z)\n')
print('1º Passo: (y * x) -> (2 * 3) = 6\n')
print('2º Passo: (x * (1º Passo)) --> x * 6 --> 2 ** 6 = 64\n')
print('3º Passo: (x * (2º Passo)) --> x * 64 --> 2 * 64 = 128\n')
print('4º PAsso: ((3º Passo) / z) --> 128/z --> 128/0.5 = 256\n')
print('5º PAsso: (x + 4º Passo) --> x + 256 --> 2 + 256 = 258\n') | false |
90a404418f04d2efc28585202c8aec6c02d351ac | nem080/Python | /Lista_4/3ex.py | 709 | 4.3125 | 4 | # Faça uma função que retorne o reverso de um número inteiro informado. Obs: utilizar uma função recursiva
def input_valores():
print("\n")
numero = str(input("Informe o número que deseja inverter:\n"))
while (numero.isnumeric() == False):
numero = str(input("Informe um número inteiro:\n"))
if(numero=="0"):
print("\n")
print("Obrigado.")
else:
print(inverte_valor(numero))
input_valores()
def inverte_valor(numero):
if len(numero)==0:
return numero
else:
return inverte_valor(numero[1:])+numero[0]
if __name__ == '__main__':
print("Olá, bem vindo ao módulo de inversão de inteiros.")
print("Para encerrar o inversor digite 0.\n")
input_valores() | false |
d0ea73dd60bd83bf6044f1a3422f23a1c68ae2d4 | miltonArango/python-challenges | /challenge1.py | 1,245 | 4.21875 | 4 | """
Challenge 1:
Read an integer N
Without using any string methods, try to print the following:
123...N
Test Case:
>>> print_array(5)
'12345'
"""
def print_array(n):
"""Print the value concatenation of an integer array of N elements
given n >= 0.
>>> [print_array(n) for n in range(1, 7)]
['1', '12', '123', '1234', '12345', '123456']
>>> print_array(10)
'12345678910'
>>> print_array(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
>>> print_array(10.1)
Traceback (most recent call last):
...
ValueError: n must be exact integer
It must also not be ridiculously large:
>>> print_array(1e100)
Traceback (most recent call last):
...
OverflowError: n too large
"""
from functools import reduce
import math
if not n >= 0:
raise ValueError("n must be >= 0")
if n < 2:
return str(n)
if math.floor(n) != n:
raise ValueError("n must be exact integer")
if n + 1 == n: # Catch a value like 1e300
raise OverflowError("n too large")
return reduce(lambda x, y: str(x) + str(y), range(1, n + 1))
if __name__ == "__main__":
import doctest
doctest.testmod()
| true |
26b6c34fd69aceded3135a1839fc95dfe2785db8 | TheArtOfPour/IT121 | /2-calculations.py | 676 | 4.5 | 4 | #-------Variables and Calculations-----------------
#Assigning variables
scoobySnackServing=5
chaseScenes=2
mysteries=1
#Calculations using variables
totalSnacks=scoobySnackServing*chaseScenes*mysteries
#Printing string variables
print("total Scooby snacks needed is %s" % totalSnacks)
#-------Input----------------------------------------
#Use the input function to prompt the user and assign the typed response
# to a variable.
food=input("Enter a food: ")
print ("You entered %s." % food)
#Prompt the user for a number
# then use int()to convert the string to an integer.
num1=input("Enter a number: ")
num1=int(num1)
print (num1, " times ", num1, " is ", num1*num1) | true |
1afdbf35d68b44a03e678ae5ebe6ea1ecec5d767 | Apoorvag2597/Python-programming | /ICP1/operations.py | 349 | 4.125 | 4 | num1String = input('Please enter an integer: ')
num2String = input('Please enter a second integer: ')
num1 = int(num1String)
num2 = int(num2String)
print (num1,' plus ',num2,' equals ',num1+num2)
print (num1, ' subtract',num2, ' equals',num1-num2)
print (num1,' multiply ',num2,' equals ',num1*num2)
print (num1,' divide ',num2,' equals ',num1/num2) | false |
650833a0d561a97b0a1fff67dd934d0767d1bd62 | surya-232/assignment | /assignment17.py | 2,127 | 4.375 | 4 | #question1
#Write a python program using tkinter interface to write Hello World and a exit button that closes the interface.
import tkinter
from tkinter import *
import sys
root = Tk()
root.title("first_question")
root.geometry("300x100")
root.resizable(False,False)
l1=Label(root,text="hello world",width=20,bg='black',fg='white')
l1.pack()
b=Button(root, text="Exit", command=quit)
b.pack()
root.mainloop()
#question2
# Write a python program to in the same interface as above and create a action when the button is click it will display some text.
import tkinter
from tkinter import *
import sys
def show():
l1 = Label(root, text="hello world", width=20, bg='black', fg='white')
l1.pack()
root = Tk()
root.title("second_question")
root.geometry("300x100")
root.resizable(False,False)
b=Button(root, text="press", command=show, bg="blue")
b.pack()
b1=Button(root, text="Exit", command=quit, bg="red")
b1.pack()
root.mainloop()
#question3
#Create a frame using tkinter with any label text and two buttons.One to exit and other to change the label to some other text.
import tkinter
from tkinter import *
import sys
root = Tk()
root.title("first_question")
root.geometry("500x400+5+5")
root.resizable(False,False)
l1=Label(root,text="and the text",width=20,bg='black',fg='white')
def press():
l1.config(text="changed")
l1.pack()
b=Button(root, text="change text", command=press)
b.pack()
b1=Button(root, text="Exit", command=quit)
b1.pack()
root.mainloop()
#question4
#Write a python program using tkinter interface to take an input in the GUI program and print it.
from tkinter import *
def show():
l3.configure(text=e1.get())
l4.configure(text=e2.get())
root = Tk()
l1=Label(root, text="First Name").grid(row=0)
l2=Label(root, text="Last Name").grid(row=1)
e1 = Entry(root)
e2 = Entry(root)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
Button(root, text='Show', command=show).grid(row=3, )
l3=Label(root, text="", bg="black", fg='white')
l4=Label(root, text="", bg="white", fg="black")
l3.grid()
l4.grid()
root.title("fourth_question")
root.geometry("500x500")
root.mainloop()
| true |
a61c6a15b1b020eded697a5318deed6c7455a28b | sackh/python-examples | /data_structures/binary_tree_traversal.py | 1,809 | 4.15625 | 4 |
class TreeNode:
"""
Node of Binary Tree
"""
def __init__(self, data, left=None, right=None):
self.left = left
self.right = right
self.data = data
def inorder_iterative(root):
"""
Inorder trversal iterative function
:param root:
:return:
"""
temp = root
stack = []
while True:
while temp:
stack.append(temp)
temp = temp.left
if not stack:
break
temp = stack.pop()
print(temp.data, end=' ')
temp = temp.right
def inorder_recursive(root):
"""
Recursive method for inorder traversal
:param root:
:return:
"""
if root:
inorder_recursive(root.left)
print(root.data, end=' ')
inorder_recursive(root.right)
def preorder_iterative(root):
"""
Pre order traversal iterative method
:param root:
:return:
"""
temp = root
stack = []
while True:
while temp:
stack.append(temp)
print(temp.data, end=' ')
temp = temp.left
if not stack:
break
temp = stack.pop()
temp = temp.right
def preorder_recursive(root):
if root:
print(root.data, end=' ')
preorder_recursive(root.left)
preorder_recursive(root.right)
if __name__ == "__main__":
root = TreeNode('a')
root.left = TreeNode('b')
root.right = TreeNode('c')
root.left.left = TreeNode('d')
root.left.right = TreeNode('e')
root.right.left = TreeNode('f')
root.right.right = TreeNode('g')
print('inorder traversal')
inorder_iterative(root)
print()
inorder_recursive(root)
print()
print('preorder traversal')
preorder_iterative(root)
print()
preorder_recursive(root)
| true |
1e2201f9d5a2567d771efd7b922ac07bc00ae1db | Ranjit-97/GitDemo | /Python/datatype_Dictionary.py | 541 | 4.21875 | 4 |
a = {1:"first name",2:"last name", "age":33, "a":"Hello world"} #key:value
print(a[1])#print value having key=1
print(a[2])#print value having key=2
print(a["age"])#print value having key="age"
print(a["a"])#we print the value here
print("\n")
#create a dynamic dictionay at run time
#steps- first create an empty dictionay then gives constraint or values
dict = {} #create an empty dictionay
print(dict)#print empty dictionary
dict["firstname"] = "Ranjit"
dict["lastname"] = "Bhintade"
dict["age"] = 24
print(dict)
print(dict["lastname"]) | true |
5b166c877224e2c7fbdfcba8f39dd55ddcea0f40 | joneyyx/LeetCodes | /elementaryAlgorithms/Tree/107BinaryTreeLevelOrderII.py | 2,238 | 4.15625 | 4 | # Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
#
# For example:
# Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
# return its bottom-up level order traversal as:
# [
# [15,7],
# [9,20],
# [3]
# ]
# Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
"""
这里用到了BFS,这里用的是while循环的方式来处理队列
还可以用Queue
:param root:
:return:
"""
if not root:
# 看清题意返回的是List,不要想当然的None
return []
nodeList , res = [root], []
while nodeList:
# create a temp list for the nodes in each layer
# create a temp list to store the node values in each layer
layer, layerVal = [], []
for node in nodeList:
layerVal.append(node.val)
if node.left: layer.append(node.left)
if node.right: layer.append(node.right)
nodeList = layer
res.append(layerVal)
return res[::-1]
from queue import Queue
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
"""
这里用到了BFS,也用到了Queue。
每一次可以记录一层有几个,循环跑抽取queue中的数
:param root:
:return:
"""
if not root:
# 看清题意返回的是List,不要想当然的None
return []
queue = Queue()
queue.put(root)
res = []
while not queue.empty():
size = queue.qsize()
nodeValue = []
for _ in range(size):
node = queue.get()
nodeValue.append(node.val)
if node.left: queue.put(node.left)
if node.right: queue.put(node.right)
res.append(nodeValue)
return res[::-1] | true |
fc44e38b69717e6c13623868c81a777a75da8066 | rtomyj/500-Algos-Python | /one.py | 595 | 4.15625 | 4 | '''
Uses the fact that dicts are hashed in python to store values of items as keys and their index as a value.
Traverses the array and subtracts sum - current value. If that result is in the dict then it means we iterated over
it already and we can print out the sum.
'''
def hash_and_find(items, sum):
hash = dict()
for index, item in enumerate(items):
hash[item] = index
operand = sum - item
if operand in hash:
print('{0} (index = {3})+ {1} (index = {4}) = {2}'.format(item, operand, sum, index, hash[operand]))
items = [8, 7, 2, 5, 3, 1]
sum = 10
hash_and_find(items, sum) | true |
6896901bca0fdf84caea528b1432c7be29392603 | mijikai/euler-python | /P035.py | 1,686 | 4.125 | 4 | #!/usr/bin/env python3
"""A circular prime is a number such that all rotations of its digits is a
prime. For example, 197 is a circular prime because 719 and 917 are also
primes.
Find the number of cicular primes below one million."""
from utils import power_comb_with_repetition, is_prime, towhole
def no_of_circular_primes(digits):
"""Determine the number of unique primes that are circular out of
``digits``.
For example:
>>> no_of_circular_primes([1,7,9]) # 197, 719, 917 are circular primes
3
>>> no_of_circular_primes([1]) # 1 is not a prime
0
>>> no_of_circular_primes([1, 1]) # 11 is a circular prime equal to its rotation
1
"""
primes = set()
for i in unique_rotate(digits):
seq = list(i)
rotations = set()
for j in range(len(seq)):
num = towhole(seq)
if is_prime(num):
rotations.add(num)
item = seq.pop()
seq.insert(0, item)
else:
rotations.clear()
break
primes.update(rotations)
return len(primes)
def main():
# ignore even numbers and 5 because after some rotation,
# a composite will be generated
digits = [1, 3, 7, 9]
limit = 6 # generate up to six digit number
number_circ = sum(map(no_of_circular_primes,
power_comb_with_repetition(digits, limit)))
number_circ += 2 # 2 and 3 is a circular prime not caught by previous
print(number_circ)
if __name__ == '__main__':
print(__doc__)
from timeit import Timer
stmt = 'from __main__ import {0}; {0}()'.format('main')
print('time =', Timer(stmt=stmt).timeit(1))
| true |
9410922eaa33abe1a0b8f45d96dcfd2df4ff5b85 | Nagajothikp/Nagajothi | /s45.py | 244 | 4.21875 | 4 |
length = float(input('Please Enter the Length of a Triangle: '))
width = float(input('Please Enter the Width of a Triangle: '))
perimeter = 2 * (length + width)
print("Perimeter of a Rectangle using", length, "and", width, " = ", perimeter) | true |
763f31617e884bfbf2129d726ca27aad1fe5316f | Nagajothikp/Nagajothi | /amstrong.py | 219 | 4.15625 | 4 | num=int(input("Enter a number:"))
sum=0
temp=num
while temp>0:
digit=temp % 10
sum +=digit ** 3
temp//=10
if num==sum:
print(num,"is an amstrong number")
else:
print(num,"is not an amstrong number")
| true |
e4b19089fc723ba37ce20219620b0e6ae2787780 | jpolitron/kattis-problems | /stack/main.py | 1,020 | 4.15625 | 4 | class Stack:
def __init__(self):
self.items = []
#2. Check if stack is empty
def isEmpty(self):
return self.items == []
#3. Push new items to the top of stack
def push(self, data):
self.items.append(data)
#4. Popping data off of the stack
def pop(self):
return self.items.pop()
#5. Returning size of the stack
def size(self):
return len(self.items)
#1. Instantiate an object from class Stack
pancakes = Stack()
#2. push to top of stack
pancakes.push(1)
#3. returning the size of stack
print(pancakes.size()) # return 1
#4. check if its empty if there's no stuff inside it
print(pancakes.isEmpty()) # False
#5. check if its empty if there's stuff inside it
pancakes.push("CSin3") #pushing CSin3 to the top
pancakes.push(100.2) #pushing 100.2 to the top
print(pancakes.isEmpty()) #False
#6. check the top of stack
print(pancakes.size()) # return back a 3
print(pancakes.pop()) # 100.2
print(pancakes.size()) # return back a 2
| true |
5fbbaeba1d89a1819668932e95e8c497ab0d5bce | subhamcareers/Python_programming | /DBtest.py | 2,105 | 4.59375 | 5 | import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()
mysid= int(input("Enter ID: "))
myname=input("Enter name: ")
myhouse=int(input("Enter house: "))
mymarks=float(input("Enter marks: "))
curschool.execute("INSERT INTO student (StudentID, name, house, marks) VALUES (?,?,?,?);", (mysid,myname,myhouse,mymarks))
MySchool.commit()
'''Example 2: To accept user input for the values in the table:
Instead of adding known values, you can also accept user input for these values. Assuming that the database MySchool is created and contains the table student, we start by creating a connection:
import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()
To accept user input, we use variables to store each of the values.
import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()
mysid= int(input("Enter ID: "))
myname=input("Enter name: ")
myhouse=int(input("Enter house: "))
mymarks=float(input("Enter marks: "))
We now replaces the fixed VALUES in the INSERT query with the variables, mysid, myname, myhouse and mymarks. To do this, we use the DB-API’s parameter substitution. We put a ? as a placeholder wherever we want to use a value and then give a tuple of values as the second argument to the cursor’s execute() method.
import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()
mysid= int(input("Enter ID: "))
myname=input("Enter name: ")
myhouse=int(input("Enter house: "))
mymarks=float(input("Enter marks: "))
curschool.execute("INSERT INTO student (StudentID, name, house, marks) VALUES (?,?,?,?);", (mysid,myname,myhouse,mymarks))
We now commit the changes.
import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()
mysid= int(input("Enter ID: "))
myname=input("Enter name: ")
myhouse=int(input("Enter house: "))
mymarks=float(input("Enter marks: "))
curschool.execute("INSERT INTO student (StudentID, name, house, marks) VALUES (?,?,?,?);", (mysid,myname,myhouse,mymarks))
MySchool.commit()'''# Comments source
| true |
9077b89775590303d65c101cf082bd7887d9005e | IMDCGP105-1819/portfolio-S197615 | /ex8.py | 920 | 4.1875 | 4 | total_cost = input("Enter the cost of your dream home: ")
portion_deposit = float(total_cost) * 0.2
current_savings = 0
r = 1.04
annual_salary = input("Enter your annual salary: ")
portion_saved = input("Enter the percent of your salary to save, as a decimal: ")
months = 0
semi_annual_raise = input("Enter a semi annual raise as a decimal: ")
semi_annual_raise = float(semi_annual_raise) + 1
counter = 0
while current_savings < portion_deposit:
pay_rise = float(annual_salary) * float(semi_annual_raise)
monthly_salary = int(annual_salary) / 12
monthly_input = float(monthly_salary) * float(portion_saved)
current_savings = current_savings * r
current_savings = current_savings + monthly_input
months = months + 1
counter = counter + 1
if counter / 6 == 1:
annual_salary = pay_rise
counter = 0
else:
print("Number of months: " + str(months)) | true |
1486186e11e16ea0265f73363be340cf745f016f | ayushi19031/My-First-sem-code-and-work | /lab6_2019031.py | 1,497 | 4.1875 | 4 | class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Line:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
class Circle:
def __init__(self, centre_x, centre_y, radius):
self.centre_x = centre_x
self.centre_y = centre_y
self.radius = radius
def findMirrorPoint(p, l):
p.x = (-2*l.a*(l.a*(p.x) + l.b*(p.y) + l.c)//((l.a**2) + (l.b**2))) + p.x
p.y = (-2*l.b*(l.a*(p.x) + l.b*(p.y) + l.c)//((l.a**2) + (l.b**2))) + p.y
return (p.x, p.y)
def Checksides(p1, p2, l1, l2):
findMirrorPoint(p1, l1)
t1 = (l2.a)*(p2.x) + (l2.b)*(p2.y) + (l2.c)
t2 = (l2.a)*(p1.x) + (l2.b)*(p1.y) + (l2.c)
if t1 > t2 or t2 > t1:
return "Both are on same side"
else:
return "Not on same side"
def checkIntersection(c1, c2):
distance_between_centres = (((c1.centre_y) - (c2.centre_y))**2 + ((c1.centre_x) - (c2.centre_x))**2 )**0.5
sum_of_radii = c1.radius + c2.radius
dif_of_radii = abs(c1.radius - c2.radius)
if sum_of_radii < distance_between_centres:
return "The circles do not intersect"
else:
return "The circles intersect"
p = Point(1, 0)
l = Line(-1, 1, 0)
p1= Point(-2, 0)
p2 = Point(-1, 1)
l1 = Line(-1, 1, 0)
l2 = Line(-2, 1, -1)
c1 = Circle(-2, 0, 3)
c2 = Circle(4, 0, 3)
print(checkIntersection(c1, c2))
| false |
9cd9c2eea8894564ec2c50514f5ec143bd8b993c | NickSeyler/MySortingAlgorithms | /Python/SortingAlgorithms.py | 585 | 4.40625 | 4 | # Author: Nick Seyler
# Date: 07/02/2020
# Description: Sort an array by iterating through it and finding the minimum value
from BubbleSort import bubble_sort
from InsertionSort import insertion_sort
from MergeSort import merge_sort
from QuickSort import quick_sort
from SelectionSort import selection_sort
def main():
arr = [9, 3, 4, 2, 6, 10, 1, 8, 7, 5]
print(arr) # before the array is sorted
quick_sort(arr) # replace this with any sorting method
print(arr) # after the array is sorted
if __name__ == "__main__":
main()
| true |
55376a2defc4815c447495e309b65b0e70fdc187 | talhaHavadar/daily-scripts-4-fat-lazy | /programming_questions/common_count_in_arr.py | 757 | 4.125 | 4 | """
Question: Given two sorted arrays, find the number of elements in common. The arrays are the same length
and each has all distinct elements.
A: 13 27 35 40 49 55 59
B: 17 35 39 40 55 58 60
"""
def get_common_count(arr1, arr2):
arr1_index = 0
arr2_index = 0
common_count = 0
while arr1_index < len(arr1) and arr2_index < len(arr2):
arr1_num = arr1[arr1_index]
arr2_num = arr2[arr2_index]
if arr1_num < arr2_num:
arr1_index += 1
elif arr2_num < arr1_num:
arr2_index += 1
else:
common_count += 1
arr1_index += 1
arr2_index += 1
return common_count
print(get_common_count([13, 27, 35, 40, 49, 55, 59], [17, 35, 39, 40, 55, 58, 60]))
| true |
1aad4ec19613c5d31407c9aed4c079131d0142aa | KopalGupta1998/Python-Programs- | /guess the number.py | 2,068 | 4.3125 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
# helper function to start and restart the game
number=100
number_of_guess=0
def new_game():
global secret_number
global number_of_guess
global number
secret_number=random.randrange(0,number)
if(number==100):
number_of_guess=7
elif(number==1000):
number_of_guess=10
# initialize global variables used in your code here
# remove this when you add your code
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
global number
number=100
# remove this when you add your code
new_game()
def range1000():
# button that changes the range to [0,1000) and starts a new game
global number
number=1000
new_game()
def input_guess(guess):
print ""
guess=int(guess)
global number_of_guess
number_of_guess=number_of_guess-1
if(number_of_guess==0):
print "You lost the game"
new_game()
else:
print "You have "+ str(number_of_guess)+" guesses left!"
print "Guess was "+str(guess)
global secret_number
if(secret_number>guess):
print "Higher"
elif(secret_number<guess):
print "Lower"
elif(secret_number==guess):
print "Correct"
else:
print "Something went wrong!"
# main game logic goes here
# remove this when you add your code
# create frame
frame=simplegui.create_frame("Guess_the_Number",200,200)
frame.add_input("Enter a Number:",input_guess,200)
frame.add_button("Range is [0,100)",range100,100)
frame.add_button("Range is [0,1000)",range1000,100)
# register event handlers for control elements and start frame
# always remember to check your completed program against the grading rubric
| true |
bc1dcb03fa6fcb2c95e270ebbb207362a8a3fff8 | fatjan/code-practices | /python/for-if.py | 382 | 4.28125 | 4 | # list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7]
# loop through the list of numbers
# if number is equal to 6, the for loop will terminate via a break statement
# the loop terminates naturally therefore the else clause is executed
for number in numbers:
if number == 6:
break
print(number, end=' ')
else:
print('Unbroken loop')
# 1 2 3 4 5 Unbroken loop | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.