blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
825f354948e7622b2fef893dac8f234ca2018bde | dapazjunior/ifpi-ads-algoritmos2020 | /Iteracoes/Fabio_03/f3_q02_numeros_pares_1_a_n.py | 194 | 3.9375 | 4 | def main():
contador = 1
n = int(input('Digite um número: '))
while contador <= n:
if contador % 2 == 0:
print(contador)
contador += 1
main() |
6e88568a43230f2ce90faf95c5d5a24d85efa12d | dapazjunior/ifpi-ads-algoritmos2020 | /Iteracoes/Fabio_03_for/f3_q03_pa.py | 434 | 3.703125 | 4 | def main():
termo_a0 = int(input('Digite o valor de A0 da PA: '))
limite = int(input('Digite o valor limite da PA: '))
razao = int(input('Digite o valor da razão da PA: '))
cont = 0
if razao == 0:
print(termo_a0)
else:
for _ in range(0, limite + 1):
termo = term... |
559d622908ae527112a98a2c22fd172fdaeba07c | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_01/Fabio01_Parte01/f1_p1_q15_area_triangulo.py | 240 | 3.828125 | 4 | # Entrada
base = float(input('Digite a medida da base do triângulo: '))
altura = float(input('Digite a medida da altura do triângulo: '))
# Processamento
area = (base * altura) / 2
# Saida
print(f'A área do triângulo é {area:.2f}.')
|
2ab6471b8ea823820f93f86335d70c4d8a333449 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_01/Fabio01_Parte02/f1_p2_q12_soma_algarismos.py | 378 | 3.71875 | 4 | # Entrada
numero = int(input('Digite um numero inteiro de 4 algarismos: '))
# Processamento
unidade_milhar = numero // 1000
centena = (numero % 1000) // 100
dezena = ((numero % 1000) % 100) // 10
unidade = ((numero % 1000) % 100) % 10
soma_algarismos = unidade_milhar + centena + dezena + unidade
# Saída
print(f'A so... |
cb411d70e50b20958f8bc0611054632631039250 | dapazjunior/ifpi-ads-algoritmos2020 | /URI/q1079_medias_ponderadas.py | 217 | 3.578125 | 4 | def main():
qtd = int(input())
for _ in range(qtd):
n1, n2, n3 = map(float, input().split())
media_ponderada = (n1*2 + n2*3 + n3*5) / 10
print('{:.1f}'.format(media_ponderada))
main() |
83871c85a545012e93680ba23a0e61caf02e40a4 | dapazjunior/ifpi-ads-algoritmos2020 | /Iteracoes/Fabio_03/f3_q14_maior_quadrado.py | 205 | 4.125 | 4 | def main():
n = int(input('Digite um número: '))
num = 0
while (num ** 2) <= n:
maior_quadrado = num ** 2
num += 1
print(f'Maior quadrado: ', maior_quadrado)
main() |
054571c626c59191f1d7c9314641a26752a7c4fe | dapazjunior/ifpi-ads-algoritmos2020 | /Pense_em_Python/capitulo_4/q_4_3_4a copy.py | 442 | 3.6875 | 4 | import turtle
from math import pi
t = turtle.Turtle()
def arc(t, r, angulo):
comprimento = r * pi * 2 * angulo / 360
n = int(comprimento / 3) + 1
comprimento_arco = comprimento / n
angulo_arco = angulo / n
for i in range(n):
t.fd(comprimento_arco)
t.lt(angulo)
def polyline(t, n, l... |
7152a15fd9569b8158fda69f3f9f505b370b114c | dapazjunior/ifpi-ads-algoritmos2020 | /URI/q1222_concurso_de_contos.py | 988 | 3.65625 | 4 | def main():
while True:
try:
num_palavras, max_linhas, max_caracteres = input().split(' ')
num_palavras = int(num_palavras)
max_linhas = int(max_linhas)
max_caracteres = int(max_caracteres)
conto = input()
... |
0fc5a3f740626c85f2abdec259c55a6be35fe911 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_02/Fabio02_Parte_a/f2_a_q26_triangulo_retangulo.py | 1,161 | 4.09375 | 4 | def main():
lado1 = int(input('Digite a medida do primeiro lado: '))
lado2 = int(input('Digite a medida do segundo lado: '))
lado3 = int(input('Digite a medida do terceiro lado: '))
eh_triangulo = verificar_se_triangulo(lado1, lado2, lado3)
if eh_triangulo == True:
verificar_se_ret... |
f25925152cdbad7af12da0af26709fa1ea095c55 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_02/Fabio02_Parte_b/f2_b_q13_entrevista.py | 927 | 3.796875 | 4 | def main():
print('Responda as perguntas com S(sim) e N(Não).')
a = input('Telefonou para a vítima?\n>>> ').lower()
b = input('Esteve no local do crime?\n>>> ').lower()
c = input('Mora perto da vítima?\n>>> ').lower()
d = input('Devia para a vítima?\n>>> ').lower()
e = input('Já trabalhou com a ... |
18e04ca4492d858bb47861a13ddc29a30f01f4c8 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_02/Fabio02_Parte_a/f2_a_q23_data_recente.py | 3,676 | 3.84375 | 4 | def main():
dia1 = int(input('Digite a primeira data(dia/mês/ano)\nDia: '))
mes1 = int(input('Mês: '))
ano1 = int(input('Ano: '))
dia2 = int(input('Digite a segunda data(dia/mês/ano)\nDia: '))
mes2 = int(input('Mês: '))
ano2 = int(input('Ano: '))
dia3 = int(input('Digite a terceira... |
e7344ca9236a968e7d7992480e19c6da427b57fe | dapazjunior/ifpi-ads-algoritmos2020 | /URI/q1011_esfera.py | 142 | 3.75 | 4 | def main():
raio = float(input())
pi = 3.14159
volume = 4/3 * pi * raio**3
print('VOLUME = {:.3f}'.format(volume))
main()
|
8c2779ac853ba16813b56efae6eb4085fc113799 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_02/Fabio02_Parte_a/f2_a_q28_retangulo.py | 610 | 4 | 4 | def main():
x1 = float(input('Primeiro vértice:\nx = '))
y1 = float(input('y = '))
# Para que dois pontos definam um retângulo eles precisam ser opostos!
x2 = float(input('\nVértie oposto:\nx = '))
y2 = float(input('y = '))
area = calcular_area(x1, x2, y1, y2)
print(f'A area ... |
ea96f33228fa12b97c7d751340b259021e85ced2 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_02/Fabio02_Parte_a/f2_a_q12_par_impar.py | 261 | 3.90625 | 4 | def main():
num = int(input('Digite um número inteiro: '))
verificar_se_par(num)
def verificar_se_par(num):
if (num % 2 == 0):
print(f'O número {num} é par.')
else:
print(f'O número {num} é ímpar.')
main()
|
57454e23133daafcd2ab2e84f87613ba4757b041 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_01/Fabio01_Parte01/f1_p1_q21_temperatura_celcius.py | 226 | 4.03125 | 4 | # Entrada
temperatura_fahrenheit = float(input('Digite a temperatura em °F: '))
# Processamento
temperatura_celcius = (5 * temperatura_fahrenheit - 160) / 9
# Saida
print(f'A temperatura é {temperatura_celcius:.2f} °C.')
|
3ad07d5be1a709248743cd82ada9ba6c84f68a5b | dapazjunior/ifpi-ads-algoritmos2020 | /Iteracoes/Fabio_03_for/f3_q02_numeros_pares_1_a_n.py | 181 | 3.859375 | 4 | def main():
n = int(input('Digite um número: '))
lista = []
for i in range(1 , n+1):
if i % 2 == 0:
lista.append(i)
print(lista)
main()
|
fd836b395d5896a59a4f3075522182ea97c62960 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_01/Fabio01_Parte02/f1_p2_q19_distancia_pontos.py | 369 | 4.03125 | 4 | # Entrada
x1 = int(input('Digite o "x" do primeiro ponto: '))
y1 = int(input('Digite o "y" do primeiro ponto: '))
x2 = int(input('Digite o "x" do segundo ponto: '))
y2 = int(input('Digite o "y" do segundo ponto: '))
# Processamento
distancia = ((x2 - x1)**2 + (y2 - y1)**2) ** (1/2)
# Saída
print(f'A distância entre (... |
104a9b9ff967b133747ff9273f17ae42ae8825d4 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_02/Fabio02_Parte_a/f2_a_q03_maior_de_3.py | 510 | 4.03125 | 4 | def main():
num1 = int(input('Digite o primeiro número: '))
num2 = int(input('Digite o segundo número: '))
num3 = int(input('Digite o terceiro número: '))
maior = verificar_maior(num1, num2, num3)
print(f'O maior número digitado é {maior}.')
def verificar_maior(num1, num2, num3):
... |
e9856e2e86c5dca29ae8c367c26e750cfce848d3 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_01/Fabio01_Parte02/f1_p2_q23_prestacoes.py | 255 | 4 | 4 | # Entrada
valor = float(input('Qual o valor do produto? '))
# Processamento
prestacao = valor // 3
entrada = (valor // 3) + (valor % 3)
# Saída
print(f'O pagamento será uma entrada de R$ {entrada:.2f} e mais duas prestações de R$ {prestacao:.2f}.')
|
ad59ffd6148b2b50ed5b1ea7537130a22dc341a0 | dapazjunior/ifpi-ads-algoritmos2020 | /Iteracoes/Fabio_04/f4_q07_num_igual.py | 232 | 3.875 | 4 | def main():
n = int(input('Digite um número: '))
cont_n = 0
while cont_n == 0:
c = int(input('Digite um número: '))
if c == n:
cont_n += 1
print('Valor encontrado!')
main()
|
d3869402b9f2309f6cc68cd1b56885d69452df4f | dapazjunior/ifpi-ads-algoritmos2020 | /Strings/uri_1024_criptografia.py | 1,605 | 3.828125 | 4 | def main():
num = int(input('Quantas linhas criptografadas?\n>>> '))
for i in range(num):
strg_criptografar = input(f'\nLinha {i + 1}: ')
nova_string = criptografar(strg_criptografar)
print(f'Linha {i + 1} encriptada:' + nova_string)
def criptografar(strg):
# Passo 1:... |
873f342dc8e6e9b8b2b929f87d8f826917e0775d | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_01/Fabio01_Parte01/f1_p1_q14_media_notas.py | 491 | 3.796875 | 4 | # Entrada
nota_1 = float(input('Digite a primeira nota: '))
peso_1 = float(input('Digite o peso da primeira nota: '))
nota_2 = float(input('Digite a segunda nota: '))
peso_2 = float(input('Digite o peso da segunda nota: '))
nota_3 = float(input('Digite a terceira nota: '))
peso_3 = float(input('Digite o peso da terceir... |
f22bd9a98620e1b6a72d4132483ee9435dd309f0 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_06/f6_q07_conjugacao.py | 712 | 4.03125 | 4 | def main():
verbo = input('Digite um verbo regular de segunda conjugação:\n> ')
conjugar(verbo)
def conjugar(verbo):
verbo = verbo.lower()
index_fim = len(verbo) - 2
if verbo[index_fim:index_fim + 2] == 'er':
print(f'Verbo: "{verbo}"')
radical = verbo[0:index_fim]
prin... |
a03e7487939f546f7f379af38146eb05c200589c | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_02/Fabio02_Parte_b/f2_b_q08_contracheque.py | 1,588 | 3.96875 | 4 | def main():
valor_hora = float(input('Digite o valor recebido por hora trabalhada:\n>>R$ '))
horas_trab = int(input('Digite a quantidade de horas trabalhadas: \n>> '))
salario_bruto = horas_trab * valor_hora
irpf = calcular_irpf(salario_bruto)
sindicato = calcular_sindicato(salario_bruto)
... |
d6ca3240531bbb0265a54e9f7e994e77488002c6 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_04/f4_q29_investimento.py | 713 | 3.71875 | 4 | def main():
inv_mensal = float(input('Investimento mensal:\n>>> R$ '))
taxa_juros = float(input('Taxa de juros mensal (% mensal)\n>>> '))
capital_acumulado = 0
mes = 0
while True:
capital_acumulado = (capital_acumulado) * (1 + taxa_juros / 100) + inv_mensal
mes += 1
if ... |
4920e55429d0d448257bb3e1a7d0953b53df0d36 | dvahlin/Python | /FLASK/pand_csv_query.py | 285 | 3.53125 | 4 | #!/usr/bin/python3
import sqlite3
import pandas as pd
conn = sqlite3.connect('/PATH/TO/TestDB.db')
c = conn.cursor()
# Read sqlite query
df = pd.read_sql_query("SELECT * from PIZZA", conn)
# Verify that result of SQL query is stored in the dataframe
print(df.head(1))
conn.close()
|
cda2821e139c91ef229ddb849f51c4739bb6181b | MattCairns/Asteroids | /ship.py | 2,851 | 3.65625 | 4 | import pygame
from pygame.locals import *
import math
class Ship(pygame.sprite.Sprite):
"""All of the logic for the players ship is contained
within this class"""
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('Assets/starship.png').conver... |
c7a0f1c8ffb73953f465fd09d97e892a8caa475e | fernandavincenzo/exercicios_python | /26-50/034_AumentoProp.py | 333 | 3.671875 | 4 | s = float(input('Digite o seu salário: R$'))
if s>1250:
a = s*10/100
nv = s+a
print('O valor de seu aumento é de R${:.2f}, e o seu novo salário é de R${:.2f}.'.format(a,nv))
else:
a = s*15/100
nv = s+a
print('O valor de seu aumento é de R${:.2f}, e o seu novo salário é de R${:.2f}.'.format(a,nv)... |
8c38eecd3ac2bcf682da96b97862683f1779f6ce | fernandavincenzo/exercicios_python | /51-75/053_Palindromo.py | 404 | 3.859375 | 4 | frase = str(input('Digite uma frase: ')).strip().upper()
palavras = frase.split()
juncao = ''.join(palavras)
inverso = juncao[::-1]
#for c in range(len(juncao)-1, -1, -1):
# inverso += juncao[c]
if inverso == juncao:
print('{} e {} são iguais, portanto, palíndromos.'.format(juncao, inverso))
else:
print('{} ... |
3bf43ba3c6e55ad68c5e989ed9dd1e2fbb13ee0a | fernandavincenzo/exercicios_python | /0-25/005_AntecessorSucessor.py | 147 | 3.859375 | 4 | n1 = int(input('Por favor, insira um número inteiro: '))
print('O antecessor desse número é {}, e o seu sucessor é {}'.format((n1-1), (n1+1)))
|
03f5eefaa3c7c247c16685aa5d1e3b8df4da363b | fernandavincenzo/exercicios_python | /76-100/092.py | 557 | 3.546875 | 4 | from datetime import datetime
dados = dict()
dados['nome'] = input('Nome: ')
nasc = (int(input('Ano de Nascimento: ')))
dados['idade'] = datetime.now().year - nasc
dados['ctps'] = int(input('Carteira de trabalho (0 se não tem): '))
if dados['ctps'] == 0:
print('Muito obrigada por utilizar o programa!')
else:
d... |
30dce02579ea310af1aee4448ec56ae3f94883db | fernandavincenzo/exercicios_python | /76-100/082_Listasextras.py | 486 | 3.734375 | 4 | lista = []
impares = []
pares = []
while True:
lista.append(int(input('Digite um valor para adicionar na lista: ')))
stop = input('Deseja parar o cadastro de números? [S/N] ').upper()[0]
if stop == 'S':
break
for c, v in enumerate(lista):
if v % 2 == 0:
pares.append(v)
else:
... |
11a835fe560f6abf863a8de12e2f5af90c52f99c | fernandavincenzo/exercicios_python | /51-75/068_JogarParImpar.py | 964 | 3.578125 | 4 | from random import randint
c = 0
while True:
pi = str(input('Escolha: Par ou Impar? [P/I] ')).strip().upper()[0]
while pi not in 'PI':
pi = str(input('Escolha: Par ou Impar? [P/I] ')).strip().upper()[0]
jogador = int(input('Ok, escolha sua jogada (de 0 à 5): '))
pc = randint(0, 5)
soma = pc+... |
fbd7e765f439058e799733a1a5f3828cf1247b95 | fernandavincenzo/exercicios_python | /0-25/025_NomeSilva.py | 129 | 3.921875 | 4 | nome = str(input('Digite o seu nome completo: ')).upper()
print('Há a palavra "Silva" no seu nome? {}'.format('SILVA' in nome))
|
be8d489f05cfa6a3d17e4f51b82a91c688560878 | fernandavincenzo/exercicios_python | /26-50/043_IMC.py | 602 | 3.765625 | 4 | print('CONSULTA DE IMC')
alt = float(input('Digite aqui sua altura em metros: '))
peso = float(input('Agora digite aqui seu peso em kilogramas: '))
imc = peso/(alt**2)
print('O seu Índice de Massa Corporal é de {:.2f}'.format(imc))
if imc<18.5:
print('Tenha cuidado! Você está abaixo do peso ideal para sua altura.')... |
c51d50bca728bb76d6e2410f9a3c67c2a58b3984 | fernandavincenzo/exercicios_python | /26-50/032_Bissexto.py | 355 | 3.921875 | 4 | from datetime import date
ano = int(input('Digite o ano desejado para saber se ele é bissexto, se quiser saber o ano atual, digite 0: '))
if ano == 0:
ano = date.today().year
if ano%4 == 0 and ano%100 != 0 or ano%400 == 0:
print('O ano {} ano é um ano bissexto!'.format(ano))
else:
print('O ano {} não é um a... |
e6489231a3c12f9784cca767bdea70e55227120c | fernandavincenzo/exercicios_python | /76-100/099.py | 202 | 3.671875 | 4 | def maior(*num):
if len(num) == 0:
print(f'Não há nenhum número passado')
else:
print(f'O maior número de {num} é {max(num)}')
maior(3,6,9,5,2,4,99)
maior(4, 7, 0)
maior() |
85d861e60ac92153d9d6a853c4d1d64c1cedc0c0 | fernandavincenzo/exercicios_python | /26-50/039_Alistamento.py | 814 | 4.03125 | 4 | from datetime import date
genero = int(input('Sobre seu genero: digite 0 para masculino ou 1 para feminino: '))
if genero == 0:
ano = int(input('Insira aqui o seu ano de nascimento: '))
anoatual = date.today().year
idade = anoatual-ano
print('Em {} você estará completando {} anos.'.format(anoatual, idad... |
d3af2121d46586e624a62eb28f6caa959c7fa6ed | fernandavincenzo/exercicios_python | /51-75/072_NumExtenso.py | 528 | 4.0625 | 4 | numeros = 'zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', \
'treze', 'catorze', 'quinze', 'dezesseis', 'dezesste', 'dezoito', 'dezenove', 'vinte'
play = 'S'
while play == 'S':
while True:
num = int(input('Digite um número de 0 à 20: '))
... |
278362806721b24ae0613bc5d307913cec969390 | acasasaez/Warm-up | /ejercicio5.py | 983 | 3.9375 | 4 | #Queremos crear un progrma que nos permita comer helados hasta saciar nuestra hambre o hasta quedarnos sin dinero:
#Partimos de:
#Tenemos 2000 euros inicialmente.
#El precio del helado es 100, pero se incrementa un 20% después de cada compra
#Incialmente estamos tan saciados como nuestra edad nos lo indica,... |
48bfaeb0d119e2cc366306922c24533545e389b9 | sokuro/PythonBFH | /01_Fundamentals/Lambda/04_QuadraticFunction.py | 354 | 3.796875 | 4 | """
Quadratic Function f(x) = ax^2 + bx + c)
"""
def build_quadratic_function(a, b, c):
return lambda x: a*x**2 + b*x + c
def main():
f = build_quadratic_function(1, 2, 3)
# elegant way
g = build_quadratic_function(1, 2, 3)(1)
print(f(1))
print(g()) # ERROR: 'int' Object is not... |
537a10b2964afb6cbecdce161536769f24eb410f | sokuro/PythonBFH | /03_Exercises/Stings/06_SplitStringDelimiter.py | 278 | 4.28125 | 4 | """
split a string on the last occurrence of the delimiter
"""
str_input = input('Enter a String: ')
# create a list from the string
temp_list = list(str_input)
int_input = int(input('Enter a Number of split Characters: '))
print(str(temp_list).rsplit(',', int_input))
|
aca362deed3cc2c968cc6ac423f4598343bf0d7c | sokuro/PythonBFH | /02_LanguageElements/Functions/NonlocalVariable.py | 453 | 3.859375 | 4 | """
Using nonlocal to bind the Variable
"""
def outer_function(x): # x = 7
y = x + 1 # y = 8
# nested function
def inner_function(z): # z = y = 8
nonlocal y # bind Variable from the outer Scope
y += 1 # y + 1 = 8 + 1 = 9
return x + y +... |
c9e9706b130e8dfb272523b8a575e0d1100dcaa3 | sokuro/PythonBFH | /01_Fundamentals/Class/04_User_Method_Age.py | 867 | 4.03125 | 4 | """
Extending with Properties
Extract the Properties
Method: Age
"""
class User:
def __init__(self, full_name, birthday):
# attach Properties to the Object
self.name = full_name
self.birthday = birthday
# Extract first and last Names
name_pieces = full_name... |
862b6cc33e0a0396c025b42c02b2092832ffaa43 | sokuro/PythonBFH | /01_Fundamentals/Strings/Exercises/06_CopyStringChars.py | 467 | 4.03125 | 4 | """
get the n (non-negative integer) copies of the first 2 characters of a given string. Return the n copies of the whole string if the length is less than 2
"""
def copy_chars(str, times):
str_length = 2
if len(str) <= str_length:
str_length = len(str)
substr = str[:str_length]
result... |
3fc66aa0b3bde5ee6a7d3bafdeb6bab46f0c926e | sokuro/PythonBFH | /01_Fundamentals/Strings/Exercises/04_IsString.py | 344 | 4.40625 | 4 | """
get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchanged.
"""
def IsString(str):
if len(str) >= 2 and str[:2] == 'Is':
return str
else:
return 'Is' + str
print(IsString("Testing"))
print... |
c8c32cfec48b1307d4b5156bbe8881d0303063d0 | sokuro/PythonBFH | /01_Fundamentals/Lists/Lists.py | 477 | 4.125 | 4 | """
* Lists are MUTABLE ordered sequence of items
* Lists may be of different type
* [] brackets
* Expressions separated by a comma
"""
list1 = [1, 2.14, 'test']
list2 = [42]
list3 = [] # empty list
list4 = list() # empty list
# ERROR
# list5 = list(1, 2, 3)
# Solving
list6 = list((1, 2, 3)) # List out o... |
720758a8ac4078f6a2a94e9b0bb73ac2283e79a6 | sokuro/PythonBFH | /02_LanguageElements/Functions/Exercises/Strings/RemoveDuplicatesList.py | 315 | 4.0625 | 4 | """
Function with a List Input, removing Duplicates
use List
"""
def remove_duplicates(list):
value_list = []
for num in list:
if num not in value_list:
value_list.append(num)
return value_list
def main():
print(remove_duplicates([1, 2, 2, 4, 3, 3, 2]))
main()
|
d8fee1257ff3444aef0edfd461dab357f832dd59 | sokuro/PythonBFH | /01_Fundamentals/Map/03_Map_Multiple_Iterables.py | 269 | 3.84375 | 4 | """
Generated Iterator terminates when the End of the Shortest Input Iterator runs out of Elements
"""
l = [1, 2, 3, 4, 5, 6]
t = (True, False, False, True)
s = 'Hello World'
result = list(map(lambda n, b, c: '{}-{}-{}'.format(n, b, c), l, t, s))
print(result)
|
9d48a93d51196f49d99e737b628b0fbcae4fcc91 | sokuro/PythonBFH | /01_Fundamentals/Functions/ArgsKwargs.py | 674 | 4.03125 | 4 | """
* If both the *args & **kwargs are present, **kwargs MUST come after!
"""
def temp(*args, **kwargs):
for x in args:
print(x)
for k, v in kwargs.items():
print(f'{k} = {v}')
temp()
temp(a=42) # >> a = 42
temp(1, a=10, b=11) # >> 1; a = 10; b = 11
# adding a ... |
1f059cf2a0d88dc090998b2ad3011baf1dede251 | sokuro/PythonBFH | /01_Fundamentals/Functions/DefaultValues.py | 188 | 4 | 4 | """
Parameters with default Values
Default Values can be mutable
"""
def f(x, y=None):
if y is None:
y = []
y.append(x)
return y
print(f(1))
print(f(2))
|
226599924ff604b05aa95225e59baa2d06a8bffe | sokuro/PythonBFH | /01_Fundamentals/Decorators/04_Decorator_Annotation_WithArguments.py | 1,236 | 3.875 | 4 | """
Decorator: Function that takes another Function as Argument
Extend the Wrapper with an extra Statement
Use Annotation for both Functions without Error: *args, **kwargs
Extend with Arguments
"""
# Decorator
def decorator_function(original_function):
# use *args, **kwargs to prevent Error, t... |
286f659c944c2744440dcdf9b3ffba55d4e4b1c1 | sokuro/PythonBFH | /01_Fundamentals/Sort/01_Sort.py | 414 | 4.21875 | 4 | """
sort(...)
L.sort(key=None, reverse=False)
"""
# List of Names
names = ["Karol", "Rebeca", "Daniel", "Michael", "Patrik", "Richard"]
# sort alphabetically
names.sort()
print(names)
# sort reversed
names.sort(reverse=True)
print(names)
# Tuple of Names
names_tuple = ("Karol", "Rebeca", "Daniel", ... |
15fc621829998dcf0bf9dbd0f94a46382a4cf0cd | sokuro/PythonBFH | /Exercises_BFH/Exercise01/mandelbrot.py | 1,921 | 3.71875 | 4 | """Mandelbrot fractale visualization."""
import time
from PIL import Image
def mandelbrot_set_iterations(c_point):
"""Determine whether the point c belongs to the Mandebrot set using
the orbit algorithm."""
max_iter = 255
iter_count = 0
z = complex(0, 0)
while (abs(z) < 2) and (iter_count ... |
f0bb44b041ff0f49f8ad546671de3634a808ff05 | sokuro/PythonBFH | /03_Exercises/Stings/01_StartWithCharacter.py | 182 | 4.28125 | 4 | """
check whether a string starts with specified characters
"""
str_input = input('Enter a string: ')
char_input = input('Enter a Character: ')
print(char_input in str_input)
|
75a6727a0bb65a07bbd948609d076d70d1a345e1 | igorgabrig/AprendizadoPython---curso-em-video | /Mundo03/desafios/Desafios Funcao/desafio97.py | 335 | 3.609375 | 4 | # Faça um programa que tenha uma função chamada escreva(),
# que receba um texto qualquer como parâmetro e mostre uma mensagem com tamanho adaptável.
def mensagem(msg):
tam = len(msg) + 6
print(f'~'*tam)
print(f' {msg}')
print(f'~'*tam)
mensagem('Olá, Mundo!')
mensagem('Igor Gabrig Barboza')
mensag... |
d3ae916761cd41faac85c8d526afb7da11c3d3b8 | igorgabrig/AprendizadoPython---curso-em-video | /Mundo03/desafios/Desafios Funcao/desafio100.py | 669 | 4.09375 | 4 | # Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar().
# A primeira função vai sortear 5 números e vai colocá-los dentro da lista e a segunda
# função vai mostrar a soma entre todos os valores pares sorteados pela função anterior.
from random import randint
def sorteia(... |
f385b19544051242da85344b7ba5b0406378fc43 | igorgabrig/AprendizadoPython---curso-em-video | /Mundo03/desafios/Desafios Modulos e Pacotes/ex107/main.py | 489 | 3.84375 | 4 | # Crie um módulo chamado moeda.py que tenha as funções incorporadas
# aumentar(), diminuir(), dobro() e metade().
# Faça também um programa que importe esse módulo e use algumas dessas funções.
import moeda
valor = float(input('Digite um valor: '))
print(f'A metade de {valor} é {moeda.metade(valor)}')
print(f'O d... |
4e8ad1365031a9051b83c439396cea43aa5b6d3a | igorgabrig/AprendizadoPython---curso-em-video | /Mundo03/desafios/Desafios Funcao/desafio104.py | 522 | 4.1875 | 4 | # Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante
# 'a função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico.
# Ex: n = leiaInt('Digite um n: ')
def leiaInt(msg):
while True:
num = str(input(msg))
if num.isnumeric():
... |
89ba2d63d208bcfa68515688fd7cd64b5d76102e | igorgabrig/AprendizadoPython---curso-em-video | /Mundo03/lista1.py | 640 | 3.859375 | 4 | vet = [] #lista vazia ou vet = list()
for i in range(0, 8):
# Adiciona elemento ao final da lista
vet.append(int(input('Digite um numero: ')))
vet.sort() # Ordena a lista em ordem crescente
vet.sort(reverse=True) # Ordena a lista em ordem decrescente
# Adiciona elemento a lista, tendo que passar como par... |
3260a76d86453e4b5b299e48b1f4eeeedc176ba4 | krishnanandSrivastava/Hackerrank_question | /Python/String Validators.py | 888 | 3.828125 | 4 | if __name__ == '__main__':
s = input()
flag=False
for sb in s:
if sb.isalnum():
print("True")
flag=True
break
if flag==False:
print("False")
flag=False
for sb in s:
if sb.isalpha():
print("True")
flag=True
... |
803ded0cda1f6fcaf3f5736871a078186e4b2384 | krishnanandSrivastava/Hackerrank_question | /Python/SetdifferenceOperation.py | 164 | 3.578125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
_=input()
e=set(input().split())
_=input()
f=set(input().split())
print(len(e.difference(f)))
|
0f25121323a78be915a9db6befd0e857a8325560 | varshithajonnalagadda/spartans | /power of 2.py | 121 | 4.125 | 4 | n=int(input("enter num"))
if((n&(n-1))==0):
print("n is a power of 2")
else:
print("n is not a power of 2")
|
b5049f3c74d105171c7d3a0634c9e4697139531c | viniciusrogerio/lista_selecao | /7.py | 656 | 4.0625 | 4 | def triangulo(x,y,z):
x=float(x)
y=float(y)
z=float(z)
if x+y > z and y+z > x and x+z > y:
if x == y:
if y == z:
print('É equilátero!')
else:
print('É isósceles!')
elif x == z:
if z == y:
print('É equilát... |
c5ae51c6e1045f5cc6af505f8ded338de6bf06b5 | JazKarit/python_teaching | /largest_palindrome_product.py | 452 | 3.921875 | 4 | import time
def is_palidrome(num):
"""Return a boolean representing if the number is a palidrome"""
num_str = str(num)
return False
#Test if is_plaindrome() works
print(is_palidrome(5))
print(is_palidrome(10101))
print(is_palidrome(2002))
print(is_palidrome(524251))
start_time = time.time()
#Lo... |
dbf8bef38b085391898b66f75892387604abb25c | zhaoyu20150930/leetcode-test | /LeetCode/l51.py | 1,995 | 3.546875 | 4 | from typing import List
"""
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
上图为 8 皇后问题的一种解法。
给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。
每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。
示例:
输入: 4
输出: [
[".Q..", // 解法 1
"...Q",
"Q...",
"..Q."],
["..Q.", // 解法 2
"Q...",
"...Q",
".Q.."]
]
解释: 4 皇后问题存在两个不... |
ed054fcb6c792a39fbfded5e121bc0de8f648237 | zhaoyu20150930/leetcode-test | /LeetCode/l1248.py | 1,794 | 3.65625 | 4 | from typing import List
"""
给你一个整数数组 nums 和一个整数 k。
如果某个 连续 子数组中恰好有 k 个奇数数字,我们就认为这个子数组是「优美子数组」。
请返回这个数组中「优美子数组」的数目。
示例 1:
输入:nums = [1,1,2,1,1], k = 3
输出:2
解释:包含 3 个奇数的子数组是 [1,1,2,1] 和 [1,2,1,1] 。
示例 2:
输入:nums = [2,4,6], k = 1
输出:0
解释:数列中不包含任何奇数,所以不存在优美子数组。
示例 3:
输入:nums = [2,2,2,1,2,2,1,2,2,2], k = 2
输出:16
... |
b0b17d6dd2a6e3bcd0df6afe61fa90917a8e61a5 | zhaoyu20150930/leetcode-test | /LeetCode/l22.py | 1,060 | 4 | 4 | from typing import List
"""
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def f(self, nl, nf, a, A):... |
ace6a1f039513d2706d2e9b7e649a72d50adc1c9 | zhaoyu20150930/leetcode-test | /LeetCode/l10.py | 2,421 | 3.71875 | 4 | """
给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '*' 的正则表达式匹配。
'.' 匹配任意单个字符
'*' 匹配零个或多个前面的那一个元素
所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。
说明:
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。
示例 1:
输入:
s = "aa"
p = "a"
输出: false
解释: "a" 无法匹配 "aa" 整个字符串。
示例 2:
输入:
s = "aa"
p = "a*"
输出: true
解释: 因为 '*' 代表可以匹配零个或多... |
4d52fc25cfcabfacccd2c6caf5c2cbc50baf57bd | zhaoyu20150930/leetcode-test | /LeetCode/v16.03.py | 2,938 | 3.796875 | 4 | from typing import List
"""
给定两条线段(表示为起点start = {X1, Y1}和终点end = {X2, Y2}),如果它们有交点,请计算其交点,没有交点则返回空值。
要求浮点型误差不超过10^-6。若有多个交点(线段重叠)则返回 X 值最小的点,X 坐标相同则返回 Y 值最小的点。
示例 1:
输入:
line1 = {0, 0}, {1, 0}
line2 = {1, 1}, {0, -1}
输出: {0.5, 0}
示例 2:
输入:
line1 = {0, 0}, {3, 3}
line2 = {1, 1}, {2, 2}
输出: {1, 1}
示例 3:
输入:
line... |
c5072eac0078b42262bc639059dd18981ad2f107 | zhaoyu20150930/leetcode-test | /LeetCode/l169.py | 1,052 | 4 | 4 | from typing import List
"""
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
"""
多数元素只存在一个
"""
class Solution:
... |
fa3d00c370f5f2a2aeaf82f58f9bb2d7f46a1ec7 | sharonk515/NBA_Statistics_Project | /visualizations.py | 2,953 | 3.703125 | 4 | import seaborn as sns
import matplotlib.pyplot as plt
def desc_stats(df):
"""
Creates a table of descriptive statistics for numerical variables of DataFrame.
Parameters
----------
df: DataFrame name
Specify columns with df[[columns]].
Returns
-------
Outputs a table o... |
6bf0e133756346da9a6f49c3ee62c0870b97844a | nithin-kumar/urban-waffle | /CodeStepByStep/sublist.py | 622 | 3.84375 | 4 | def sublist(arr):
result = []
sublistHelper(result, 0, arr, [])
#print result
def sublistHelper(result, i, arr, path):
#print 'sublistHelper', result, i, arr, path
if len(arr) == 0:
print path
result.append(list(path))
return
#pathWithCurrent = list(path)
#pathWithCurrent.append(arr[i])
#sublistHelper(r... |
cef635066388f048ce3d26fecca96ad288202bbf | nithin-kumar/urban-waffle | /SamQuestions/make_change.py | 750 | 3.59375 | 4 | def make_chage(denominations, limit, memo, i):
if limit in memo:
print 'Hit' , limit
return memo[limit]
print 'make_chage(' + str(denominations) + ',' + str(limit)+')'
# Selecting the base case
# 1) Deleting item from arr and checking the len == 0
# 2) Subtracting the limit and checking for limit == 0
if limi... |
da46590dcb44a879d75f9ebe34eeb043545760c8 | nithin-kumar/urban-waffle | /LucidProgramming/paranthesis_balance_stack.py | 551 | 4.15625 | 4 | from stack import Stack
def is_balanced(expression):
stack = Stack()
for item in expression:
if item in ['(', '[', '{']:
stack.push(item)
else:
if is_matching_paranthesis(stack.peek(), item):
stack.pop()
else:
return False
if not stack.is_empty():
return False
return True
def is_matching_p... |
abcbb6f7a02de5de2d19df7a96a2fa018d2d1985 | nithin-kumar/urban-waffle | /InterviewCake/max_product_3.py | 699 | 4.125 | 4 | import math
def highest_product_of_3(list_of_ints):
# Calculate the highest product of three numbers
if len(list_of_ints) < 3:
raise Exception
return
window = [list_of_ints[0], list_of_ints[1], list_of_ints[2]]
min_number = min(window)
min_index = window.index(min_number)
prod =... |
948938a5fad016b533078e3c505e241f284cc724 | nithin-kumar/urban-waffle | /CodeStepByStep/permute.py | 522 | 3.90625 | 4 | def permute(arr):
result = []
permuteHelper(result, arr, [])
return result
def permuteHelper(result, arr, chosen):
print 'permuteHelper('+ str(chosen) + ',' + str(arr) + ')'
if len(arr) == 0:
print chosen
#result.append(list(chosen))
return
for i in range(len(arr)):
# Choose
elem = arr[i]
chosen.appe... |
9ad6a5f99c12c431a24dc05788cc2362fc2fd320 | marrecs/Raspberry | /Matrix.py | 169 | 3.6875 | 4 |
MATRIX = [ [1,2,3,'A'],
[4,5,6,'B'],
[7,8,9,'C'],
['*',0,'#','D']]
print (MATRIX[1] [1])
print (MATRIX[0] [2])
print (MATRIX[3] [2])
|
b1e996cd2eb3842bdbb15f99fe1bb23caf276160 | tlxxzj/leetcode | /865. Smallest Subtree with all the Deepest Nodes.py | 1,111 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
def depth(node):
if not node:
r... |
a96d757cf042fe2a5e5eaeb7bd68ea96940949de | tlxxzj/leetcode | /25. Reverse Nodes in k-Group.py | 1,498 | 3.859375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if k<=1 ... |
bd87fa47da016f72426f826067e2e471df3adbbf | tlxxzj/leetcode | /110.Blanced.Binary.Tree.py | 624 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
ret = [True... |
f3141a87ea0c4c9fad93f76dcdf6fcce140cc8c5 | tlxxzj/leetcode | /572. Subtree of Another Tree.py | 791 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
if not root:
... |
c8ebed110170084e47b2f65688d978233ffafe2e | tlxxzj/leetcode | /124. Binary Tree Maximum Path Sum.py | 752 | 3.59375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
ninf = -floa... |
7bde1d37b60a214f92596185383a9fec29cc2c89 | Shivani1989/Universe | /Adhoc_Programs/person-dept.py | 1,119 | 3.5625 | 4 | class Person:
def __init__(self, name, job=None, pay=0):
self.name=name
self.job=job
self.pay=pay
def lastName(self):
return(self.name.split()[-1])
def giveRaise(self, percent):
self.pay= int(self.pay*(1+percent))
def __repr__(self):
return ('[Person : %s ... |
a8798d0623136431334ef7e791b6b5cd2a81e187 | nachobh/python_calculator | /main.py | 1,064 | 4.1875 | 4 | def compute(number1, operation, number2):
if is_number(number1) and "+-*/^".__contains__(operation) and is_number(number2):
result = 0
if operation == "+":
result = float(number1) + float(number2)
elif operation == "-":
result = float(number1) - float(number2)
... |
0a217be052ad34e326b15008bf02dcf4a54fa27b | gilgameshzzz/learn | /day4-循环和分支/04-while循环.py | 738 | 4.25 | 4 | # while 循环
"""
while 条件语句:
循环体
while :关键字
条件语句:结果是True,或者False
循环体:重复执行的代码段
执行过程:判断条件语句是否为True,如果为True就执行循环体,执行完循环体在判断条件语句是否True,
如果为True,再次执行循环体,直到条件语句的值为False,循环结束,直接执行其他语句。
注意:如果条件语句的结果一直都是True,就会造成死循环。在循环体中要有可以让循环结束的操作。
Python 中没有do-while循环
"""
# 使用while循环计算1+2+。。+100
x=1;a=0
while x<=100:
a+=x
x+=1
print(a)
... |
a045cd2a100ac535a1ce498f282c9c0b9fb5a80f | gilgameshzzz/learn | /day7Python管理系统/03-函数参数.py | 1,394 | 4.46875 | 4 | """
参数的作用:从函数的外面给函数传值
"""
# 1、位置参数
"""
传参数的时候,实参按顺序给形参赋值
"""
# 2、关键字参数
"""
调用函数的时候:
函数名(参数=值)
"""
def func1(a, b, c):
print(a, b, c)
func1(10, 20, 30)
func1(b=20, a=10, c=30)
# 说明:位置参数和关键字参数可以混着来
# 3、参数的默认值
"""Python中函数的参数可以设置默认值,有默认值的
参数必须放在参数列表的最后
调用参数有默认值的函数,有默认值的参数可以传参也可以不传参
"""
def func2 (a, b, c=100):
... |
5531f81e5a293246c451eec8e6dff1bb005b1b5d | gilgameshzzz/learn | /day6Python字典/day6-字典/dict/04-集合.py | 2,419 | 4.25 | 4 | """__author__ = 余婷"""
"""
集合(set)也是一种容器类型的数据类型(序列);数据放在{}中,多个之间只用逗号隔开:{1, 2, 'a'}
集合是无序的(不能通过索引取取值), 可变(可以增删改), 元素不能重复
集合可以进行数学中集合相关的操作:判断是否包含,求交集、并集、差集、补集
"""
# 1.怎么声明集合
"""a.声明一个变量,赋一个集合值"""
set0 = set() # 创建一个空的集合
set1 = {1, 2, 3, 2, 2}
print(set1, type(set1))
"""b.将其他的数据转换成集合"""
set2 = set('abc1233h') # 将其他数据转... |
314108b57b96328fbc7ebaf09aee3ac342133234 | gilgameshzzz/learn | /day12Python面向对象/04 - 对象的属性.py | 1,164 | 4.0625 | 4 | # Filename : 04 - 对象的属性.py
# Date : 2018/7/31
"""
对象属性的声明
class 类名:
def __init__(self):
self.属性名 = 初值
self.属性名2 = 初值2
"""
class Person:
# 1、init方法是系统自带的一个方法,这个方法不能直接调用,通过类
# 创建对象的时候系统会自动调用这个方法
# init方法的作用是对对象的属性进行初始化
# 2、通过构造方法创建对象的时候,一定要保证,init方法中除了self以外,
# 其他的每个参数都必须有值
... |
c64ba5ea1bb599384e763e95e123b638aa5e3733 | gilgameshzzz/learn | /day5Python/03-列表.py | 1,642 | 4.1875 | 4 | """
列表、字典、元组、集合都是序列,都是容器类型的数据类型
列表(list):用来存储多个数据的一种数据类型。里面存储的单个数据,叫元素
特点1、有序的 2、可变的(可变指容器中的内容的个数和值可变)
3、元素可以是任何类型的数据
列表的值:用[]将列表中的元素括起来,多个元素之间用逗号隔开。[] -->空列表
"""
# 1、怎么声明一个列表
"""1、声明一个变量,赋一个列表值"""
list1 = []
print(type(list1))
"""2、将其他的数据类型转换成列表"""
list2 = list('police')
print(list2)
list3 = list(i*2 for i in rang... |
3fcf3845be2d4a2b662c21374123e759fe344cec | gilgameshzzz/learn | /day7Python管理系统/02-函数的作用.py | 2,056 | 3.921875 | 4 | """
1、函数:就是对实现某一特定功能的代码块的封装
2、作用:封装(将功能绑定在一个函数中,想使用这个函数的时候,直接调用函数)
3、怎么声明函数:
格式: def 函数名(参数列表):
'''函数说明'''
(一个缩进)函数体
def:是python中声明函数的一个关键字
函数说明: 对函数的功能和参数以及返回值进行说明
函数名:标识符。 pep8,见名知义
():是固定格式
参数列表:(形参列表)参数名1、参数名2、参数名3.。
参数的功能是用来接收从外部传到函数内部的数据。
函数体:实现函数功能的代码块,可能会包含一个return语句
4、初学者声明函数的步骤
a、确定函数的功... |
1f5d440084e02fe88bce3a547e56a7c0a83f5e29 | gilgameshzzz/learn | /day12Python面向对象/day12-面向对象基础/object/05-对象属性的增删改查.py | 2,608 | 4.5 | 4 | """__author__ = 余婷"""
class Dog:
"""狗类"""
def __init__(self, age=0, color='yellow'):
self.age = age
self.color = color
if __name__ == '__main__':
dog1 = Dog(3,'white')
# 1.查(获取属性)
"""
方法一:对象.属性 (如果属性不存在,会报错)
方法二:对象.__getattribute__(属性名) 和 getattr(对象, 属性名, 默认值)
"""
... |
599c7d33e1527d59e70365f0925b2153d42fcfc4 | gilgameshzzz/learn | /day5Python/作业.py | 318 | 3.609375 | 4 | list1 = [1, 3, 5, 5, 6, 8, 9]
list2 = [3, 7, 10, 99, 11, 9, 5]
list3 = list1 + list2
print(list3)
list4 = list3[::-1]
for i in list3:
count = 0
for j in list4:
if i == j:
count += 1
if count == 2:
list4.remove(j)
count = 1
list3 = list4[::-1]
print(list3)
|
17866554f72989d5e18dad60ab824915aa0753c4 | Jsings/Palindrome-Problem | /test_pal.py | 1,506 | 3.90625 | 4 | import palindrome
import unittest
cases = ["bobdhv","jbihbob", "noonsjhkj","sdkbjnoon","jksdfbobanfb", "absvnoonsjdf","bobnoonsjhvdbobasdnoonjavdbobahnoon"]
#unittest class to test module palindrome.py
class testPalindrome(unittest.TestCase):
#odd palindrome at start of string
def test_pal_odd_st... |
2c10cdac29aa87916da2ca449c5b4d6a48b11ec9 | Mixiz/python_study | /lesson_5/task_6.py | 1,249 | 3.609375 | 4 | # Создаем структуру
# subjects = [{'Subject': {'lectures': number, 'practice': number, 'labs': number} }, and so on]
# и заполняем ее из файла
# Типы занятий
LESSON_WORDS = ['лекции', 'практика', 'лабораторные']
# Структура занятий
subjects = {}
# Считываем данные из файла
with open('task_6_file.txt', 'r', encoding=... |
5f214bed0b6a63a59d002dfcd685d42f93013b80 | Mixiz/python_study | /lesson_5/task_3.py | 738 | 3.953125 | 4 | # В файле содержатся фамилии сотрудников и их оклады.
# Нужно вывести тех, у кого оклады меньше 20к и сумму среднего оклада среди всех
CRIT_SALARY = 20000
avg_salary = 0
records = []
# Ввод данных
with open('task_3_file.txt', 'r', encoding='UTF-8') as file:
for line in file:
record = line.rstrip('\n').sp... |
86485d9d6f8634e1e1b7cba487180bb6f86441d1 | Mixiz/python_study | /lesson_3/task_2.py | 1,099 | 4.5 | 4 | # Запросим у пользователя данные и передадим их в функцию как именованные аргументы. Вывод в одну строку
def print_user_data(name, surname, birth_place, birth_date, email, phone_number):
print(f'Пользователь {name} {surname} родился {birth_date} в населенном пункте {birth_place}. '
f'Вы можете написать ... |
b10dfdb063283012974f58deb9f5baf5711570bf | skhortiuk/python_course | /lab_5/main_3.py | 803 | 4.1875 | 4 | #! /usr/bin/python3
# -*-coding: utf-8-*-
import random
def human_win(human_move_id, computer_move_id):
if human_move_id == computer_move_id:
return "Draw"
elif human_move_id == 0 and computer_move_id == 2:
return "YOU WIN!!!!!!!"
elif human_move_id > computer_move_id and human_move_id !=... |
27fb2c60aef612197ce7fd6802c800ec51683dfc | skhortiuk/python_course | /lab_5/main_5.py | 195 | 3.84375 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
i = 2
numb = int(input())
while i < numb:
if numb % i == 0:
print("Not simple")
break
i += 1
else:
print("Simple number")
|
c0318f86ec2fd5ac13531c4b6ab07216ea4e967c | neranjana/pythonexamples | /simplescripts/filestuff.py | 397 | 3.6875 | 4 | file=open("./mytextfile.txt", 'w')
file.write("This is a nice file")
file.close()
file=open("./mytextfile.txt", 'r')
fileContent=file.read()
print(fileContent)
file.close()
file=open("./mytextfile.txt", 'a')
file.write("\nthis is a new line")
file.close()
with open("./mysecondfile", 'w') as file:
file.write("Thi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.