blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
9b3aa94ef5818da1f76aacda0d12a2e83a31e8ec
|
zhouf1234/untitled3
|
/函数编程函数19内置高阶函数map.py
| 1,081
| 4.21875
| 4
|
#定义列表
numbers = [1,2,3,4,5,6,7]
#要求得到一个新列表,新列表是numbers这个列表中每个元素的3次方
#map一般用来处理列表:map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回
# new_number = []
# for i in numbers:
# new_number.append(i ** 3)
#
# print(new_number)
def map_fn(ite):
return ite **3
res=list(map(map_fn,numbers)) #把map的返回结果变为列表,不写list的话结果。。。。
print(res)
#res2=map(map_fn,numbers)
#print(list(res2)) #也可,同res结果一样的
#处理字符串,把字符串都变为大写
msg = 'Hello nihao'
def upper_str(item):
if item >= 'a' and item<= 'z':
return chr(ord(item)-32) #Unicode编码转换,
else: #ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符
return item
#return item.upper() #尝试一下直接返回值是大写
print(''.join(list(map(upper_str,msg))))
| false
|
96088e55587bcbf20b661824f0717a2e6ae9987e
|
zhouf1234/untitled3
|
/函数编程函数0自定义和返回值.py
| 2,024
| 4.21875
| 4
|
#自定义一个函数print_hello()
def print_hello(): #无参
pass
#Python函数先定义 再调用
#函数名(print_name)本质上就是变量名
#定义阶段
def print_name():
print('nihao')
print('222')
print('ddd')
print('....end....')
#调用阶段才会执行
print_name()
print_name()
print_name()
print()
def fn_02():
b = 1 + 1
#定义函数
def fn_01():
a = 10 * 10
return a #返回值会作为函数表达式的值
#调用 函数调用本身就是表达式,该表达式的值就是 函数的返回值
res = fn_01()
print(res)
print(res + 9)
print()
print(fn_01())
print(fn_01() + 20)
print()
print(fn_02()) #fn_02没有写返回值,所以显示空值
print()
#print不是return,函数中有print,函数调用了就会执行
def fn_03():
print('hello!nihao!')
print(fn_03()) #函数中已经输出一次,此次之后返回none空值
print()
#python函数可以return多个值,函数调用表达式的值是个元组
def fn_04():
return 20,30,'hello',['1','2','3'] #返回值是个元组
print(fn_04()) #输出返回值
print()
#return会终止函数的执行,retrurn后面的不会执行
def fn_05():
print('你好')
return 150
print('aaa')
fn_05() #只输出 你好,因为函数输出了(printt)
print()
#两个return:retrurn后面的不会执行,只执行第一个return
def fn_06():
return 4*4 #函数终止
return 3 #不会执行到了
fn_06() #此次不会输出任何值,因为没有输出fn_06()
print(fn_06()) #输出16
print()
print(10 + fn_06()) #输出26
print()
def fn_07(a):
return a #返回值是个元组
print(fn_07('111111111')) #输出返回值
print()
def fn_08(a,b,*args):
return a,b,args #所以返回值是个元组
print(fn_08(2,59,'nihao')) #调用值是个元组
#G=(2,4,'key') #简化写法有点问题暂时不用与return
#fn_08(G)
| false
|
64a4e611797c396cbc03829c781896eb330507a3
|
fpavanetti/python_lista_de_exercicios
|
/aula21_ex104.py
| 893
| 4.40625
| 4
|
'''
Desafio 104
Faça um programa que tenha uma função chamada ficha(), que receba dois parâmetros
opcionais: o nome de um jogador e quantos gols ele marcou.
O programa deverá ser capaz de mostrar a ficha do jogador, mesmo que algum
dado não tenha sido informado corretamente.
'''
def ficha(nome='', gols=''):
print('-' * 30)
if nome == '' and gols == '':
return print(f'O jogador <desconhecido> fez 0 gol(s) no campeonato.')
elif nome == '' and gols != '':
return print(f'O jogador <desconhecido> fez {gols} gol(s) no campeonato.')
elif nome != '' and gols == '':
return print(f'O jogador {nome} fez 0 gol(s) no campeonato.')
else:
return print(f'O jogador {nome} fez {gols} gol(s) no campeonato.')
n = str(input('Nome do jogador: ')).strip()
g = str(input('Número de Gols: ')).strip()
ficha(n, g)
| false
|
df3a255364d770172c8ab0b9c36a9004acd4f900
|
fpavanetti/python_lista_de_exercicios
|
/aula17_explicação.py
| 1,952
| 4.46875
| 4
|
'''
AULA 17 - VARIÁVEIS COMPOSTAS (LISTAS: PARTE 1)
Os índices em Python são chamados de KEY
Para casos em que precisamos de listas CONSTANTES = tuplas
Para casos em que precisamos manipular os dados dentro
da estrutura = LISTAS
lista = [1, 2, 3, 4]
lista[3] = 'outra coisa'
Para adicionar elementos na lista: lista.append('elemento novo')
Para adicionar elementos em outras posições: lista.insert(0, "outro novo elemento")
Para apagar elementos:
del lanche[3]
lanche.pop[3] > geralmente elimina o último elemento
lanche.remove("Elemento")
Para descobrir se um elemento estiver na lista:
if elemento in lista:
lista.remove('elemento')
criando listas com ranges:
valores = list(range(4,11))
cria uma lista chamada valores, com os valores de 4 a 10, índice 0 a 6
ordenar os valores > valores.sort()
valores.sort(reverse=True) > ordenar ao contrário
ler o número de valores > len(valores)
'''
num = [2, 5, 9, 1]
num[2] = 3
num.append(7)
num.sort(reverse=True)
num.insert(2, 0) # na posição 2, adiciona o 0
num.pop() # elimina o último elemento
num.pop(2) # elimina a key índice 2
# o remove remove o 1o valor encontrado
print(num)
print(f'Essa lista tem {len(num)} elementos.')
lista = []
lista.append(5)
lista.append(9)
lista.append(4)
for valores in lista:
print(f'{valores}...', end=' ')
print()
for chaves, valores in enumerate(lista):
print(f'Na posição {chaves} encontrei o valor {valores}!')
print('Cheguei ao final da lista.')
listinha = list()
for cont in range(0, 5):
listinha.append(int(input("Digite um valor: ")))
for c, v in enumerate(listinha):
print(f'Na posição {c} encontrei o valor {v}!')
listinha.sort(reverse=True)
print(listinha)
a = [2, 3, 4, 7]
b = a # o python não COPIA simplesmente; ele faz uma ligação
c = a[:]
b[2] = 8
print(f'Lista A: {a}')
print(f'Lista B: {b}')
print(f'Lista C: {c}')
| false
|
fad1250d600a8951bf1af8879cf5cf4043492b41
|
fpavanetti/python_lista_de_exercicios
|
/aula14_ex63.py
| 1,023
| 4.1875
| 4
|
'''
DESAFIO 63
Melhore o desafio 62, perguntando para o usuário
se ele quer mostrar mais alguns termos. O programa
encerra quando ele disser que quer mostrar 0 termos.
'''
p1 = int(input("Digite o primeiro termo da PA: "))
r = int(input("Digite a razão da PA: "))
resp = int
while resp != 0:
resp = int(input("Quantos termos deseja verificar? "))
for resp in range(1, resp + 1):
print(p1, end=' ')
p1 = p1 + r
print()
print("Leitor de PAs encerrado com sucesso.")
'''
Resolução Guanabara
primeiro = int(input("Primeiro termo: "))
razão = int(input("Razão da PA: "))
termo = primeiro
cont = 1
total = 0
mais = 10
while mais != 0:
total = total + mais
while cont <= total:
print("{} -> ".format(termo, end='')
termo = termo + razão
cont = cont + 1
print("PAUSA")
mais = int(input("Quantos termos você quer mostrar a mais? "))
print("Progressão finalizada com {} termos mostrados.".format(total))
'''
| false
|
40b0d55a22addb33668cad9ea65247cd54e20ec0
|
fpavanetti/python_lista_de_exercicios
|
/aula16_ex76.py
| 1,117
| 4.28125
| 4
|
'''
DESAFIO 76 - ANÁLISE DE DADOS EM UMA TUPLA
Desenvolva um programa que leia quatro valores pelo teclado e guarde-os
em uma tupla. No final, mostre:
A) Quantas vezes apareceu o valor 9
B) Em que posição foi digitado o primeiro valor 3
C) Quais foram os números pares
'''
pares = 0
n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite outro número: "))
n3 = int(input("Digite mais um número: "))
n4 = int(input("Digite o último número: "))
tupla = (n1, n2, n3, n4)
print(f"Você informou os valores {tupla}")
print(f"O valor nove apareceu {tupla.count(9)} vez(es)")
if 3 in tupla:
print(f"O número 3 apareceu na posição {tupla.index(3)+1}")
else:
print("O valor 3 não apareceu nenhuma vez.")
for c in tupla: # tupla é o range (4), a cada laço o "c" (variável genérica) pegara o valor contido em tupla no range determinado (tupla 1: valor x = c)
if c % 2 == 0:
pares = pares + 1
print(f"Foram digitados {pares} número(s) par(es)")
#eu poderia ter feito uma tupla automaticamente; é possível fazer uma tupla por meio
#de um input
| false
|
bb896caa016179a5444c7eaaa48fe355ec17fab5
|
fpavanetti/python_lista_de_exercicios
|
/aula15_ex67.py
| 893
| 4.125
| 4
|
'''
DESAFIO 67
Crie um programa que leia vários números inteiros pelo teclado. O programa só
vai parar quando o usuário digitar o valor 999, que é a condição de parada. No
final, mostre quantos números foram digitados e qual foi a soma entre eles (des-
considerando o flag).
O que deve aparecer:
"A soma dos x valores foi y!"
'''
# Primeiro: criar as variáveis de contador e soma
n_d = 0
s_n = 0
print("*-" * 20)
print(" Contador de números")
print("*-" * 20)
# Segundo: criar o leitor de números já com condição de parada
while True:
n = int(input("Digite um número inteiro (999 para parar): "))
if n == 999:
break
else:
# criar os contadores de números digitados e a soma entre eles
n_d = n_d + 1
s_n = s_n + n
print(f"Foram digitados {n_d} valores e a soma entre eles é {s_n}.")
| false
|
1c8fcbdbb630058b69cb6f37250f3d3aefc4ba5a
|
fpavanetti/python_lista_de_exercicios
|
/aula9_ex27.py
| 1,277
| 4.5
| 4
|
'''
Faça um programa que leia uma frase pelo teclado e mostre:
- Quantas vezes aparece a letra 'A'
- Em que posição ela aparece pela primeira vez
- Em que posição ela aparece pela última vez
'''
f = str(input("Digite uma frase qualquer: ")).upper().split()
print(f)
print("A frase possui {} espaços.".format(len(f)))
print("Número de vezes em que a letra A aparece:")
print(f.count('A')) # Quantas vezes a letra A aparece
# Em que posição A aparece pela primeira vez
print("Posição em que A aparece pela primeira vez:")
print(f.find('A'))
# Em que posição ele aparece pela última vez
print("Posição em que A aparece pela última vez, analisando do fim ao começo:")
print(f[::-1].find('A')) # string[inicio:fim:passo]
'''
Solução Guanabara
frase = str(input("Digite uma frase: ")).upper().strip()
print("A letra A aparece {} vezes na frase.".format(frase.count('A')))
print("A primeira letra A apareceu na posição {}".format(frase.find('A')+1))
print("A última letra A apareceu na posição {}".format(frase.rfind('A')+1))
A função rfind procura da direita para a esquerda.
O +1 foi adicionado para que o usuário veja na ordem em que estamos acostumados,
contando a partir do 1, e não do 0, como o Python.
'''
| false
|
c8e50e78c0d07129f2b0d4ebfc6da08776aaf4ca
|
fpavanetti/python_lista_de_exercicios
|
/aula14_ex59.py
| 1,536
| 4.25
| 4
|
'''
DESAFIO 59 - Jogo de Adivinhação 2.0
Melhore o jogo DESAFIO 028 onde o computador vai
"pensar" em um número entre 0 e 10. Só que agora
o jogador vai tentar adivinhar até acertar, mostrando
no final quantos palpites foram necessários para vencer.
'''
from random import randint
from time import sleep
print("=*=" * 20)
print("================ JOGO DA ADIVINHAÇÃO ===============")
print("Quantas tentativas você precisa para derrotar o computador?")
print("=*=" * 20)
cont_tentativas = int(1)
computador = randint(0, 10)
usuario = int(input("Digite um número entre 0 e 10: "))
while usuario != computador:
print("Você errou! Tente novamente.")
usuario = int(input("Digite um número entre 0 e 10: "))
cont_tentativas = cont_tentativas + 1
print("=*=" * 20)
print("Você venceu!!!")
print("Foram necessárias {} tentativa(s) para vencer.".format(cont_tentativas))
'''
Solução Guanabara
from random import randint
computador = randint(0, 10)
print("Sou o seu computador e acabei de pernsar num número entre 0 e 10.")
print("Será que você consegue adivinhar qual foi?")
acertou = False
palpites = 0
while not acertou:
jogador = int(input("Qual é seu palpite? "))
palpite = palpite + 1
if jogador == computador:
acertou = True
else:
if jogador < computador:
print("Mais...")
elif jogador > computador:
print("Menos...")
print("Acertou com {} tentativas!".format(palpites))
'''
| false
|
dc9bb9344cadecb222767f9bc2184d89597310d9
|
fpavanetti/python_lista_de_exercicios
|
/aula19_ex94.py
| 1,029
| 4.1875
| 4
|
'''
Desafio 94
Crie um programa que gerencie o aproveitamento de um JOGADOR DE FUTEBOL.
O programa vai ler o NOME DO JOGADOR e QUANTAS PARTIDAS ele jogou. Depois,
vai ler a QUANTIDADE DE GOLS feitos em CADA PARTIDA. No final, tudo isso
será guardado em um DICIONÁRIO, incluindo o TOTAL DE GOLS feitos durante
o campeonato.
'''
jogador = dict()
l = list()
jogador['Nome'] = str(input("Nome do jogador: "))
jogador['Partidas'] = int(input(f'Quantas partidas {jogador["Nome"]} jogou? '))
for c in range(0, jogador['Partidas']):
l.append(int(input(f'Quantos gols {jogador["Nome"]} fez na partida {c+1}? ')))
jogador['Gols'] = l
jogador['Total'] = sum(l)
print('=' * 50)
print(jogador)
print('=' * 50)
for k, v in jogador.items():
print(f'\tO campo {k} tem o valor {v}')
print('=' * 50)
print(f'O jogador {jogador["Nome"]} jogou {jogador["Partidas"]} partidas.')
for p, g in enumerate(l):
print(f'\t=> Na partida {p+1} ele fez {g} gols.')
print(f'Sendo um total de {jogador["Total"]} gols.')
| false
|
75de8adff9ee5574cdad8788c67c44deb46a5c5e
|
anarariand/cs102
|
/homework01/caesar.py
| 1,151
| 4.25
| 4
|
def encrypt_caesar(plaintext: str) -> str:
"""
>>> encrypt_caesar("PYTHON")
'SBWKRQ'
>>> encrypt_caesar("python")
'sbwkrq'
>>> encrypt_caesar("Python3.6")
'Sbwkrq3.6'
>>> encrypt_caesar("")
''
"""
ciphertext = ""
for char in plaintext:
if not char.isalpha():
ciphertext = ciphertext + char
else:
d = 'A' if char.isupper() else 'a'
cipher = (((ord(char) + 3) - ord(d)) % 26) + ord(d)
ciphertext = ciphertext + chr(cipher)
return ciphertext
def decrypt_caesar(ciphertext: str) -> str:
"""
>>> decrypt_caesar("SBWKRQ")
'PYTHON'
>>> decrypt_caesar("sbwkrq")
'python'
>>> decrypt_caesar("Sbwkrq3.6")
'Python3.6'
>>> decrypt_caesar("")
''
"""
plaintext = ""
for char in ciphertext:
if not char.isalpha():
plaintext = plaintext + char
else:
d = 'A' if char.isupper() else 'a'
cipher = (((ord(char) + 23) - ord(d)) % 26) + ord(d)
plaintext = plaintext + chr(cipher)
return plaintext
| false
|
17b641ee02371d924e4dc0020f65d9ba3ce5a23c
|
boswellgathu/py_learn
|
/12_strings/count_triplets.py
| 338
| 4.1875
| 4
|
# Write a Python method countTriplets that accepts a string as an input
# The method must return the number of triplets in the given string
# We'll say that a "triplet" in a string is a char appearing three times in a row
# The triplets may overlap
# for more info on this quiz, go to this url: http://www.programmr.com/count-triplets
| true
|
5eab2196af7a27cfffeadcdacbc4e5f94c3d70c6
|
boswellgathu/py_learn
|
/8_flow_control/grade.py
| 497
| 4.125
| 4
|
# Write a function grader that when given a dict marks scored by a student in different subjects
# prepares a report for each grade as A,B,C and FAIL and the average grade
# example: given
# marks = {'kisw': 34, 'eng': 50}
# return
# {'kisw': 'FAIL', 'eng': 'C', 'average': 'D'}
# A = 100 - 70, B = 60 - 70, C = 50 - 60, D = 40 - 50, FAIL = 0 - 39
# average is calculated from the number of subjects in the marks dict
# for more info on this quiz, go to this url: http://www.programmr.com/grade
| true
|
b86e8fdcecfd16b387546feee6fd171942b16033
|
ICLau/randomStuff
|
/test-asterisk.py
| 1,200
| 4.625
| 5
|
#
# https://treyhunner.com/2018/10/asterisks-in-python-what-they-are-and-how-to-use-them/
#
"""
what = [1,2,3,4,5]
print (f'*what:', *what)
print (f'what:', what)
lol = [[1,4,7,11], [2,5,8,], [3,6,9,]]
ziplol = zip(*lol)
print (f'lol: {lol}')
print (f'*lol:->', *lol)
print (f'ziplol: {ziplol}')
for i in ziplol:
print (f'i={i}')
ziplol2 = zip(lol)
print (f'ziplol2: {ziplol2}')
for i in ziplol2:
print (f'i2={i}')
"""
###
# resequence collection using "*" unpacking
# - moves the first element in the collection to the end
###
fruits = ["pears", "apples", "oranges", "bananas", "strawberries"]
"""
first_fruit, *rest = fruits
rearranged_tuple = *rest, first_fruit
rearranged_list = [*rest, first_fruit]
print (f'fruits: ', fruits)
print (f'first_fruit: ', first_fruit)
print (f'rest: ', rest)
print (f'*rest: ', *rest)
print (f'rearranged_tuple: ', rearranged_tuple)
print (f'rearranged_list: ', rearranged_list)
# rotate 1st element to the end
rotated_fruits = [*fruits[1:], fruits[0]]
print (f'rotated_fruits: ', rotated_fruits)
"""
###
# a function to reverse the argument list passed in
###
def show_reversed(*args):
print(*args[::-1])
show_reversed(1,2,3)
show_reversed(*fruits)
| false
|
78f11800113f225702032ce9481c411f306d6658
|
rafaelribeiroo/scripts_py
|
/Mundo 03: Estruturas Compostas/23. Listas I/4. Inserção mais complexa.py
| 410
| 4.1875
| 4
|
# list define que será uma lista vazia até receber um append
valores = list()
for c in range(0, 5):
valores.append(int(input('Digite um valor: ')))
# Mostra apenas os elementos
for elemento in valores:
print(f'{elemento}...', end='')
# Mostra os elementos e o índice
for posição, elemento in enumerate(valores):
print(f'Na posição {posição} encontrei o valor {elemento}!')
| false
|
ec483614b64aa91427ce30b2c457e79141361e6c
|
rafaelribeiroo/scripts_py
|
/+100 exercícios com enunciados/102. Função para fatorial.py
| 874
| 4.15625
| 4
|
# 102. Crie 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.
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.
'''
# Fator nulo de fatoração é 1
fatorial = 1
for contador in range(n, 0, -1):
if show:
print(contador, end='')
if contador > 1:
print(f'{contador} x ', end='')
else:
print(f' = ', end='')
fatorial *= contador
return fatorial
print(fatorial(5, show=True))
| false
|
5e61b1c087b8d4f3b7144da7e7900aee7d8b8db2
|
rafaelribeiroo/scripts_py
|
/Mundo 03: Estruturas Compostas/31. Funções II/1. Docstrings.py
| 588
| 4.15625
| 4
|
# No PY, todos os comandos fornecem uma documentação para melhor compreensão,
# que pode ser acessada através de help(método). Em nossas funções, é
# possível oferecer isso também através dos comentários abaixo.
def contador(i, f, p):
"""
-> Faz uma contagem e mostra na tela.
:param i: início da contagem
:param f: fim da contagem
:param p: passo da contagem
:return: sem retorno
"""
c = i
while c <= f:
print(f'{c}', end='..')
c += p
print('FIM!')
contador(2, 10, 2)
# A partir disso, basta dar um help(contador)
| false
|
6307fa2237a0317e621459d2d764db4e10b8f639
|
rafaelribeiroo/scripts_py
|
/+100 exercícios com enunciados/26. Primeira e última ocorrência de uma string.py
| 564
| 4.125
| 4
|
# 26. Faça um programa que leia uma frase pelo teclado e mostre:
# > Quantas vezes aparece a letra "A".
# > Em que posição ela aparece a primeira vez.
# > Em que posição ela aparece a última vez.
frase = input('Digite uma frase: ').upper().strip()
print(f"Analisando a letra 'A', ela aparece {frase.count('A')} vezes")
# Porque +1? Porque o Python ignora o último valor, considerando o 0
print(f"Aparece pela 1ª vez na posição: {frase.find('A') + 1}")
# Adequar a posição no Python
print(f"E pela última vez em: {frase.rfind('A') + 1}")
| false
|
2fac6d1c50c76bc283fa9210f27854f62be7f0b5
|
rafaelribeiroo/scripts_py
|
/Mundo 03: Estruturas Compostas/27. Dicionários/4. Iterando dicionários.py
| 240
| 4.125
| 4
|
pessoas = {'nome': 'Rafael', 'sexo': 'M', 'idade': 25}
# Como no dict não há o ENUMERATE, podemos utilizar as características vistas
# anteriormente para repesentá-lo
for key, value in pessoas.items():
print(f'O {key} é {value}')
| false
|
26313125ba6626d10b33a608e93346bf56ccfb94
|
rafaelribeiroo/scripts_py
|
/+100 exercícios com enunciados/85. Listas com pares e ímpares.py
| 861
| 4.28125
| 4
|
# 85. Crie um programa onde o usuário possa digitar sete valores numéricos e
# cadastre-os em uma lista única que mantenha separados os valores pares e
# ímpares. No final, mostre os valores pares e ímpares em ordem crescente
# Podemos declarar dessa forma também, pra não ter que sempre ficar inserindo
# uma lista dentro de outra para "matrizar"
núm = [[], []]
valor = 0
for contador in range(1, 7 + 1):
valor = int(input(f'Digite o {contador}º valor: '))
# Se o valor inserido for ímpar
if valor % 2 == 0:
# Insere na minha 1ª lista
núm[0].append(valor)
else:
# Caso ímpar, insere na 2ª lista
núm[1].append(valor)
print('-=' * 30)
núm[0].sort()
núm[1].sort()
print(f'Os valores pares digitados foram: {núm[0]}')
print(f'Os valores ímpares digitados foram: {núm[1]}')
| false
|
4e2e19b88a59cf422a811ccc10f532147c66321b
|
rafaelribeiroo/scripts_py
|
/+100 exercícios com enunciados/37. Conversor de bases numéricas.py
| 901
| 4.34375
| 4
|
# 37. Escreva um programa que leia um número inteiro qualquer e peça para o
# usuário escolher qual será a base de conversão:
# > 1 para binário
# > 2 para octal
# > 3 para hexadecimal
num = int(input('Digite um número inteiro: '))
print('''Escolha uma das bases para conversão:
[ 1 ] converter para BINÁRIO
[ 2 ] converter para OCTAL
[ 3 ] converter para HEXADECIMAL''')
opção = int(input('Sua opção: '))
if opção == 1:
# As 2ª primeiras posições não me interessam então não tem porque eu
# exibir, portanto eu corto elas logo após converter
print(f'{num} convertido para BINÁRIO é igual a {bin(num)[2:]}')
elif opção == 2:
print(f'{num} convertido para OCTAL é igual a {oct(num)[2:]}')
elif opção == 3:
print(f'{num} convertido para HEXADECIMAL é igual a {hex(num)[2:]}')
else:
print('Opção inválida. Tente novamente')
| false
|
4bf760250f45132573e5bacef08da788ef893017
|
rafaelribeiroo/scripts_py
|
/+100 exercícios com enunciados/77. Contando vogais em tupla.py
| 521
| 4.125
| 4
|
# 77. Crie um programa que tenha uma tupla com várias palavras (não usar
# acentos). Depois disso, você deve mostrar, para cada palavra, quais
# são as suas vogais.
lista = (
'aprender', 'programar', 'linguagem', 'python',
'curso', 'grátis', 'estudar', 'praticar',
'trabalhar', 'mercado', 'programador', 'futuro'
)
for palavra in lista:
print(f'\nNa palavra {palavra.upper()} temos ', end='')
for letra in palavra:
if letra.lower() in 'aáeéióoóu':
print(letra, end=' ')
| false
|
ebc4b93409aaa4382720eb1c7eaa5ea50ab6b31d
|
dfi/Learning-edX-MITx-6.00.1x
|
/itertools.py
| 608
| 4.28125
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 14 20:10:18 2017
@author: sss
"""
# https://docs.python.org/3.5/library/itertools.html
import operator
def accumulate(iterable, func=operator.add):
'Return running totals'
# accumulate([1,2,3,4,5]) --> 1 3 6 10 15
# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
it = iter(iterable)
try:
total = next(it)
except StopIteration:
return
yield total
for element in it:
total = func(total, element)
yield total
data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
accumulate(data)
| true
|
a65f814ce9f62bc8cff8642691e206d8fa8c6b96
|
pabolusandeep1/python
|
/lab1/source code/password.py
| 854
| 4.15625
| 4
|
#validation cliteria for the passwords
import re# importing the pre-defined regular expressions
p = input("Input your password: ")
x = True
while x:# loop for checking the various cliteria
if (len(p)<6 or len(p)>16):#checking for the length
print('\n length out of range')
break
elif not re.search("\d",p):#checking for the numbers
print('number missing')
break
elif not re.search("[$@!*]",p):#checking for the numbers
print('special character missing')
break
elif not re.search("[a-z]",p):#checking for the numbers
print('lower case missing')
break
elif not re.search("[A-Z]",p):#checking for the numbers
print('upper case missing')
break
else:
print("Valid Password")
x=False
break
if x:
print("Not a Valid Password")
| true
|
6be0dd923383acba74f9820a0b4ac590b58618ed
|
jasonifier/tstp_challenges
|
/ch5/challenge4.py
| 732
| 4.28125
| 4
|
#!/usr/bin/env python3
about_me = {'height': 70, 'favorite_color': 'red', 'favorite_athlete': 'Stephen Curry', 'favorite_show': 'The Big Bang Theory'}
inquiry = input("Select what you want to learn about me by typing one of four letters for the attribute: (a) - 'height', (b) - 'favorite_color', (c) - 'favorite_athlete', (d) - 'favorite_show' ")
if inquiry == 'a':
print('My height is ' + str(about_me['height']))
elif inquiry == 'b':
print('My favorite color is ' + about_me['favorite_color'])
elif inquiry == 'c':
print('My favorite athlete is ' + about_me['favorite_athlete'])
elif inquiry == 'd':
print('My favorite TV show is ' + about_me['favorite_show'])
else:
print('You did not select a valid choice.')
| false
|
fad58160cbcd35d9a671c8bc1217cf151560fafd
|
jasonifier/tstp_challenges
|
/ch6/challenge2.py
| 247
| 4.125
| 4
|
#!/usr/bin/env python3
response_one = input("Enter a written communication method: ")
response_two = input("Enter the name of a friend: ")
sentences = "Yesterday I wrote a {}. I sent it to {}!".format(response_one,response_two)
print(sentences)
| true
|
4a68ac695f956f6f9ee1326e59d21ce5554362ee
|
jasonifier/tstp_challenges
|
/ch4/challenge1.py
| 289
| 4.15625
| 4
|
#!/usr/bin/env python3
def squared(x):
"""
Returns x ** 2
:param x: int, float.
:return: int, float square of x.
"""
return x ** 2
print(squared(5))
print(type(squared(5)))
print(squared(16))
print(type(squared(16)))
print(squared(5.0))
print(type(squared(5.0)))
| true
|
e81f21436059dc2b3cd7f16ca43473a3f6e0f30f
|
destleon/Python-project
|
/classact.py
| 1,933
| 4.25
| 4
|
Boy_NameOfWeeks = ['Kojo','kwabena','Kwaku','Yaw','Kofi','Kwame','Kwasi']
Girl_nameOfweeks =['Adjoa','Abena','Akua','Yaa','Afia','Ama','Esi']
dayOfBirth = input("please enter your day of birth ")
gender = input("are you a male or a female ")
loglist = []
if (dayOfBirth == 'monday' and gender == 'female'):
print("your name will be " , Girl_nameOfweeks[0])
elif(dayOfBirth == 'monday' and gender == 'male'):
print("your name will be ", Boy_NameOfWeeks[0])
elif(dayOfBirth == 'tuesday' and gender == 'female'):
print("your name will be ", Girl_nameOfweeks[1])
elif(dayOfBirth == 'tuesday' and gender == 'male'):
print("your name will be ", Boy_NameOfWeeks[1])
elif(dayOfBirth == 'wednesday' and gender == 'female'):
print("your name will be ", Girl_nameOfweeks[2])
elif(dayOfBirth == 'wednesday' and gender == 'male'):
print("your name will be ", Boy_NameOfWeeks[2])
elif(dayOfBirth == 'thursday' and gender == 'female'):
print("your name will be ", Girl_nameOfweeks[3])
elif(dayOfBirth == 'thursday' and gender == 'male'):
print("your name will be ", Boy_NameOfWeeks[3])
elif(dayOfBirth == 'friday' and gender == 'female'):
print("your name will be ", Girl_nameOfweeks[4])
elif(dayOfBirth == 'friday' and gender == 'male'):
print("your name will be ", Boy_NameOfWeeks[4])
elif(dayOfBirth == 'saturday' and gender == 'female'):
print("your name will be ", Girl_nameOfweeks[5])
elif(dayOfBirth == 'saturday' and gender == 'male'):
print("your name will be ", Boy_NameOfWeeks[5])
elif(dayOfBirth == 'sunday' and gender == 'female'):
print("your name will be ", Girl_nameOfweeks[6])
elif(dayOfBirth == 'sunday' and gender == 'male'):
print("your name will be ", Boy_NameOfWeeks[6])
else:
print("please check your input and try again")
loglist.append(dayOfBirth)
print("a", loglist , "born just used your app ")
| false
|
871016d4714e1d5e710bd7d3c06ab5a269040d70
|
Code-for-me-10/My-codes
|
/my_file5.py
| 1,158
| 4.1875
| 4
|
# booleans
print(True)
print("True")
print(type(True)) # bool type
print(type("True")) # string type
print(5==5)
print(5==6)
# loops
# 1. if
x = 10
y = 5
if x%y == 0:
print(True)
else:
print(False)
# 2. while
number = 1
while number < 10:
print(number)
if number == 7:
break
number = number + 1
# incorporating else in while loop
print("---------------------------------------else loop-----------------------------------------------------")
number2 = 5
while number2 < 10:
print(number2)
number2 = number2 + 1
else:
print("number is no longer less than 10")
Number3= (int(input("Enter your number")))
if Number3 == 0:
print("zero")
elif Number3 == 1:
print("one")
elif Number3 == 2:
print("Two")
elif Number3 == 3:
print("Three")
elif Number3 == 4:
print("Four")
elif Number3 == 5:
print("Five")
elif Number3 == 6:
print("Six")
elif Number3 == 7:
print("Seven")
elif Number3 == 8:
print("Eight")
elif Number3 == 9:
print("Nine")
elif Number3 == 10:
print("Ten")
else:
print("oops..! Check Your number.")
| false
|
76c7b4ba9c6176b96c050884111c397d651c2cba
|
Epiloguer/ThinkPython
|
/Chapter 2/Ex_2_2_3/Ex_2_2_3.py
| 612
| 4.15625
| 4
|
# If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile),
# then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again,
# what time do I get home for breakfast?
import datetime
easy_pace = datetime.timedelta(minutes = 8, seconds = 15)
easy_miles = 2
tempo = datetime.timedelta(minutes = 7, seconds = 12)
tempo_miles = 3
run_time = (easy_pace * easy_miles) + (tempo * tempo_miles)
start_time = datetime.timedelta(hours = 6, minutes = 52)
breakfast_time = start_time + run_time
print(f"If you start running at {start_time}, you will be home for breakfast at {breakfast_time}!")
| true
|
8c5f65fa6ce581a28ed8d34c5a36fa0c186af33d
|
Epiloguer/ThinkPython
|
/Chapter 1/Ex_1_2_3/Ex_1_2_3.py
| 643
| 4.15625
| 4
|
# If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace
# (time per mile in minutes and seconds)? What is your average speed in miles per hour?
kilometers = 10
km_mi_conversion = 1.6
miles = kilometers * km_mi_conversion
print(f'you ran {miles} miles')
minutes = 42
minutes_to_seconds = minutes * 60
seconds = 42
total_seconds = minutes_to_seconds + seconds
print(f'in {total_seconds} seconds')
average_pace_seconds = miles/seconds
print(f'at a pace of {average_pace_seconds} miles per second')
average_pace_minutes = miles / (total_seconds / 60)
print(f'or at a pace of {average_pace_minutes} miles per minute')
| true
|
b62fa67f503814abbe41952067be6b9083e7b0b9
|
ANUMKHAN07/assignment-1
|
/assign3 q6.py
| 203
| 4.21875
| 4
|
d = {'A':1,'B':2,'C':3} #DUMMY INNITIALIZATION
key = input("Enter key to check:")
if key in d.keys():
print("Key is present and value of the key is:",d[key])
else:
print("Key isn't present!")
| true
|
1f0714e66eb4c28d8c77ec279db5c6c45f178f81
|
Louise0709/calculator-
|
/calculator.py
| 617
| 4.3125
| 4
|
income=int(input('what\'s your salary?'))
salary=0
shouldPay=0
tax=0
def calculator(num):
shouldPay=num-5000
if shouldPay<=0:
tax=0
elif 0<shouldPay <=3000:
tax=shouldPay*0.03
elif 3000 < shouldPay <=3000:
tax=shouldPay*0.1-210
elif 12000< shouldPay <=25000:
tax=shouldPay<=0.2-1410
elif 25000< shouldPay <=25000:
tax=shouldPay*0.2 -1410
elif 35000 <shouldPay <=55000:
tax=shouldPay *0.3-4410
elif 55000<shouldPay <=80000:
tax=shouldPay*0.35-1760
else:
tax=shouldPay*0.45-15160
salary=income-tax
return '{:.2f}'.format(salary)
print('your income after taxed {}'.format(calculator(income)))
| false
|
5cecd539c025b0733629ff4c403d70e280f00284
|
PallaviGandalwad/Python_Assignment_1
|
/Assignment1_9.py
| 213
| 4.1875
| 4
|
print("Write a program which display first 10 even numbers on screen.")
print("\n")
def EvenNumber():
i=1
while i<=10:
print(i*2," ",end="");
i=i+1
#no=int(input("Enter Number"))
EvenNumber()
| true
|
47715f1e3fe9c0cc7dbb898ff0082d053ea6fa51
|
csyhhu/LeetCodePratice
|
/Codes/33/33.py
| 1,324
| 4.15625
| 4
|
def search(nums, target: int):
"""
[0,1,2,4,5,6,7] => [4,5,6,7,0,1,2]
Find target in nums
:param nums:
:param target:
:return:
"""
def binSearch(nums, start, end, target):
mid = (start + end) // 2
print(start, mid, end)
if start > end:
return -1
if nums[mid] == target:
return mid
if nums[start] <= nums[mid]: # [start, mid] is ordered. Attention here, less or equal for mid may be equal to start
if nums[start] <= target < nums[mid]: # target is within a order list
return binSearch(nums, start, mid - 1, target)
else:
return binSearch(nums, mid + 1, end, target)
else: # [mid, end] is ordered
if nums[end] >= target > nums[mid]: # target is within a order list
return binSearch(nums, mid + 1, end, target)
else: # target is outside a order list, direct it to another list
return binSearch(nums, start, mid - 1, target)
return binSearch(nums, 0, len(nums) - 1, target)
nums = [4,5,6,7,0,1,2]
target = 0
print(search(nums, target))
nums = [4,5,6,7,0,1,2]
target = 3
print(search(nums, target))
nums = [1]
target = 0
print(search(nums, target))
nums = [3,1]
target = 1
print(search(nums, target))
| true
|
c39b8d31be3c31cc2a914a2bd0ae5a380363b27b
|
zhanengeng/mysite
|
/知识点/字符串和常用数据结构/日付け計算.py
| 638
| 4.3125
| 4
|
'''入力した日付はその年何日目'''
def leap_year(year):
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
def which_day(year,month,day):
days_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days_count = 0
if leap_year(year):
days_of_month[1] = 29
for days in days_of_month[:month-1]:
days_count += days
days_count += day
return days_count
if __name__ == "__main__":
y = int(input("yearを入力:"))
m = int(input("monthを入力:"))
d = int(input("dayを入力:"))
print(which_day(y,m,d))
| true
|
9de40eb8d5d6abd67ff90ff2195562822399567f
|
lucien-stavenhagen/JS-interview-research
|
/fizzbuzz.py
| 902
| 4.21875
| 4
|
#
# and just for the heck of it, here's the
# Python 3.x version of FizzBuzz, using a Python closure
#
# Here's the original problem statment:
# "Write a program that prints all
# the numbers from 1 to 100.
# For multiples of 3, instead of the number,
# print "Fizz", for multiples of 5 print "Buzz".
# For numbers which are multiples of both 3 and 5,
# print "FizzBuzz".
#
def checkModulo(fizzbuzzfactor):
def ifmultiple(number):
return number % fizzbuzzfactor == 0
return ifmultiple
fizz = checkModulo(3)
buzz = checkModulo(5)
def fizzBuzzGenerator():
text=[]
for i in range(1,100):
if fizz(i) and buzz(i):
text.append("FizzBuzz")
elif buzz(i):
text.append("Buzz")
elif fizz(i):
text.append("Fizz")
else:
text.append(str(i))
return " ".join(text)
output = fizzBuzzGenerator()
print(output)
| true
|
d4e9e097d89d3db339d92adde12b682548adf8c8
|
Dipesh1Thakur/Python-Basic-codes
|
/marksheetgrade.py
| 329
| 4.125
| 4
|
marks=int(input("Enter the marks :"))
if (marks>=90):
print("grade A")
elif (marks>=80) and (marks<90):
print("grade B")
elif marks>=70 and marks<80:
print("grade C")
elif marks>=60 and marks<70:
print("grade D")
elif marks>=50 and marks<40:
print("grade E")
else:
print("Your grade is F")
| true
|
774075170cd50e0197b4c5a830515a9a5fac7211
|
zungu/learnpython
|
/lpthw/ex14.py
| 982
| 4.4375
| 4
|
#!/usr/bin/python
from sys import argv
#defines two items to be inputted for argv
(script, user_name) = argv
prompt1 = 'give me an answer you ass > '
prompt2 = 'I\'ll murder ye grandmotha if ye don\'t tell me > '
prompt3 = 'Sorry please answer, I\'m just having a bad day > '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
#defines a new variable, likes, with what the user enters into raw_input.
likes = raw_input(prompt1)
print "Where do you live %s?" % user_name
#defines a new variable "lives" with a user generated input
lives = raw_input(prompt2)
print "What kind of computer do you have?"
#defines a new variable, "computer" with a user generated input.
computer = raw_input(prompt3)
print """
Ok, so you said %r about liking me.
You live in %r. That is a cool place.
And you have a %r computer. Sweet!
""" % (likes, lives, computer) #calls the variables the user entered
| true
|
acca2584c588aab08753d32484a804b5e492d8e0
|
zungu/learnpython
|
/lpthw/ex20.py
| 1,249
| 4.28125
| 4
|
#!/usr/bin/python
from sys import argv
script, input_file = argv
#defines the function, the j can be any letter
def print_all(j):
print j.read()
def rewind (j) :
j.seek(0)
# defines a function, with a variable inside of it. line_count is a variable cleverly named so that the user knows what it is doing. later on, on line 31, we establish the current line.
def print_a_line(line_count, j) :
print line_count, j.readline()
current_file = open(input_file)
print "First let's print the whole file: \n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind (current_file)
print "Let's print three lines:\n"
#establishes the current line as line #1 in the .txt file
current_line = 1
#calls up to def print_a_line and counts the above current line to read it
print_a_line(current_line, current_file)
#adds one more line to current line, so now it is reading the second line
current_line = current_line + 1
#calls up to def print_a_line and counts +1 to readline(2) now
print_a_line(current_line, current_file)
#adds one more line to current_line, which is 2 from above. So now 3
current_line = current_line + 1
#reads line 3 of the .txt file that is current_file
print_a_line(current_line, current_file)
| true
|
5dde55554b5745f3dc71a7bb201d20a3e0496239
|
rehmanalira/Python-Practice-Problems
|
/Practice problem8 Jumble funny name.py
| 908
| 4.21875
| 4
|
"""
It is a program which gives funny name
"""
from random import shuffle # for shffling
from random import sample # sampling shuffle
def function_shuffling(ele): # this is a function which is used to shuflle with this is used for shuflling
ele=list(ele) # store the valu of list in ele
shuffle(ele) # shufle the list
return ''.join(ele) # return and join
if __name__ == '__main__':
name=int(input("Enter the how much names ou want"))
list1=[]
for i in range(name):
n1=str(input("Enter the name"))
list1.append(n1)
print("original list",list1)
res=[function_shuffling(ele) for ele in list1] # for shuffling ele is use like i or j ot anyhthing we use here as element
print("SHuffled list is",res)
# second way
res1=[''.join(sample(ele1,len(ele1))) for ele1 in list1] # this is sample way
print("Second shffeld ",res1)
| true
|
53df6c7f31947ba21c4a0e0bbed1840ed790e8d9
|
Ivankipsit/TalentPy
|
/May week5/Project1.py
| 1,917
| 4.25
| 4
|
"""
Create a python class ATM which has a parametrised constructor (card_no, acc_balance).
Create methods withdraw(amount) which should check if the amount is available on the
account if yes, then deduct the amount and print the message “Amount withdrawn”, if the
amount is not available then print the message “OOPS! Unable to withdraw amount, Low
balance”. Create another method called, deposit, which should deposit amount if amount is
positive and should print message “Amount deposited”. If not, print message “Invalid amount
to deposit”. Create a method called getBalance which should print current balances at any
given point of time.
Example: atm_acc_1 = ATM(“1234”, 400)
atm_acc_2 = ATM(“10001”, 100)
"""
class ATM:
def __init__(self,card_no,acc_balance):
#initiation of variables
self.card_no = card_no
self.acc_balance = acc_balance
def withdraw(self,w_amount):
#withdraw section
self.w_amount = w_amount
self.acc_balance -= self.w_amount
if self.acc_balance > 0 :
return "Amount withdrawn"
else:
self.acc_balance += self.w_amount
return "OOPS! Unable to withdraw amount, Low balance"
def deposit(self,d_amount):
#deposit section
self.d_amount = d_amount
if self.d_amount > 0 :
self.acc_balance += self.d_amount
return "Amount deposited"
else:
return "Invalid amount to deposit"
def getBalance(self):
#final section
return self.acc_balance
atm_acc_1 = ATM(123,400)
print(atm_acc_1.withdraw(300)) #Amount withdrawn
print(atm_acc_1.deposit(-100)) #Invalid amount to deposit
print(atm_acc_1.getBalance()) #100
print(atm_acc_1.withdraw(300)) #OOPS! Unable to withdraw amount, Low balance
print(atm_acc_1.getBalance()) #100
| true
|
d12f4c3636de41e75e9a4bf5e435166f00866b4e
|
minal444/PythonCheatSheet
|
/ArithmaticOperations.py
| 770
| 4.125
| 4
|
# Arithmetic Operations
print(10+20) # Addition
print(20 - 5) # Subtraction
print(10 * 2) # Multiplication
print(10 / 2) # Division
print(10 % 3) # Modulo
print(10 ** 2) # Exponential
# augmented assignment operator
x = 10
x = x + 3
x += 3 # augmented assignment operator
x -= 3 # augmented assignment operator
# Operator Precedence = Order of Operator
# Exponential --> multiplication or division --> addition or subtraction
# parenthesis take priority
# Math Functions
x = 2.9
print(round(x))
print(abs(-2.9)) # always gives positive number
# Math Module has more math functions
import math
print(math.ceil(2.9))
print(math.floor(2.9))
# For more information regarding Math - google it for Math module for python 3
| true
|
c7237ded5227b686fe4d6a005db6b52a7c5bf435
|
chandthash/nppy
|
/Project Number System/quinary_to_octal.py
| 1,525
| 4.71875
| 5
|
def quinary_to_octal(quinary_number):
'''Convert quinary number to octal number
You can convert quinary number to octal, first by converting quinary number to decimal and obtained decimal number to quinary number
For an instance, lets take binary number be 123
Step 1: Convert to deicmal
123 = 1 * 5^2 + 2 * 5^1 + 3 * 5^0
= 38 (Decimal)
Step 2: Convert to octal from the obtained decimal
8 | 38 | 6
-----
4
And our required octal number is 46 (taken in a reverse way)
'''
def is_octal():
count = 0
for quinary in str(quinary_number):
if int(quinary) >= 5:
count += 1
if count == 0:
return True
else:
return False
if is_octal():
decimal = 0
octal_number = ''
reversed_quinary = str(quinary_number)[::-1]
for index, value in enumerate(reversed_quinary):
decimal += int(value) * 5 ** index
while decimal > 0:
octal_number += str(decimal % 8)
decimal = decimal // 8
print(octal_number[::-1])
else:
print('Invalid quinary Number')
if __name__ == '__main__':
try:
quinary_to_octal(123)
except (ValueError, NameError):
print('Integers was expected')
| true
|
e0da7a3dd1e796cf7349392dc1681663e36616ad
|
chandthash/nppy
|
/Minor Projects/multiples.py
| 317
| 4.25
| 4
|
def multiples(number):
'''Get multiplication of a given number'''
try:
for x in range(1, 11):
print('{} * {} = {}'.format(number, x, number * x))
except (ValueError, NameError):
print('Integer value was expected')
if __name__ == '__main__':
multiples(10)
| true
|
dddc399fa7fc2190e838591ae38c24b3065afadd
|
purwar2804/python
|
/smallest_number.py
| 660
| 4.15625
| 4
|
"""Write a python function find_smallest_number() which accepts a number n and returns the smallest number having n divisors.
Handle the possible errors in the code written inside the function."""
def factor(temp):
count=0
for i in range(1,temp+1):
if(temp%i==0):
count=count+1
return count
def find_smallest_number(num):
temp=1
while(1):
x=factor(temp)
if(x==num):
return temp
else:
temp=temp+1
num=16
print("The number of divisors :",num)
result=find_smallest_number(num)
print("The smallest number having",num," divisors:",result)
| true
|
5ff2b74ab932957cfe36253a8d686018564a8c16
|
purwar2804/python
|
/longestsub.py
| 451
| 4.15625
| 4
|
def longest_substring(string):
l=[]
for i in range(0,len(string)):
s1=string[0]
for j in range(i+1,len(string)):
if(string[j] not in s1):
s1=s1+string[j]
else:
if(len(s1)>=3):
l.append(s1)
s2=""
for k in l:
if(len(k)>len(s2)):
s2=k
return s2
string=input()
print(longest_substring(string))
| false
|
37e7b3c7ea73bc62be4d046ce93db984b269e2aa
|
brawler129/Data-Structures-and-Algorithms
|
/Python/Data Structures/Arrays/reverse_string.py
| 805
| 4.40625
| 4
|
import sys
def reverse_string(string):
"""
Reverse provided string
"""
# Check for invalid input
if string is None or type(string) is not str:
return 'Invalid Input'
length = len(string)
# Check for single character strings
if length < 2:
return string # Return string itself
# Create empty string to store reversed string
reversed_string = ""
for i in range(length-1, -1, -1):
reversed_string += string[i]
return reversed_string
# Command line argument
# input_string = sys.argv[1]
""" A Few test cases """
# input_string = None # NULL
# input_string = 1 #Integer
# input_string = ['Hello!' , 'my' , 'name', 'is', 'Devesh.'] # Array
input_string = 'Hello! My name is Devesh.'
print(reverse_string(input_string))
| true
|
3425852ccba1415b95e0feaf62916082d4a3f8b6
|
itu-qsp/2019-summer
|
/session-8/homework_solutions/sort_algos.py
| 2,501
| 4.125
| 4
|
"""A collection of sorting algorithms, based on:
* http://interactivepython.org/runestone/static/pythonds/SortSearch/TheSelectionSort.html
* http://interactivepython.org/runestone/static/pythonds/SortSearch/TheMergeSort.html
Use the resources above for illustrations and visualizations.
"""
def bubble_sort(data_list):
for passnum in range(len(data_list) - 1, 0, -1):
for idx in range(passnum):
if data_list[idx] > data_list[idx + 1]:
temp = data_list[idx]
data_list[idx] = data_list[idx + 1]
data_list[idx + 1] = temp
#Growth rate is O(n*n)
#Bubble sort in 2 minutes: https://www.youtube.com/watch?v=xli_FI7CuzA
def selection_sort(data_list):
for fill_slot in range(len(data_list) - 1, 0, -1):
position_of_max = 0
for location in range(1, fill_slot + 1):
if data_list[location] > data_list[position_of_max]:
position_of_max = location
temp = data_list[fill_slot]
data_list[fill_slot] = data_list[position_of_max]
data_list[position_of_max] = temp
#O(n*n)
#Selection sort in 3 minutes: https://www.youtube.com/watch?v=g-PGLbMth_g
def merge_sort(data_list):
# print("Splitting ", data_list)
if len(data_list) > 1:
mid = len(data_list) // 2
left_half = data_list[:mid]
right_half = data_list[mid:]
merge_sort(left_half)
merge_sort(right_half)
i = 0
j = 0
k = 0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
data_list[k] = left_half[i]
i = i + 1
else:
data_list[k] = right_half[j]
j = j + 1
k = k + 1
while i < len(left_half):
data_list[k] = left_half[i]
i = i + 1
k = k + 1
while j < len(right_half):
data_list[k] = right_half[j]
j = j + 1
k = k + 1
# print("Merging ", data_list)
#O(n*logn) (linearithmic time)
#Merge sort in 3 minutes: https://www.youtube.com/watch?v=4VqmGXwpLqc
def sort_algo_b(data_list):
selection_sort(data_list)
def sort_algo_a(data_list):
merge_sort(data_list)
if __name__ == '__main__':
data_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
selection_sort(data_list)
print(data_list)
data_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
merge_sort(data_list)
print(data_list)
| true
|
b6e003c0946e13e0f2bc4d386cab5e3c966f2998
|
itu-qsp/2019-summer
|
/session-6/homework_solutions/turtle_geometry.py
| 1,424
| 4.34375
| 4
|
from turtle import Turtle, done
class GeometryTurtle(Turtle):
def make_square(self, width):
moves = [width] * 4
for move in moves:
self.right(90)
self.forward(move)
def make_rectangle(self, width, height):
moves = [width, height] * 2
for move in moves:
self.forward(move)
self.right(90)
def make_triangle(self, length):
moves = [length] * 3
for move in moves:
self.forward(move)
self.right(120)
def make_star(self, length):
moves = [length] * 5
for move in moves:
self.forward(move)
self.right(144)
def main():
my_turtle = GeometryTurtle(shape = "turtle")
my_turtle.make_square(50)
my_turtle.penup()
my_turtle.forward(70)
my_turtle.pendown()
for i in range(6):
my_turtle.right(60)
my_turtle.make_square(30)
my_turtle.penup()
my_turtle.forward(70)
my_turtle.pendown()
my_turtle.make_rectangle(50, 20)
my_turtle.penup()
my_turtle.forward(70)
my_turtle.pendown()
my_turtle.make_triangle(50)
my_turtle.penup()
my_turtle.forward(70)
my_turtle.pendown()
my_turtle.make_star(49)
# The call to the function `done` from the `turtle` module means that you
# Have to close the window manually
done()
if __name__ == '__main__':
main()
| false
|
3f859b0275a136b8b8078b7d0798c3496d57af06
|
itu-qsp/2019-summer
|
/session-6/homework_solutions/A.py
| 2,864
| 4.6875
| 5
|
"""
Create a Mad Libs program that reads in text files and lets the user add their own text anywhere
the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file.
For example, a text file may look like this, see file mad_libs.txt:
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
unaffected by these events.
The program would find these occurrences and prompt the user to replace them.
Enter an adjective:
silly
Enter a noun:
chandelier
Enter a verb:
screamed
Enter a noun:
pickup truck
The following text file would then be created:
The silly panda walked to the chandelier and then screamed. A nearby pickup
truck was unaffected by these events.
The results should be printed to the screen and saved to a new text file.
"""
# 1. Read in the mad_libs and save it as a list where the words are the items, initialize an empty list for the result
# 2. loop through all of the words.
# 3. check if the words are either ADJECTIVE, NOUN, ADVERB, or VERB
# 4. if they are, then replace them by a input.
# 5. Append all words to the result list
# 6. save result in a new file.
# Opens the mad_libs.txt and saves it as a list where the items are all of the words
with open("/Users/viktortorpthomsen/Desktop/qsp2019/session6_homework/mad_libs.txt", "r") as f:
words = f.read().split()
# Initializing a new list to store the result in
new_words = []
# Looping through all of the words in the list words
for word in words:
if "ADJECTIVE" in word:
# If the string "ADJECTIVE" is in the current word, then replace that part of the word
word = word.replace("ADJECTIVE", input("Enter an adjective:\n"))
elif "NOUN" in word:
# If the string "NOUN" is in the current word, then replace that part of the word
word = word.replace("NOUN", input("Enter a noun:\n"))
elif "ADVERB" in word:
# If the string "ADVERB" is in the current word, then replace that part of the word
word = word.replace("ADVERB", input("Enter an adverb:\n"))
elif "VERB" in word:
# If the string "VERB" is in the current word, then replace that part of the word
word = word.replace("VERB", input("Enter an verb:\n"))
# Append the word to the list, whether is was changes or not.
new_words.append(word)
# Prints the new_words list as a string, where all of the items (the words in the list) are seperated by " " (a white space)
print(" ".join(new_words))
# Write the new file
with open("/Users/viktortorpthomsen/Desktop/qsp2019/session6_homework/mad_libs_result.txt", "w") as f:
# Write the same string we printed in line 59 in the new file
f.write(" ".join(new_words))
# Open the new file to check that it was saved as we wanted
with open("/Users/viktortorpthomsen/Desktop/qsp2019/session6_homework/mad_libs_result.txt", "r") as f:
new_text = f.read()
print(new_text)
| true
|
7cf44380af29bb10e89ef1ec62ba1b2ee96c0066
|
fortiz303/python_code_for_devops
|
/join.py
| 290
| 4.34375
| 4
|
#Storing our input into a variable named input_join
input_join = input("Type a word, separate them by spaces: ")
#We will add a dash in between each character of our input
join_by_dash = "-"
#Using the join method to join our input. Printing result
print(join_by_dash.join(input_join))
| true
|
81151f0a5de8a7edda840bb24e97288a99d29ab0
|
MyreMylar/artillery_duel
|
/game/wind.py
| 2,110
| 4.15625
| 4
|
import random
class Wind:
def __init__(self, min_wind, max_wind):
self.min = min_wind
self.max = max_wind
self.min_change = -3
self.max_change = 3
self.time_accumulator = 0.0
# Set the initial value of the wind
self.current_value = random.randint(self.min, self.max)
self.last_change = 0
if self.current_value > 0:
self.last_change = 1
if self.current_value < 0:
self.last_change = -1
# Set the amount of time in seconds until the wind changes
self.time_until_wind_changes = 5.0
def change_wind(self):
# Set the amount of time in seconds until the wind changes
self.time_until_wind_changes = random.uniform(3.0, 8.0)
# Try to simulate the wind changing. Currently it is more likely to continue
# blowing in the same direction it blew in last time (4 times out of 5).
if self.last_change > 0:
change_value = random.randint(-1, self.max_change)
self.last_change = change_value
elif self.last_change < 0:
change_value = random.randint(self.min_change, 1)
self.last_change = change_value
else:
change_value = random.randint(-1, 1)
self.last_change = change_value
self.current_value += change_value
# Make sure the current wind value does not exceed the maximum or minimum values
if self.current_value > self.max:
self.current_value = self.max
if self.current_value < self.min:
self.current_value = self.min
def update(self, time_delta):
# The timeDelta value is the amount of time in seconds since
# the last loop of the game. We add it to the 'accumulator'
# to track when an amount of time has passed, in this case
# 3 seconds
self.time_accumulator += time_delta
if self.time_accumulator >= self.time_until_wind_changes:
self.time_accumulator = 0.0 # reset the time accumulator
self.change_wind()
| true
|
a39693609674bd616fe3f12e1cc173188d3688ae
|
svfarande/Python-Bootcamp
|
/PyBootCamp/Advance DS/advanced_lists.py
| 1,096
| 4.375
| 4
|
mylist = [1, 2, 3, 2]
print(mylist)
print(mylist.count(2)) # 2
# appending element -
print(mylist.append(4)) # None
print(mylist) # [1, 2, 3, 2, 4]
# appending list - incorrect way -
mylist.append([3, 5])
print(mylist) # [1, 2, 3, 2, [3, 5]]
# appending list - correct way -
mylist = [1, 2, 3, 2]
mylist = mylist + [3, 5]
print(mylist) # [1, 2, 3, 2, 3, 5]
# OR appending list - another correct way -
mylist = [1, 2, 3, 2]
mylist.extend([3, 5])
print(mylist) # [1, 2, 3, 2, 3, 5]
print(mylist.index(2)) # 1 # 1st successful hit
mylist.insert(3, 'insert me')
print(mylist) # [1, 2, 3, 'insert me', 2, 3, 5]
mylist.pop() # by default last element will be popped
print(mylist)
popped = mylist.pop(3)
print(popped) # insert me
print(mylist) # [1, 2, 3, 2, 3]
mylist.remove(2) # only removes 1st successful hit
print(mylist) # [1, 3, 2, 3]
# Below will affect original list
mylist.reverse()
print(mylist) # [3, 2, 3, 1]
mylist.sort()
print(mylist) # [1, 2, 3, 3]
mylist = [1, 3, 2, 3]
print(sorted(mylist)) # [1, 2, 3, 3]
print(mylist) # [1, 3, 2, 3]
| false
|
69e105a8de8977b9177b21a4219a2a6ea6b42e33
|
svfarande/Python-Bootcamp
|
/PyBootCamp/Advance DS/advanced_strings.py
| 1,664
| 4.28125
| 4
|
s = 'hellow world'
print(s.capitalize()) # Hellow world
print(s.lower()) # hellow world
print(s.upper()) # HELLOW WORLD
print(s) # hellow world
print(s.count('o')) # 2
print(s.find('o')) # 4 # 1st occurrence of that string
print(s.center(20, 'z')) # zzzzhellow worldzzzz # places the string in center
print('hello world'.center(20, 'z')) # zzzzhello worldzzzzz
print(s.center(10, 'z')) # hellow world
print('hello\tworld'.expandtabs()) # hello world
print('hello\tworld') # hello world
print(s.isnumeric()) # False
# A string is numeric if all characters in the string are numeric and
# there is at least one character in the string.
print(s.isalnum()) # False # because there is space(' ') in between 2 words
print('hellowworld'.isalnum()) # True
# A string is alpha-numeric if all characters in the string are alpha-numeric and
# there is at least one character in the string.
print(s.isalpha()) # False
# A string is alphabetic if all characters in the string are alphabetic and
# there is at least one character in the string.
print(s.islower()) # True
# A string is lowercase if all cased characters in the string are lowercase and
# there is at least one cased character in the string
print(s.isspace()) # False
# A string is whitespace if all characters in the string are whitespace and
# there is at least one character in the string.
print(s.endswith('d')) # True
print(s[-1] == 'd') # True
print(s.split('o')) # ['hell', 'w w', 'rld']
print(s.partition('o')) # ('hell', 'o', 'w world') # divide string at 1st occurrence
| false
|
ea2e97ed068f7dc534f6d1dd6318927d2ed01a4a
|
svfarande/Python-Bootcamp
|
/PyBootCamp/errors and exception.py
| 957
| 4.125
| 4
|
while True:
try: # any code which is likely to give error is inserted in try
number1 = float(input("Enter Dividend (number1) for division : "))
number2 = float(input("Enter Divisor (number2) for division : "))
result = number1 / number2
except ValueError: # it will run when ValueError occurs in try block
print("Looks like you didn't enter number. Try again.")
continue
except ZeroDivisionError: # it will run ZeroDivisionError occurs in try block
print("Looks like your divisor is 0. Try again.")
continue
except: # it will run when error occur but doesn't belong to above expected errors
print("Something is wrong. Try again.")
continue
else: # It will only run when either of the expect don't run
print("Division is = " + str(result))
break
finally: # Whatever may be the case this will run for sure
print("Great Learning !!")
| true
|
9b6c4e8219809f7e2235bdedad400d80f6d0be98
|
nage2285/day-3-2-exercise
|
/main.py
| 1,027
| 4.34375
| 4
|
# 🚨 Don't change the code below 👇
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
#print(type(height))
#print(type(weight))
#BMI Calculator
BMI = round(weight/ (height * height))
if BMI < 18.5 :
print (f"Your BMI is {BMI}, you are underweight.")
elif BMI < 25 :
print (f"Your BMI is {BMI}, you are normal weight.")
elif BMI < 30 :
print (f"Your BMI is {BMI}, you are slightly overweight.")
elif BMI < 35 :
print (f"Your BMI is {BMI}, you are obese.")
else :
print (f"Your BMI is {BMI}, you are clinically obese.")
# How to convert string into lower
#sentence = ("Mary Had a Little lamb")
#sentence_l = sentence.lower()
#print(sentence_l)
#How to count number of certain alphabets
#sentence = "Mary had a little lamb"
#sentence1 = sentence.count("a")
#sentence2 = sentence.count("t")
#count = sentence1 + sentence2
#print(sentence1)
#print(sentence2)
#print (type(count))
#print(count)
| true
|
f008d9f277104d710ab6268fd562d220c7850c86
|
semihsevik/BasicPython
|
/bubleSort.py
| 415
| 4.21875
| 4
|
#Buble Sort
def bubbleSort(arr):
arrLen = len(arr)
for i in range(arrLen - 1):
for j in range(0, arrLen-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [14 , 63 , 56 , 22 , 756 , 29 , 3]
print("Array:" , arr)
bubbleSort(arr)
#Sıralanmış listeyi list comprehension yapısı ile oluşturalım.
sortedArr = [i for i in arr]
print ("Sorted array:" , sortedArr)
| false
|
e7b53c7fbc4d829b538dd65e5b6014376d5416c2
|
semihsevik/BasicPython
|
/biggestDigit.py
| 247
| 4.1875
| 4
|
number = input("Sayı: ")
numOfDigits = len(number)
number = int(number)
digitList = []
for i in range(numOfDigits):
digit = number % 10
digitList.append(digit)
number //= 10
biggestDigit = max(digitList)
print(biggestDigit)
| false
|
c49c011ba6e6cf3ab79a148655948f6b51a0f3c1
|
AstroOhnuma/Unit5
|
/displaydate.py
| 446
| 4.125
| 4
|
#Astro Ohnuma
#11/16/17
#displaydate.py - displays the current date
import datetime
today = datetime.date.today()
today.day
today.month
today.year
today.weekday()
month = ['January','February','March','April','May','June','July','August','September','October','November','December']
weekday = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
print('Today is',weekday[today.weekday()],',',month[today.month],today.day,today.year)
| false
|
6c635536f0536a5559620557dde4b1d49941b1fc
|
waynessabros/Linguagem-Python
|
/script_13.py
| 834
| 4.53125
| 5
|
"""Em python strings são objetos
pode-se aplicar métodos a strings
string = string.metodo()
"""
#-*- coding: utf-8 -*-
a="Diego"
b="Mariana"
concatenar = a + " " + b
print(concatenar)
print(concatenar.lower())#lower = deixar tudo em minisculo
print(concatenar.upper())#upper = deixar tudo em maiusculo
concatenar2=concatenar.upper()
print(concatenar2)
#strip - Remove espaço e caracteres especiais
#split - converte a sequencia em lista
minha_string = "O rato roeu a roupa do rei de roma"
minha_lista = minha_string.split(" ")
print(minha_lista)
#como fazer busca na string
busca = minha_string.find("rei")#find procura onde esta a palavra em questão
print(busca)
print(minha_string[busca:])
busca2 = minha_string.find("rainha")
print(busca2)
minha_string2= minha_string.replace("o rei", "a rainha")
print(minha_string2)
| false
|
5d6f1d2bb57b752e8d5bbff3d6fad38c375976c5
|
waynessabros/Linguagem-Python
|
/script_17.py
| 747
| 4.3125
| 4
|
#listas em python
#-*- coding: utf-8 -*-
minha_lista = ["abacaxi","melancia", "abacate"]
minha_lista2 = [1,2,3,4,5]
minha_lista3 = ["abacaxi", 2, 9.89, True]
print(minha_lista)
print(minha_lista2)
print(minha_lista3)
print(minha_lista[0])#exibe determinado item da lista
for item in minha_lista:#imprime item por item
print(item)
tamanho = len(minha_lista)
print(tamanho)#exibe a quantidade de elementos da lista
minha_lista.append("Limão")#adiciona limãp a minha_lista
print(minha_lista)
if 3 in minha_lista2:
print("3 esta na lista") #procura se 3 esta em minha_lista2
del minha_lista[2:]#apagou os elementos da minha_lista : abacate e limão
print(minha_lista)
minha_lista4 = []
minha_lista4.append(57)
print(minha_lista4)
| false
|
4d7defe699a93eaed852f88c73029be2f50465f2
|
cs24k1993/Offer
|
/1.1.bubbleSort.py
| 763
| 4.1875
| 4
|
# coding:utf-8
'''
冒泡法:
第一趟:相邻的两数相比,大的往下沉。最后一个元素是最大的。
第二趟:相邻的两数相比,大的往下沉。最后一个元素不用比。
'''
def bubbleSort2(lists):
count = len(lists)
for i in range(count-1):
for j in range(count-i-1):
if lists[j] > lists[j+1]:
lists[j], lists[j+1] = lists[j+1], lists[j]
return lists
lists = [7, 8, 6, 2, 10, 5]
print bubbleSort2(lists)
def bubbleSort(lists):
count = len(lists)
for i in range(0, count):
for j in range(i+1, count):
if lists[i]>lists[j]:
lists[i], lists[j] = lists[j], lists[i]
return lists
lists = [7, 8, 6, 2, 10, 5]
print bubbleSort(lists)
| false
|
61d5f409e19effec42600395ec8e9ce06f88b956
|
UjjwalDhakal7/basicpython
|
/typecasting.py
| 1,793
| 4.46875
| 4
|
#Type Casting or Type Cohersion
# The process of converting one type of vaue to other type.
#Five types of data can be used in type casting
# int, float, bool, str, complex
#converting float to int type :
a = int(10.3243)
print(a)
#converting complex to int type cannot be done.
#converting bool to int :
b = int(True)
c = int(False)
print(b,c)
#converting string to int type :
#string should contain int or float values which should be specified in base 10.
d = int('50')
print(d)
#converting int to float :
print(float(12))
print(float(0b101))
#converting complex to float is also not possible.
#converting bool to float :
print(float(True))
print(float(False))
#converting str to float :
print(float('200'))
#converting int, float into complex :
#Form 1 :
#entering only one argument, pvm will assume it as real value.
print(complex(1))
print(complex(10.4))
print(complex(True))
print(complex(False))
print(complex('50'))
#Form 2 :
#entering two arguments, pvm will assume first argument as real and the other as imaginery value.
print(complex(10,3))
print(complex(10.4, 10.2))
#str to complex has various restrictions.
#converting to bool types:
#For int and float types,
#if the argument is 0, the bool value will be False, else true.
print(bool(10))
print(bool(0))
#For complex types,
#if real and imaginary part is 0, bool value is False, else True.
print(bool(10+10j))
print(bool(0j))
#For str types,
#if the argument is empty then only bool value is False, else any value is True.
print(bool('True'))
print(bool("False"))
print(bool(''))
#converting to str types :
a = str(10)
b = str(0b1010)
c = str(10.67)
d = str(10+2j)
print(type(a), type(b), type(c))
| true
|
48741d9ccf235ca379a3b7ead7082637b33c450d
|
UjjwalDhakal7/basicpython
|
/booleantypes.py
| 248
| 4.21875
| 4
|
#boolean datatypes
#we use boolean datatypes to work with boolean values(True/False, yes/no) and logical expressions.
a = True
print(type(a))
a = 10
b=20
c = a<b
print(c)
print(type(c))
print(True + True)
print(False * True)
| true
|
50ed06f5df2f648636a8237cca5ca3cd36732b2c
|
UjjwalDhakal7/basicpython
|
/intdatatypes.py
| 1,181
| 4.40625
| 4
|
#we learn about integer datatypes here:
#'int' can be used to represent short and long integer values in python 3
# python 2 has a concpet of 'long' vs 'int' for long and short int values.
#There are four ways to define a int value :
#decimal, binary, octal, hexadecimal forms
#decimal number system is the default number system
#To define a binary number it should have a prefix '0b' or '0B':
a = 0b1111
A = 0B11001
print(a)
print(A)
#To define a octal number it should have a prefix '0o' or '0O':
b = 0o1341
B = 0O12301
print(b)
print(B)
#To define a hexa number it should have a prefix '0x' or '0X':
c = 0x2342AB
C = 0X43667F
print(c)
print(C)
#in case of Hexa form python does not follow case sensitiveness.
print(0xBeef)
print(0XAbcD)
#Base Conversion Functions :
#1. bin()
#can be used to convert other forms of number to binary number system.
bin(0o127)
bin(15)
bin(0X12A)
#2. oct() >>
#can be used to convert other forms of number to octal number system.
oct(0b100110)
oct(15)
oct(0X12A)
#3. hex() >>
#can be used to convert other forms of number to binary number system.
hex(0o127)
hex(15)
print(hex(0b100110))
| true
|
8709a8799021fed49bb620d7088c22bc086492dd
|
ewrwrnjwqr/python-coding-problems
|
/python-coding-problems/unival tree challenge easy.py
| 1,921
| 4.25
| 4
|
#coding problem #8
#A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
#Given the r to a binary tree, count the number of unival subtrees.
# the given tree looks like..
# 0
# / \
# 1 0
# / \
# 1 0
# / \
# 1 1
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
node_right_left1 = Node(1, Node(1), Node(1))
node_right1 = Node(0, node_right_left1, Node(0))
t = Node(0, Node(1), node_right1)
def in_order(r):
if r.left:
in_order(r.left)
print(str(r.value) + ', ', end='')
if r.right:
in_order(r.right)
in_order(t)
print('')
def is_unival(r):
if r is None:
return True
if r.left is not None and r.left.value != r.value:
return False
if r.right is not None and r.right.value != r.value:
return False
if is_unival(r.left) and is_unival(r.right):
return True
return False
def count_univals(r):
if r is None:
return 0
total_count = count_univals(r.left) + count_univals(r.right)
if is_unival(r):
total_count += 1
return total_count
def count_univals2(r):
total_count, is_unival = helper(r)
return total_count
def helper(r):
if r is None:
return 0, True
left_count, is_left_unival = helper(r.left)
right_count, is_right_unival = helper(r.right)
is_unival = True
if not is_left_unival or not is_right_unival:
is_unival = False
if r.left is not None and r.left.value != r.value:
is_unival = False
if r.right is not None and r.right.value != r.value:
is_unival = False
if is_unival:
return left_count + right_count + 1, True
else:
return left_count + right_count, False
print(count_univals(t), 'should be 5')
| true
|
1f3b48d098480dd34dee90aaabe24822b6682e71
|
ColeCrase/Week-5Assignment
|
/Page82 pt1.py
| 228
| 4.125
| 4
|
number = int(input("Enter the numeric grade: "))
if number > 100:
print("Error: grade must be between 100 and 0")
elif number < 0:
print("Error: grade must be between 100 and 0")
else:
print("The grade is", number)
| true
|
e25f0c584eecec3fba8b638eba070b15fc4d245c
|
subho781/MCA-Python-Assignment
|
/Assignment 2 Q6.py
| 213
| 4.375
| 4
|
number = int(input(" Enter the number : "))
if((number % 5 == 0) and (number % 3 == 0)):
print("Given Number is Divisible by 5 and 3",number)
else:
print("Given Number is Not Divisible by 5 and 3",number)
| false
|
8de67b2e8d4fb914a3b9f3e29a5a85d9cba30c0c
|
subho781/MCA-Python-Assignment
|
/Assignment 2 Q7.py
| 337
| 4.1875
| 4
|
#WAP to input 3 numbers and find the second smallest.
num1=int(input("Enter the first number: "))
num2=int(input("Enter the second number: "))
num3=int(input("Enter the third number: "))
if(num1<=num2 and num1<=num3):
s2=num1
elif(num2<=num1 and num2<=num3):
s2=num2
else:
s2=num3
print('second smallest number is :',s2)
| true
|
bd2ef2d43a62650f68d140b1097e98b73a27f293
|
Athenstan/Leetcode
|
/Easy/Edu.BFSzigzag.py
| 888
| 4.15625
| 4
|
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
#first try at the problem
def traverse(root):
result = []
if root is None:
return result
# TODO: Write your code here
queue = deque()
queue.append(root)
toggle = True
while queue:
levelsize = len(queue)
currentlevel = []
for _ in range(levelsize):
currentnode = queue.popleft()
if toggle:
currentlevel.append(currentnode.val)
else:
currentlevel.insert(0,currentnode.val)
if currentnode.left:
queue.append(currentnode.left)
if currentnode.right:
queue.append(currentnode.right)
toggle = not toggle
result.append(currentlevel)
return result
#Generally correct, logic was done properly and the method executed as promised. Need to research more into appendleft function
| true
|
d407f3540a1a4d7240fb572a3e1fa12e430cdced
|
rjimeno/PracticePython
|
/e6.py
| 273
| 4.125
| 4
|
#!/usr/bin/env python3
print("Give me a string and I will check if it is a palindrome: ")
s = input("Type here: ")
for i in range(0, int(len(s)/2)):
l = len(s)
if s[i] != s[l-1-i]:
print("Not a palindrome.")
exit(1)
print("A palindrome!")
exit(0)
| true
|
f72b45ba5408c8ab5afbe1d88e96c10bb157b920
|
rjimeno/PracticePython
|
/e3.py
| 1,479
| 4.15625
| 4
|
#!/usr/bin/env python3
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
default_limit = 5
for x in a:
if x < default_limit:
print(x)
# Extras:
# 1.Instead of printing the elements one by one, make a new list that has all
# the elements less than 5 from this list in it and print out this new list.
def list_less_than( input_array, limit=default_limit):
"""
>>> list_less_than([])
[]
>>> a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> list_less_than(a)
[1, 1, 2, 3]
>>> list_less_than(a, 8)
[1, 1, 2, 3, 5]
"""
l = []
for n in input_array:
if n < limit:
l.append(n)
return l
# 2. Write this in one line of Python.
def list_less_than_oneliner(i_a, l=default_limit):
"""
>>> list_less_than([])
[]
>>> a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> list_less_than_oneliner(a)
[1, 1, 2, 3]
>>> list_less_than_oneliner(a, 8)
[1, 1, 2, 3, 5]
"""
return [n for n in i_a if n < l]
try:
limit = int(input("What's the smallest number you don't care about (i.e. "
"What's the limit? Default is {}.)" .format(
default_limit)))
except Exception as e:
print("That did not look like a number: '{}'".format(e))
print("Will default of {} instead.".format(default_limit),
file=sys.stderr)
limit = default_limit
print(list_less_than_oneliner(a, limit))
if '__main__' == __name__:
import doctest
doctest.testmod()
| true
|
4c45d8b55ec5830f9fc6d0287b513fdc129b44dc
|
siglite/nlp100knock
|
/chapter1/knock00.py
| 1,274
| 4.1875
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 00. 文字列の逆順
# 文字列 "stressed" の文字を逆に(末尾から先頭に向かって)並べた文字列を得よ.
text = "stressed"
answer = "desserts"
# Case 1
##########
case1 = text[::-1] # str[start:end:step] : start から end まで step 毎の文字列を取得
# text[1:7:2] => "tes" (1 から 7 まで 2 文字毎)
# text[:-1:2] => "srse" (最初から後ろの 2 文字目まで 2 文字毎)
# text[::-1] => 最初から最後まで -1 文字ずつ
assert case1 == answer
print("Case 1: '" + case1 + "'")
# => "Case 1: 'desserts'"
# Case 2
##########
lst = list(text) # => ['s', 't', 'r', 'e', 's', 's', 'e', 'd']
lst.reverse() # => ['d', 'e', 's', 's', 'e', 'r', 't', 's']
case2 = ''.join(lst) # => "desserts" ( '' で文字列を連結)
assert case2 == answer
print("Case 2: '" + case2 + "'")
# => "Case 2: 'desserts'"
# Case 3
##########
lst = list(text) # => ['s', 't', 'r', 'e', 's', 's', 'e', 'd']
rvs = reversed(lst) # => ['d', 'e', 's', 's', 'e', 'r', 't', 's']
case3 = ''.join(rvs) # => "desserts"
assert case3 == answer
print("Case 3: '" + case3 + "'")
# => "Case 3: 'desserts'"
| false
|
b5a3565e203b64adf84a1446dda1b7fe0d6ce6c6
|
james-hadoop/JamesPython
|
/web_crawler/showTuple.py
| 1,166
| 4.21875
| 4
|
#!/usr/bin/env python
#-*- coding: utf-8 -*-
__author__ = 'hstking hstking@hotmail.com'
class ShowTuple(object):
def __init__(self):
self.T1 = ()
self.createTuple()
self.subTuple(self.T1)
self.tuple2List(self.T1)
def createTuple(self):
print(u"创建元组:")
print(u"T1 = (1,2,3,4,5,6,7,8,9,10)")
self.T1 = (1,2,3,4,5,6,7,8,9,10)
print(u"T1 = "),
print(self.T1)
print('\n')
def subTuple(self,Tuple):
print(u"元组分片:")
print(u"取元组T1的第4个到最后一个元组组成的新元组,执行命令T1[3:]")
print(self.T1[3:])
print(u"取元组T1的第2个到倒数第2个元素组成的新元组,步长为2,执行命令T1[1:-1:2]")
print(self.T1[1:-1:2])
print('\n')
def tuple2List(self,Tuple):
print(u"元组转换成列表:")
print(u"显示元组")
print(u"T1 = "),
print(self.T1)
print(u"执行命令 L2 = list(T1)")
L2 = list(self.T1)
print(u"显示列表")
print(u"L2 = "),
print(L2)
print(u"列表追加一个元素100后,转换成元组。执行命令L2.append(100) tuple(L2)")
L2.append(100)
print(u"显示新元组")
print(tuple(L2))
if __name__ == '__main__':
st = ShowTuple()
| false
|
c6e36b6fb21454dbfb35fcf4862afeb97c3abbc5
|
souzartn/Python2Share
|
/other/completed/Rock_Paper_Scissors.py
| 1,296
| 4.34375
| 4
|
################################################################
# Challenge 02
# Game "Rock, Paper, Scissors"
# Uses: Basic Python - e.g. If, elif,input, print
################################################################
import os
clearScreen = lambda: os.system('cls')
def computeGame(u1, u2):
if u1 == u2:
return("It's a tie!")
elif u1 == 'rock':
if u2 == 'scissors':
return("Rock wins!")
else:
return("Paper wins!")
elif u1 == 'scissors':
if u2 == 'paper':
return("Scissors win!")
else:
return("Rock wins!")
elif u1 == 'paper':
if u2 == 'rock':
return("Paper wins!")
else:
return("Scissors win!")
else:
return("Invalid input! One of the player did not enter rock, paper or scissors, try again.")
sys.exit()
clearScreen()
print("---------------------------------------------------------")
print("Game: Rock, Paper, Scissors!")
user1_answer = input("Player01, do yo want to choose rock, paper or scissors? ")
user2_answer = input("Player02, do you want to choose rock, paper or scissors? ")
result = computeGame(user1_answer, user2_answer)
print(result)
print("---------------------------------------------------------")
| true
|
80e6a92937db9f5a34465ec78fff113e99b1e4a9
|
neerajmaurya250/100-Days-of-Code
|
/Day-12/power.py
| 417
| 4.125
| 4
|
terms = int(input("How many terms? "))
result = list(map(lambda x: 2 ** x, range(terms)))
# display the result
print("The total terms is:",terms)
for i in range(terms):
print("2 raised to power",i,"is",result[i])
# output:
# How many terms? 5
# The total terms is: 5
# 2 raised to power 0 is 1
# 2 raised to power 1 is 2
# 2 raised to power 2 is 4
# 2 raised to power 3 is 8
# 2 raised to power 4 is 16
| true
|
a805c9af0f10ca75770fc88d7b33967e5af71cfc
|
everydaytimmy/code-war
|
/7kyu.py
| 716
| 4.1875
| 4
|
# In this kata, you are asked to square every digit of a number and concatenate them.
# For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
# Note: The function accepts an integer and returns an integer
def square_digits(num):
return int(''.join(str(int(i)**2) for i in str(num)))
###------ Over The Road ------###
# You've just moved into a perfectly straight street with exactly n identical houses on either side of the road. Naturally, you would like to find out the house number of the people on the other side of the street. The street looks something like this:
def over_the_road(address, n):
distance = (2*n) + 1
return distance - address
| true
|
cdc5c85f46fd305ca907c9fbade019303c7b3c9d
|
Keion-Larsen/cp1404practicals
|
/prac_05/hex_colours.py
| 587
| 4.25
| 4
|
HEXADECIMAL_COLOURS = {"AliceBlue": '#f0f8ff', 'beige': 'f5f5dc', 'black': '000000', 'blue': '#0000ff',
'brown': '#a52a2a', 'chocolate': '#d2691e', 'coral': '#ff7f50',
'cyan1': '#00ffff', 'DarkGreen': '#006400', 'firebrick': '#b22222'}
colour_name = input("Please enter a colour name: ")
while colour_name != "":
if colour_name in HEXADECIMAL_COLOURS:
print("{} has code: {}".format(colour_name, HEXADECIMAL_COLOURS[colour_name]))
else:
print("Invalid colour")
colour_name = input("Please enter a colour name: ")
| false
|
1a240fc55219fb3bc62c04352bbc734a568ffd46
|
frobes/python_learning
|
/abnormal/json.py
| 1,443
| 4.28125
| 4
|
#使用模块json存储数据
#json能让简单的python数据结构转储到文件中,并在程序再次运行时加载文件中的数据。
#json.dump()和json.load()
#number_writer.py
import json
numbers = [2,3,5,7,11,13]
filename = 'numbers.json'
#使用函数json.dump()将数字列表存储到文件numbers.json
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)
#AttributeError: module 'json' has no attribute 'dump'
#number_reader.py
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
#remember_me.py
import json
username = input("what's your name?")
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We'll remember you when you come back, "+username+" !")
#greet_user.py
import json
filename = 'username.json'
with open(filename) as f_obj:
username = json.load(f_obj)
print("Welcome back,"+username+" !")
#try代码块
import json
#如果以前存储了用户名就加载,否则提示用户输入用户名并存储它。
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("what's your name?")
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We'll remember you when you come back, "+username+" !")
else:
print("Welcome back,"+username+" !")
| false
|
08c96e56664470ca7bd05aed0a3d8f583bd57b1d
|
ksakkas/Learn-Python
|
/greek/class.py
| 835
| 4.125
| 4
|
# Κλάσεις στην Python
class mclass: # Δημιουργία κλάσης με όνομα mclass
x = 5
p1 = mclass() # Δημιουργήστε ένα αντικείμενο με το όνομα p1 και εκτυπώστε την τιμή του x
print(p1.x)
print("--------------------")
class Person:
def __init__(self, name, age): # Η συνάρτηση __init __ () καλείται αυτόματα κάθε φορά που η κλάση χρησιμοποιείται για τη δημιουργία ενός νέου αντικειμένου.
# Αντιστοιχίσετε τιμές για το όνομα και την ηλικία
self.name = name
self.age = age
p1 = Person("Kostas", 21)
print(p1.name)
print(p1.age)
| false
|
c944e5314444364dfcffe437c49a16cd70062888
|
rjrishav5/Codes
|
/Linkedlist/insert_doubly_linkedlist.py
| 2,193
| 4.28125
| 4
|
class Node:
def __init__(self,data):
self.data = data
self.next = None
self.prev = None
class doubly_linkedlist:
def __init__(self):
self.head = None
# insert node at the end of a doubly linkedlist
def at_end(self,data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
else:
temp = self.head
while(temp.next is not None):
temp = temp.next
temp.next = new_node
new_node.prev = temp
# insert node at the begining of a doubly linkedlist
def at_begining(self,data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
# insert node at a given position in doubly linkedlist
def at_position(self,position,data):
new_node = Node(data)
if (position == 1):
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
else:
temp = self.head
i = 2
while(i <=position-1):
if(temp.next is not None):
temp = temp.next
i+=1
if (temp.next is not None):
new_node.next = temp.next
new_node.prev = temp
temp.next = new_node
if(new_node.next is not None):
new_node.next.prev = new_node
# print the doubly linkedlist
def print_llist(self):
temp = self.head
if (temp is not None):
print("\nThe list contains:",end=" ")
while(temp is not None):
print(temp.data,end=" ")
temp = temp.next
else:
print("The list is empty")
dllist = doubly_linkedlist()
dllist.at_end(2)
dllist.at_end(3)
dllist.at_end(4)
dllist.at_end(5)
dllist.at_end(6)
dllist.at_end(7)
dllist.print_llist()
dllist.at_position(3,15)
dllist.print_llist()
dllist.at_position(1,20)
dllist.print_llist()
| true
|
596d01a48433701abcdf0b13d338b6d176d3de90
|
YOON81/PY4E-classes
|
/09_dictionaries/exercise_04.py
| 973
| 4.25
| 4
|
# Exercise 4: Add code to the above program to figure out who has the most messages
# in the file. After all the data has been read and the dictionary has been created,
# look through the dictionary using a maximum loop (see Chapter 5: Maximum and minimum
# loops) to find who has the most messages and print how many messages the person has.
fname = input('Enter a file name: ') # mbox-short.txt
if len(fname) < 1:
fname = 'mbox-short.txt'
try:
fhand = open(fname)
except:
print('Check the name again.')
exit()
emailist = dict()
for line in fhand:
line = line.rstrip()
word = line.split()
if line.startswith('From '):
emailist[word[1]] = emailist.get(word[1], 0) + 1
#print(emailist)
largest = 0
themail = None
for key, value in emailist.items():
if largest == 0 or value > largest:
largest = value
themail = key
print('The most message is', themail, largest) # The most message is cwen@iupui.edu 5
# good job Yoon!
| true
|
92514ac1daed990f7d22f402f23760511642d1c1
|
YOON81/PY4E-classes
|
/04_functions/exercise_06.py
| 759
| 4.15625
| 4
|
# Exercise 6: Rewrite your pay computation with time-and-a-half for overtime and
# create a function called computepay which takes two parameters (hours and rate).
# ** 첫번째 질문에 문자 입력했을 때 에러 메세지 뜨는 건 아직 해결 안됨 **
# ** 마지막 프린트문에 에러 뜸 ! **
hours = input('Enter Hours: ')
rate = input('Enter Rate: ')
try:
hours = float(hours)
rate = float(rate)
def computepay(hours, rate):
if hours <= 40:
hours_pay = (hours * rate)
return hours_pay
else:
hours_pay = (40 * rate) + (hours - 40) * rate * 1.5
return hours_pay
except ValueError:
print('Error, Please enter numeric input')
print(computepay(hours, rate))
| true
|
8dbdb6407f75391c2148ac54a31056364c8cb58c
|
SindiCullhaj/pcs2
|
/lecture 5 - sorting/insertion.py
| 280
| 4.125
| 4
|
def insertionSort(list):
for i in range(1, len(list)):
for j in range(0, i):
if (list[i] < list[j]):
item = list.pop(i)
list.insert(j, item)
a = [5, 1, 4, 2, 6, 3]
print("Initial: ", a)
insertionSort(a)
print("Final: ", a)
| false
|
7f9d7da99a451c6e90b34331a02076cdbe4b2d3b
|
brad93hunt/Python
|
/github-python-exercises/programs/q12-l2-program.py
| 482
| 4.125
| 4
|
#!/usr/bin/env python
#
# Question 12 - Level 2
#
# Question:
# Write a program, which will find all such numbers between 1000 and 3000 (both included)
# such that each digit of the number is an even number.
# The numbers obtained should be printed in a comma-separated sequence on a single line.
def main():
# Print number for each number in the range of 1000 - 3000 if num % 2 == 0
print [i for i in range(1000,3001) if i % 2 == 0]
if __name__ == '__name__':
main()
| true
|
9bd97f882ac5185dd2f78b4f4ed83e3e7c930de6
|
brad93hunt/Python
|
/github-python-exercises/programs/q13-l2-program.py
| 595
| 4.21875
| 4
|
#!/usr/bin/env python
# coding: utf-8
#
# Question 13 - Level 2
#
# Question:
# Write a program that accepts a sentence and calculate the number of letters and digits.
# Suppose the following input is supplied to the program:
# hello world! 123
# Then, the output should be:
# LETTERS 10
# DIGITS 3
def main():
user_input = raw_input('Please enter a string of letters and numbers: ')
letters = sum(c.isaplha() for c in user_input)
numbers = sum(c.isdigit() for c in user_input)
print 'Letters: ', letters
print 'Numbers: ', numbers
if __name__ == '__main__':
main()
| true
|
2af9387667d6254a491cef429c85c32e75a3c2d8
|
Artem123Q/Python-Base
|
/Shimanskiy_Artem/homework_5/homework5_2.py
| 788
| 4.25
| 4
|
'''
Task 5.2
Edit your previous task: put the results into a file.
Then create a new python script and import your previous program to the new script.
Write a program that reads the file and prints it three times.
Print the contents once by reading in the entire file, once by looping over the file object,
and once by storing the lines in a list and then working with them outside the 'with' block.
'''
'''from homework_5_1 import summ
print(summ())
with open('file_test', 'a') as in_file:
for i in range(3):
read_3_times = in_file.write(f'{summ()}\n')
print(read_3_times)'''
with open('file_test') as read_all:
file_value = read_all.read()
print(file_value)
for i in file_value:
print(i)# loop
list_1 = []
for i in file_value:
list_1.append(i)
| true
|
14d073161823c4a5e088b42bf08480dc072cc804
|
KonstBelyi/Python_hw
|
/lesson_9/task_3.py
| 1,566
| 4.25
| 4
|
"""
Даны значения двух моментов времени, принадлежащих одним и тем же суткам: часы, минуты и секунды для каждого из
моментов времени. Известно, что второй момент времени наступил не раньше первого. Определите, сколько секунд прошло
между двумя моментами времени. Программа на вход получает три целых числа: часы, минуты, секунды, задающие первый
момент времени и три целых числа, задающих второй момент времени. Выведите число секунд между этими моментами времени.
"""
hours_1 = int(input('Enter an hour for the first moment (0-23): '))
minutes_1 = int(input('Enter minutes for the first moment (0-59): '))
seconds_1 = int(input('Enter seconds for the first moment (0 - 59): '))
print()
hours_2 = int(input('Enter an hour for the second moment (0-23): '))
minutes_2 = int(input('Enter minutes for the second moment (0-59): '))
seconds_2 = int(input('Enter seconds for the second moment (0 - 59): '))
moment1_to_seconds = hours_1 * 360 + minutes_1 * 60 + seconds_1
moment2_to_seconds = hours_2 * 360 + minutes_2 * 60 + seconds_2
secs_between_moments = moment2_to_seconds - moment1_to_seconds
print()
print('Seconds between these two moments: {} seconds.'.format(secs_between_moments))
| false
|
5b8d1ace63c60e8cd8b80d6a9dbeb6fdd003f55b
|
KonstBelyi/Python_hw
|
/lesson_5/task_4.py
| 958
| 4.21875
| 4
|
"""
4. Дана строка, состоящая ровно из двух слов, разделенных пробелом. Переставьте эти слова местами. Результат запишите в
строку и выведите получившуюся строку.
При решении этой задачи посторайтесь не пользоваться циклами и инструкцией `if`.
"""
string = 'Волшебный Пендаль' # input('Please, enter a string: ')
print('Дана строка: "{}"'.format(string))
probel_idx = string.find(' ')
print('Находим индекс пробела, который разделяет слова: "{}"'.format(probel_idx))
word1 = string[0:probel_idx]
print('Первое слово: "{}"'.format(word1))
word2 = string[probel_idx+1:]
print('Второе слово: "{}"'.format(word2))
print('Переворачиваем строку: "{} {}"'.format(word2, word1))
| false
|
90f7be5030f16383990d1b86da825e14378d3e99
|
KonstBelyi/Python_hw
|
/lesson_5/task_7.py
| 876
| 4.65625
| 5
|
"""
Дана строка, в которой буква `h` встречается минимум два раза. Удалите из этой строки первое и последнее вхождение
буквы `h`, а также все символы, находящиеся между ними.
При решении этой задачи использовать циклы - ЗАПРЕЩЕНО! (Задача решается в 3 (три) строчки кода. Понадобятся методы поиска,
срезы и метод replace)
"""
string = 'Manhattan is my home for this hard year!'
print(string)
first_h = string.find('h')
print('The index of the first "h" is: {}'.format(first_h))
last_h = string.rfind('h')
print('The index of the last "h" is: {}'.format(last_h))
string = string.replace(string[first_h:last_h+1], '')
print(string)
| false
|
cc3ac6ecc1a37725a461e77c9bc38e0b8670763a
|
KonstBelyi/Python_hw
|
/lesson_9/task_5.py
| 749
| 4.5625
| 5
|
"""
Дано целое, положительное ЧИСЛО (не строка). Необходимо его перевернуть (работаем как с ЧИСЛОМ). Программа принимает
на вход целое число, возвращает ЧИСЛО являющееся зеркальным отражением исходного. Нечего, кроме, цикла и арифметических
операторов применять нельзя.
"""
number = int(input('Введите целое число: '))
rev_number = 0
while number != 0:
digit = number % 10
number //= 10
rev_number *= 10
rev_number += digit
print('Перевернутое число: {}.'.format(rev_number))
| false
|
30ab4ea8670f90b416f0b6fc86d33ecfa1490fb7
|
KonstBelyi/Python_hw
|
/lesson_6/task_6.py
| 2,631
| 4.125
| 4
|
"""
Петя перешёл в другую школу. На уроке физкультуры ему понадобилось определить своё место в строю.
Помогите ему это сделать.
Программа получает на вход невозрастающую последовательность натуральных чисел, означающих рост каждого
человека в строю. После этого вводится число X – рост Пети. Все числа во входных данных натуральные и не превышают 200.
Выведите номер, под которым Петя должен встать в строй. Если в строю есть люди с одинаковым ростом, таким же,
как у Пети, то он должен встать после них.
( 1. Здесь понадобится сортировка.
Вот пример:
a = [5, 8, 2, 8, 4, 7, 0, 3, 1, 6, 9]
print(a)
# [5, 8, 2, 8, 4, 7, 0, 3, 1, 6, 9]
a.sort(reverse=True)
print(a)
# [9, 8, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Параметр reverse=True отсортирует список в порядке убывания элементов.
2. Так же, понадобится list comprehension который позволит создать список случайных значений)
"""
from random import randint
num_students = int(input('Введите количесвто учеников в классе (до прихода Пети): '))
lst = [randint(150, 201) for _ in range(num_students)]
print('Рост учеников в классе (до прихода Пети): {}'.format(lst))
rost_Peti = int(input('Введите рост Пети: '))
print('Рост Пети: {} cм.'.format(rost_Peti))
lst.append(rost_Peti)
print('Рост учеников в классе (с Петей): {}'.format(lst))
lst.sort(reverse=True)
print('Рост учеников по убыванию: {}'.format(lst))
print('Количество учеников с таким же ростом, как у Пети:', lst.count(rost_Peti))
id1_rostPeti = lst.index(rost_Peti) # ищем первое вхождение с таким же ростом, как у Пети
# print(id1_rostPeti)
idx_Peti = lst.index(rost_Peti) + lst.count(rost_Peti) # к первому вхождению прибавляем общее количество учеников с таким же ростом
print('Место Пети в строю (по росту): {} место.'.format(idx_Peti))
| false
|
27495ff095e063331f70111ca9a9055a3b4d1c4a
|
my-sundry/FinanceTools
|
/sh_hk_hq_financial_report/unzip.py
| 668
| 4.125
| 4
|
#zip文件解压缩并删除原压缩文件
#巨潮下载三表和行情为压缩文件
import zipfile
import os
def un_zip(file_name):
"""unzip zip file"""
zip_file = zipfile.ZipFile(file_name)
if os.path.isdir(file_name[:-4]):
pass
else:
os.mkdir(file_name[:-4])
for names in zip_file.namelist():
zip_file.extract(names, file_name[:-4])
zip_file.close()
def unzip_all():
files=os.listdir('data/')
zip_files=[i for i in files if i.endswith('.zip')]
for i in zip_files:
un_zip('data/'+i)
os.remove('data/'+i)
if __name__ == '__main__':
unzip_all()
| false
|
4a0ba4aa999fe8dc26cbe25ca313f61e6fd8d9c4
|
gryzzia/Python-tasks
|
/The sum of the values of two elements.py
| 494
| 4.125
| 4
|
# Генерируется 3 случайных значения, если сумма значений двух элементов будет равна 3-му вывести ДА
# 3 random values are generated if the sum of the values of two elements is equal to the 3rd; print YES
from random import randint
a=[randint(1,10) for i in range(3)]
if a[0]==a[1]+a[2]:
print ('yes')
if a[1]==a[0]+a[2]:
print ('yes')
if a[2]==a[1]+a[0]:
print ('yes')
print (a)
| false
|
9ecf2afb58c4c9a938b4d8a96f75a4858d5138bc
|
xinmu01/python-code-base
|
/Advanced_Topic/Iterator_example.py
| 1,113
| 4.28125
| 4
|
class Reverse:
"""Iterator for looping over a sequence backwards."""
def __init__(self, data):
self.data = data
self.index = len(data)
# After define the __iter__, the iter() and for in loop can be used.
def __iter__(self):
return self
#As long as define __next__, the next() can be used.
def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
def reset(self):
self.index = len(self.data)
a = Reverse("I am Xin")
print (next(a))
for i in a:
print (i)
print()
a.reset()
for i in a:
print(i)
print()
a.reset()
b = iter(a)
print (next(b))
for i in b:
print(i)
print()
##Convert List to Iterator
test_list = [1,2,3]
test_list_iter = iter(test_list)
print(next(test_list_iter))
print(next(test_list_iter))
print(next(test_list_iter))
##Generator Example
def generator_example(a):
for i in a:
yield i
generator_example = generator_example([1,2,3])
print(next(generator_example))
for i in generator_example:
print (i)
| true
|
e5ea2965be23486032a8d31ee2bfc01cd8d59126
|
cryptoaimdy/Python-strings
|
/src/string_indexing_and_slicing_and_length.py
| 1,180
| 4.4375
| 4
|
#!/usr/bin/env python
# coding: utf-8
# In[35]:
# string indexing and slicing
s = "crypto aimdy"
# printing a character in string using positive index number
print(s[5])
# printing a character in string using negative index number
print(s[-5])
# In[28]:
##String Slicing
#printing string upto 5 characters
print(s[:5])
# In[29]:
#prints string after first leaving first 5 char
print(s[5:])
# In[30]:
#prints char at position 4 all the way upto char at position 5 but leaving the character 5.
print(s[4:5])
# In[31]:
#prints all the char from opposite side after leaving first eight char from backwards.
print(s[:-8])
# In[32]:
#pritns cahr from backward at index 2.
print(s[-2])
# In[33]:
#prints the every character at the gap of 5 characters after priting each character.
print(s[::5])
# In[34]:
#prints the every character from backwards at the gap of 3 characters after priting each character.
print(s[::-3])
# In[37]:
# string length
#printing string length
print(len(s))
# In[43]:
#Instead of using a variable, we can also pass a string right into the len() method:
print(len("Let's print the length of this string."))
# In[ ]:
| true
|
310c2e0bbde417cbf69ee2768a833c6c3cbdb51a
|
thonathan/Ch.04_Conditionals
|
/4.2_Grading_2.0.py
| 787
| 4.25
| 4
|
'''
GRADING 2.0
-------------------
Copy your Grading 1.0 program and modify it to also print out the letter grade depending on the numerical grade.
If they fail, tell them to "Transfer to Johnston!"
'''
grade= int(input("Please enter your grade: "))
exam= int(input("Please enter your exam score: "))
worth= int(input("Please enter your exam worth: "))
examworth=worth/100
gradeworth=(100-worth)/100
ave=grade*(gradeworth)+exam*examworth
print()
print("Here is your final grade: ",ave,)
if ave>90:
print("Here is your letter grade: A!")
elif ave>80:
print("Here is your letter grade: B!")
elif ave>70:
print("Here is your letter grade C")
elif ave>60:
print("Here is your letter grade D")
else:
print("Here is your letter grade F")
print("Transfer to Johnston!")
| true
|
370cfa9c4c18e0345cd14d49f6bc5762886d3b84
|
SHajjat/python
|
/binFunctionAndComplex.py
| 359
| 4.1875
| 4
|
# there is another data type called complex
complex =10 # its usually used in complicated equations its like imaginary number
# bin() changes to binary numbers
print(bin(10000)) # this will print 0b10011100010000
print(int("0b10011100010000",2)) # im telling it i have number to the base of 2 i wanna change to int
# this will return it to integer 10000
| true
|
9e3d56ac56705389fedaae15d3598f07fbe20996
|
axelsot0/Repositorio-1
|
/PracticaII-2.py
| 1,713
| 4.15625
| 4
|
print("-----------------------------------------------------------------")
print("Ejecicio 2")
def opciones():
print(" 1- Convertir grados a Celsius a Fahrenheit 2- Convertir dólar a pesos 3- Convertir metros a pies 4- Salir : ")
opciones ()
accion = input("Elija una opción:")
accion = int(accion)
while accion != 4:
if accion == 1:
print("Convertir grados Celsius a Fahrenheit")
Cantidad_celcius = input("Ingrese Cantidad de grados celsius: ")
Cantidad_celcius = float(Cantidad_celcius)
print("Grados Fahrenheit:")
print(Cantidad_celcius * 9 / 5 +32)
opciones()
accion = input("Ingrese una opción: ")
accion = int(accion)
elif accion == 2:
print("Convertir dolar a pesos")
cantidad_dollar = input("Ingrese cantidad de dolares")
cantidad_dollar = float(cantidad_dollar)
print("Pesos:")
print(cantidad_dollar * 58.52)
opciones()
accion = input("Ingrese una opción: ")
accion = int(accion)
elif accion == 3:
print("Convertir metros a pies")
cantidad_metros = input("Ingrese cantidad de metros: ")
cantidad_metros = float(cantidad_metros)
print("Pies:")
print(cantidad_metros * 3.28)
opciones()
accion = input("Ingrese una opción: ")
accion = int(accion)
elif accion >= 4:
print("Error")
print("Acción no valida")
opciones()
accion = input("Ingrese una opción: ")
accion = int(accion)
if accion == 4:
print("Gracias por utilizar nuestros servicios")
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.