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 |
|---|---|---|---|---|---|---|
d458c64eb785af2d04f1590add96f55abe7fd4f9 | SouzaCadu/guppe | /Secao_04_Lista_Ex_53e/ex_39.py | 265 | 3.546875 | 4 | """
Dividir um valor por 46%, 32% e o restante
"""
print(f"O valor inicial é de:")
v = float(input())
p1 = 0.46
p2 = 0.34
p3 = 1 - p1 - p2
print(f"46% do valor é {p1 * v:.2f}, \n"
f"32% do valor é {p2 * v:.2f}, \n"
f"o restante é {p3 * v:.2f}") |
0749cac78b6cc763e8bf415c1b59e46404149c8c | SouzaCadu/guppe | /Secao_06_Estruturas_repeticao/06_29_break.py | 388 | 3.859375 | 4 | """
Saindo de loops com break
Utilizado para sair de loops de maneira projetada, criamos uma condição de parada para determinados loops
"""
# Exemplo 1
for numero in range(0, 150, 5):
if numero == 75:
break
else:
print(numero, end=" ")
# Exemplo 2
print()
while True:
comando = input(... |
fab644ebfde0b5c52983ac2d5aaf9db931bc28ab | SouzaCadu/guppe | /Secao_05_Lista_Ex_41e/ex_21.py | 1,027 | 3.984375 | 4 | """
Monte um menu e execute a ação escolhida,
se a ação for inválida informe o erro.
"""
from sys import exit
print("Escolha a opção:"
"1 - Soma de 2 números.\n"
"2 - Diferença entre 2 números (maior pelo menor). \n"
"3 - Produto entre 2 números. \n"
"4 - Divisão entre 2 números (não há divisã... |
f7abd2c7092c7e148e47391dc2b9e78d7cb2fc72 | SouzaCadu/guppe | /Secao_08_Funcoes/08_47_funcoes_com_parâmetro_padrão.py | 1,916 | 4.65625 | 5 | """
Funções com parâmetro padrão
- funções onde a passagem de parâmetro seja opcional, ou seja, quando eu
estabeleço um valor padrão para o parâmetro, se o usuário informar um valor
como argumento será usado o valor do argumento passado pelo usuário
- ao usar valores padrão eles DEVEM estar no final da declaração ... |
e20439f3edaf2f3aa04657ab8c0d34c39f787e8b | SouzaCadu/guppe | /Secao_08_Lista_Ex_73e/ex_54.py | 867 | 3.828125 | 4 | """
faça uma função que recebe por parâmetro uma matriz [4][4] e retorna a
soma dos seus elementos
"""
from random import randint
def soma_matriz(matriz):
"""
Recebe uma matriz 4 x 4 e calcule a soma dos elementos
:param matriz: Qualquer matriz 4 x 4
:return: Soma dos elementos
"""
soma = 0
... |
2a86881a9688ced8fd4f8974673ababa11015eb7 | SouzaCadu/guppe | /Secao_07_Lista_Ex_25e/ex_19.py | 1,676 | 4 | 4 | """
faça um programa que leia uma matriz de 5 colunas e
4 colunas contendo as seguintes informações sobre
alunos de uma disciplina, sendo todas as informações do tipo
inteiro
- Primeira coluna: matrícula do aluno
- Segunda coluna: média das provas
- Terceira coluna: média dos trabalhos
- Quarta coluna: nota final
A - l... |
ba8ad8967d353f640fe9e81e0b332f75a1a6f944 | SouzaCadu/guppe | /Secao_07_Lista_Ex_39e/ex_10.py | 387 | 3.84375 | 4 | """
faça um programa para ler a nota da prova de 15 alunos
e armazene num vetor, calcule e imprima a média geral
"""
print("Insira 15 notas para saber a média dos alunos.")
v1 = []
count = 1
while count <= 15:
valor = int(input(f"Digite {count} de 15 notas: "))
v1.append(valor)
count += 1
if count > ... |
c9db169a66d3166f20fc1aed6fa32b144b941990 | SouzaCadu/guppe | /Secao_11_Debugando_tratando_erros/11_76_Try_except_else_finally.py | 1,367 | 4.1875 | 4 | """
Try / Except / Else / Finally
Toda a entrada de dados, principalmente do usuário, deve ser tratada!
Else: É executado apenas se não acontecer o erro
try:
num = int(input("Informe um número: "))
except ValueError:
print("Valor incorreto.")
else:
print(f"Você digitou {num}.")
Finally: É sempre execut... |
dbdeacec5370bea5a578ddf5df5a346a42cf0d93 | SouzaCadu/guppe | /Secao_06_Lista_Ex_62e/ex_37.py | 404 | 3.90625 | 4 | """
Escreva um programa que verifique quais os números
entre 1000 e 9999 (inclusive) possuem a
seguinte propriedade:
- a soma dos dois dígitos de mais baixa ordem
com os dois de mais alta ordem elevada ao quadrado
é igual ao próprio número
"""
for i in range(1000, 100000):
j = str(i)
soma = int(j[:2]) + in... |
4c4c2eee1f93b9bbec5823be07037efb22d25d70 | SouzaCadu/guppe | /Secao_04_Lista_Ex_53e/ex_28.py | 278 | 3.78125 | 4 | """
Leia três valores e apresente a soma dos quadrados
"""
print(f"Insira 3 valores para receber a soma de seus quadrados:")
n1, n2, n3 = float(input()), float(input()), float(input())
print(f"A soma dos quadrados dos números informados é { n1 ** 2 + n2 ** 2 + n3 ** 3}.") |
4d9315c7edaad54c0b197c1646965b3908e1c425 | SouzaCadu/guppe | /Secao_07_Lista_Ex_39e/ex_37.py | 482 | 4 | 4 | """
considere um vetor A com 11 elementos
A1 < A2 < ... < A6 > A7 A8> ... > A11, ou seja,
em ordem crescente até o sexto elemento e em
ordem decrescente a partir do sétimo.
"""
print("Insira 11 valores reais")
vetor = []
v1 = []
v2 = []
count = 1
while count <= 11:
valor = float(input(f"Digite {count} de 11 núme... |
b51cf9502c680d0c5f6c42c71cff8e8611151c84 | SouzaCadu/guppe | /Secao_13_Lista_Ex_29e/ex_22.py | 2,572 | 4.3125 | 4 | """
22) Faça um programa que recebe como entrada o nome de um arquivo de entrada e o nome de um arquivo saída.
O arquivo de entrada contém o nome de um aluno ocupando 40 caracteres e três inteiros que indicam suas notas.
O programa deverá ler o arquivo de entrada e gerar um arquivo de saída onde aparece o nome ... |
2ab8fe36f6f5d25af5e294c04aa74ec81c5be5e6 | SouzaCadu/guppe | /Secao_07_Lista_Ex_39e/ex_35.py | 826 | 3.96875 | 4 | """
faça um programa que leia dois números a e b (positivos e menores que 10000)
- crie um vetor onde cada posição é um algarismo do número.
a primeira posição deve ser o número menos significativo
- crie um vetor que seja a soma de a e b, usando os valores
construidos anteriormente
"""
print("Insira dois valores, pos... |
9ddb5dcdade06dd98de8825cb4b9eb74df30b564 | SouzaCadu/guppe | /Secao_07_Lista_Ex_25e/ex_14.py | 493 | 3.796875 | 4 | """
faça um programa para gerar automaticamente números entre
0 e 99 em uma matriz 5 x 5, sem repetições, imprima a matriz
"""
from random import randint, choice
conjunto = set({})
matriz = []
while len(conjunto) < 25:
num = randint(0, 99)
conjunto.add(num)
lista = list(conjunto)
print(lista, len(lista))
fo... |
89463d549cfbd1bd4ca48bd20cb374bc44c27021 | SouzaCadu/guppe | /Secao_07_Lista_Ex_25e/ex_07.py | 527 | 3.75 | 4 | """
gerar uma matriz 10 x 10, onde os elementos são
A[i][j] = 2i + 7 - 2 se i < j
A[i][j] = 3i^2 - 1 se i = j
A[i][j] = 4i^2 + 5j^2 se i > j
"""
matriz = []
for i in range(10):
aux = []
for j in range(10):
aux.append(0)
matriz.append(aux)
for i in range(10):
for j in range(10):
if i <... |
a91cf7747fcd974eae0a0ea95261d82b8aaac1d7 | SouzaCadu/guppe | /Secao_08_Lista_Ex_73e/ex_23.py | 346 | 4.25 | 4 | """
escreva uma função que gere um triângulo lateral de
altura 2*n-1 e n de largura
"""
def triangulo_lateral(num):
linha = ""
for i in range (2 * num - 1):
if i < num:
linha += "*" * (i + 1) + "\n"
else:
linha += (2 * num - (i + 1)) * "*" + "\n"
return linha
print... |
1c5fb28c1c667af22fc2c1737d1113856a7b1b5c | SouzaCadu/guppe | /Secao_07_Lista_Ex_25e/ex_25.py | 2,415 | 4.15625 | 4 | """
faça um programa para determinar a próxima jogada em jogo da velha
o tabuleiro é uma matriz 3 x 3
"""
from collections import Counter
print('Jogo da velha')
def linha_check(matriz, i):
"""Função para conferir o número de X/O na linha i de matriz.
Retorna 1 se há 3 X's, -1 se há 3 O's, e 0 caso contrá... |
4005743837adc1c3fa96d8f95aea9dec02ad2585 | SouzaCadu/guppe | /Secao_17_Lista_Ex_31e/ex_30.py | 1,058 | 3.5625 | 4 | """
30) Baseando-se no exercício 29 adicione os métodos fecharPorta e abrirPorta que
deverá mudar o conteúdo do atributo portaFechada conforme o caso.
"""
from ex_29 import Microondas3
class Microondas4(Microondas3):
def __init__(self):
super().__init__(porta_fechada=True)
def fechar_porta(self):
... |
54d1eb3bad846f3eeb01994f308b6f732456b15a | SouzaCadu/guppe | /Secao_13_Lista_Ex_29e/ex_11.py | 1,204 | 4.15625 | 4 | """
11) Faça um programa no qual o usuário informa o nome do arquivo e uma palavra, e retorne o número de vezes que aquela
palavra aparece no arquivo.
"""
from collections import Counter
def cont_palavra(texto, palavra):
"""
Conta quantas vezes uma palavra aparece em um texto extamente como o usuário inf... |
4a256bfa77951822529589070833c54141adafc5 | SouzaCadu/guppe | /Secao_10_Expressoes_Lambdas_Funcoes_Integradas/10_64_Any_All.py | 999 | 4.125 | 4 | """
Any e All
all(): retorna True se todos os elementos do iterável são verdadeiros ou ainda se o iterável está vazio
Exemplos
print(all([0, 1, 2, 3, 4]), all([1, 2, 3, 4]), all({}),
all("Geek University"))
nomes = ["carlos", "cristiano", "castro", "cassiano", "carina", "camilla"]
print(all([nome[0] == "c" f... |
dc7ea67f1d50c2ce5a980a4f40dd512451657929 | SouzaCadu/guppe | /Secao_17_Lista_Ex_08e/ex_01_08.py | 6,464 | 4.40625 | 4 | """
1) Crie um novo pacote com o nome: heranca. Todas as (três) classes criadas abaixo
deverão ser salvas neste pacote.
2) Crie uma classe Equipamento com dois atributos privados.
3) Crie uma classe Computador com dois atributos sua escolha,
também privados. A classe Computador deverá herdar tudo da classe
Equipament... |
7f543fbaf20cf5f36e0cb2fd5ff8972ddc6f487c | SouzaCadu/guppe | /Secao_08_Lista_Ex_73e/ex_43.py | 623 | 4 | 4 | """
faça uma função que receba um vetor de inteiros e o preencha com
números aleatórios sem repetição
"""
def vetor_inteiros(lista):
print("Informe números inteiros para serem adicionados a um vetor.\n"
"Apenas serão aceitos elemento únicos.\n"
"Para finalizar digite 'Sair'.")
entrada = No... |
d19baede38cab82d0ca2b4f168c89dd366bfac53 | SouzaCadu/guppe | /Secao_08_Lista_Ex_73e/ex_58.py | 1,591 | 4.0625 | 4 | """
faça uma função que receba duas matrizes quadradas de ordem N
e retorne uma terceira matriz, como multiplicação das duas
"""
from random import randint
def multiplica_matrizes(matriz_a, matriz_b):
"""
Recebe duas matrizes quadradas de ordem N
e retorne uma terceira matriz que é a multiplicação das du... |
77bf5f64defe7712ddaff8000265bd881a7240bb | SouzaCadu/guppe | /Secao_06_Lista_Ex_62e/ex_40.py | 604 | 4.125 | 4 | """
Faça um programa que leia vários números inteiros positivos
se um número negativo for digitado o programa deve ser encerrado
e exibir o maior e o menor valor
"""
i = 1
menor = maior = 0
print("Digite quantos números inteiros positivos desejar\n"
"ao digitar um inteiro negativo serão exibidos\n"
"o mai... |
782fe60d2c5bd9df58542168d3249ebc606770f5 | SouzaCadu/guppe | /Secao_18_Manipulando_arquivos_CSV_JSON/18_133_Trabalhando_JSON_Pickle.py | 928 | 3.703125 | 4 | """
JSON e Pickle
JSON (Java Script Object Notation) são um tipo de arquivo muito utilizado em API's
"""
import json, jsonpickle
ret = json.dumps(["produto", {"Playstation 5": ("2TB", "Novo", "220v", 4750)}])
print(ret, type(ret))
class Gato:
def __init__(self, nome, raca):
self.__nome = nome
... |
3601cd2ab4dbfcb4671215627f24a815381a9db2 | SouzaCadu/guppe | /Secao_19_Manipulando_data_hora/19_136_Manipulando_data_hora.py | 891 | 4.125 | 4 | """
Manipulando data e hora
import datetime
print(dir(datetime))
print(datetime.MINYEAR, datetime.MAXYEAR)
print(datetime.datetime, datetime.datetime.now()) # <class 'datetime.datetime'>, 2021-02-12 19:12:35.202509
print(repr(datetime.datetime.now())) # datetime.datetime(2021, 2, 12, 19, 13, 56, 852411)
inicio ... |
53d001aa9ece5395ba80ff292656b291086465fd | SouzaCadu/guppe | /Secao_04_Lista_Ex_53e/ex_37.py | 183 | 3.8125 | 4 | """
Aplicar desconto de 12% sobre um valor
"""
print(f"Desconto de 12% sobre um valor. \n"
f"Insira um valor:")
v = float(input())
print(f"O valor com desconto é {v*0.88}.") |
bc83f0a07ae68ec88ca8b2c778c3940d587f2390 | SouzaCadu/guppe | /Secao_04_Lista_Ex_53e/ex_01.py | 98 | 3.734375 | 4 | # Receber um número inteiro e imprimir
num = int(input("Insira um número inteiro:"))
print(num) |
ae2be8154746d3a5a62fb76e92f6e1d1b6e7932a | SouzaCadu/guppe | /Secao_06_Lista_Ex_62e/ex_32.py | 735 | 4.21875 | 4 | """
faça um programa que simula o lançamento de dois dados n
vezes e tenha como saída:
- o número de cada dado
- a relação entre eles (>, <, =) de cada lançamento
"""
from random import randint
n = int(input("Digite 1 para girar os dados ou 2 para sair: "))
while n != 2:
d1 = randint(1, 6)
d2 = randint(1, 6)... |
5faf644d20a04f669db4f64bcf333b90dfd83f59 | SouzaCadu/guppe | /Secao_07_Lista_Ex_25e/ex_17.py | 947 | 3.953125 | 4 | """
leia uma matriz 10 x 3 com as notas de 10 alunos em 3 provas
escreva o número de alunos cuja pior nota foi na prova 1,
o número de alunos cuja pior nota foi na prova 2 e
o número de alunos cuja pior nota foi na prova 3
o critério de desempate é arbitrário, o aluno deve ser
contado apenas uma vez
"""
from random im... |
4dd2bf14a759e7fd7a3dd9e4488c0cd7c300713c | SouzaCadu/guppe | /Secao_06_Lista_Ex_62e/ex_53.py | 331 | 3.96875 | 4 | """
escreva um programa que leia um número inteiro positivo N e em seguida imprima N
linhas do chamado Triangulo de Floyd.
"""
n = int(input("Digite o valor para o Triângulo de Floyd: "))
linhas = 1
for i in range(1, n + 1):
for j in range(1, i + 1):
print(linhas, end=" ")
linhas = linhas + 1
... |
265ce887362d8f699b0bc7a41d508d03c699689d | SouzaCadu/guppe | /Secao_07_Colecoes/07_40_module_collections_named_tuple.py | 627 | 4.21875 | 4 | """
Módulo Collections - Named Tuple
São tuplas para as quais especificamos um nome, para a tupla e para os parametros
facilitando o acesso a informação.
Aceita os mesmo métodos usados em tuplas
"""
from collections import namedtuple
cachorro1 = namedtuple("cachorro", "raça idade origem")
cachorro2 = namedtuple("ca... |
41b39981143523af2633ce4da0820b064f161df5 | SouzaCadu/guppe | /Secao_04_Lista_Ex_53e/ex_23.py | 192 | 3.6875 | 4 | """
Conversor de metros para jardas
"""
print(f"Conversor de metros em jardas. \n"
f"Insira o valor em metros:")
m = float(input())
print(f"{m} metros equivalem a {m / 0.91} jardas.") |
0361cb6efb465bfde4492102c0d7b6ece2900e41 | SouzaCadu/guppe | /Secao_06_Lista_Ex_62e/ex_30.py | 703 | 4 | 4 | """
Faça um programa para calcular as seguintes sequencias:
-> 1 + 2 + 3 + ... + n
-> 1 - 2 + 3 - ... + (2n - 1)
-> 1 + 3 + 5 + ... + (2n -1)
"""
print("Digite um valor n para calcular as sequencias:\n"
"1 + 2 + 3 + ... + n \n"
"1 - 2 + 3 - ... + (2n - 1) \n"
"1 + 3 + 5 + ... + (2n - 1)")
n = int(in... |
2781c787dc628664a228ebd0be86becf78c23c69 | SouzaCadu/guppe | /Secao_05_Lista_Ex_41e/ex_08.py | 494 | 3.859375 | 4 | """
verifique se os valores digitados estão entre 0.0 e 10.0
e calcule a média
"""
import sys
print("Informe as duas notas do aluno para saber a média.")
v1 = float(input("Digite a primeira nota:"))
if 0.0 <= v1 <= 10.0:
pass
else:
sys.exit(print("Nota inválida. Programa finalizado."))
v2 = float(input("Di... |
f3adc9411761ca5836799f1ae448c4e80f5ab983 | SouzaCadu/guppe | /Secao_06_Lista_Ex_62e/ex_47.py | 1,779 | 4.375 | 4 | """
Dadas as operações fundamentais da matemática,
faça um programa que permita ao usuário escolher
a operação obter o resultado e voltar ao menu
"""
print("Selecione uma das opções para o cálculo das operações\n"
"entre 2 números:\n"
"1 - adição\n"
"2 - subtração\n"
"3 - multiplicação\n"
... |
4db09844fbfd5c0f532ff95432e10892417e4ed5 | SouzaCadu/guppe | /Secao_07_Lista_Ex_39e/ex_06.py | 408 | 4.0625 | 4 | """
faça um programa que receba do usuário um vetor com 10 posições
em seguida imprima o maior e o menor valor
"""
print("Insira 10 números para saber o maior e o menor")
v1 = []
count = 1
while count <= 10:
valor = float(input(f"Digite {count} de 10 números: "))
v1.append(valor)
count += 1
if count ... |
02891b944f40f2d8a31020b6091ef033a2e6d6ed | SouzaCadu/guppe | /Secao_04_Lista_Ex_53e/ex_18.py | 214 | 3.84375 | 4 | """
Conversor de m3 em litros
"""
print(f"Conversor de metros cúbicos em litros. \n"
f"Insira o valor em metros cúbicos:")
m3 = float(input())
print(f"{m3} metros cúbicos é igual a {m3*1000} litros." ) |
9a3914779547ef189c0ceb34dcc0238ad3bd2f15 | SouzaCadu/guppe | /Secao_07_Colecoes/07_36_conjuntos.py | 3,512 | 4.21875 | 4 | """
Conjuntos
Referencia a teoria dos conjuntos da matemática.
Os conjuntos são chamados de set, em Python.
Não possuem valores duplicados, valores ordenados, não são indexados.
São úteis quando precisamos armazenar elementos quando não nos importamos com a
ordem, chaves, valores e itens duplicados.
Sets em Python ... |
89fc6081ad014075e675cc6c38172467d8861961 | SouzaCadu/guppe | /Secao_06_Lista_Ex_62e/ex_33.py | 566 | 4.03125 | 4 | """
Dados n e dois números inteiros positivos, i e j, diferente de 0,
imprimir primeiros naturais que são múltiplos de i ou j ou de ambos
"""
print("Digite a quantidade números múltiplos desejados\n"
"para 2 números a sua escolha.")
print()
n = int(input("Digite a quantidade de múltiplos desejados: "))
i = int(i... |
02a30dcf7b6572e48615667660ca000308fe9f25 | SouzaCadu/guppe | /Secao_07_Lista_Ex_39e/ex_01.py | 384 | 3.796875 | 4 | """
escreva um vetor que armazene 6 números inteiros:
- os valores são 1, 0, 5, -2, -5, 7
- armazene em uma variável o valor da soma das posições [0], [1], [5]
- modifique o valor na posição 4 para 100
- mostre na tela cada valor do vetor em um linha
"""
a = [1, 0, 5, -2, -5, 7]
soma = a[0] + a[1] + a[5]
print(soma)
... |
001eb665780bc4c6b1e162c201d83399ef511157 | SouzaCadu/guppe | /Secao_15_Decoradores/15_109_Decoradores_diferentes_assinaturas.py | 1,970 | 3.890625 | 4 | """
Decoradores com diferentes assinaturas
Relembrado Decorators
def gritar(funcao):
def aumentar(nome):
return funcao(nome).upper()
return aumentar
@gritar
def saudacao(nome):
return f"Olá eu sou, {nome}!"
@gritar
def ordenar(principal, acompanhamento):
return f"Olá eu gostaria de {princi... |
2a95d388f5dfde00a6d5f6c7eeb3c04ee54954ae | SouzaCadu/guppe | /Secao_08_Lista_Ex_73e/ex_14.py | 921 | 4.15625 | 4 | """
faça uma função que receba a distância em KM e a quantidade de litros
de gasolina consumidos por um carro e calcule o consumo em
KM / L e escreva a mensagem de acordo com a tabela
- se menor que 8: venda o carro
- entre 8 e 14 econômico
- maior que 14 super econômico
"""
def avalia_consumo(km, litros):
"""
... |
cd90c86a2e0ddbca4f4ef6262dbbda3cb7c8876b | SouzaCadu/guppe | /Secao_17_Lista_Ex_31e/ex_19.py | 1,363 | 3.609375 | 4 | """
19) Baseando-se no exercicio 18 adicione os métodos ligar e desligar
que deverão mudar o conteúdo do atributo ligado conforme o caso.
"""
from ex_18 import Eletrodomestico1
class Eletrodomestico2(Eletrodomestico1):
def __init__(self):
super().__init__()
self._Eletrodomestico1__ligado = bool
... |
92879635c47f9f7becf3f7a8debe07ec1859b96b | alinasansevich/ROSALIND | /007_calculate_protein_mass.py | 1,820 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 5 18:25:32 2021
@author: alina
Calculating Protein Mass
Problem
In a weighted alphabet, every symbol is assigned a positive real number called a weight.
A string formed from a weighted alphabet is called a weighted string, and its weight is
equa... |
f321cada44ecb2ce103a0acae1c23d4756b7fb43 | germandouce/AyP-1 | /Clases_y_ejercicios/Ejs_RPL/2_Programas_sencillos.py | 6,412 | 4.0625 | 4 | #UNIDAD 2: Programas sencillos
#ej 2.1 - Ganancia
'''
Escribir una función que reciba una cantidad de pesos, una tasa de interés y un
número de años y devuelva el monto final a obtener. La fórmula a utilizar es:
Cn = C × (1 + x⁄100)^n
Donde C es el capital inicial, x es la tasa de interés y n es el número de años a ... |
a8a795d0461e42406e4040b71140f9ce2e1f41c1 | germandouce/AyP-1 | /Clases_y_ejercicios/Ejs_RPL/9_Diccionarios.py | 6,202 | 4.125 | 4 | #UNIDAD 9: Diccionarios
#METODOS CLAVE!
# diccionario.keys() :Devuelve una secuencia desordenada, con todas las claves que se hayan
# ingresado al diccionario
# diccionario.values(): Devuelve una secuencia desordenada, con todos los valores que se hayan
# ingresado al diccionario.
# diccionario.items(): Devuelve... |
7f9f40992be4ec3d540615dd37d3de8e558f416a | vikaspradhan/K-Means-Clustering | /K_means.py | 1,408 | 3.578125 | 4 |
#importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the mall dataset
dataset=pd.read_csv('Mall_Customers.csv')
X=dataset.iloc[:,[3,4]].values
#Using the elbow method to find the optimal number of clusters
from sklearn.cluster import KMeans
wcss=[]
f... |
237802e16ec41465fd3e2ecee0fb292825f3afbb | amandadumi/ising_model | /.ipynb_checkpoints/ising_model_solutions-checkpoint.py | 16,326 | 4.375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In this lab we will look at modeling an Ising system with Monte Carlo.
# # Ising Model
#
# The Ising model is a lattice of $k$ interacting sites. Each site has a spin $\sigma_k$ which can have a value of +1 or -1. The spins are allowed to interact with their nearest-neighbor sp... |
d0a27664d463063f00bc079e2e35653ba92f1526 | earl-grey-cucumber/Algorithm | /108-Convert-Sorted-Array-to-Binary-Search-Tree/solution.py | 666 | 3.71875 | 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 sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
... |
0bec5ddfc164e98819caf9f83e34c535cd3c21ca | earl-grey-cucumber/Algorithm | /114-Flatten-Binary-Tree-to-Linked-List/solution.py | 562 | 3.8125 | 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 flatten(self, root):
if not root:
return
stack = [root]
while stack:
... |
8952a219e349498121e00fc45c06c53b19e92b65 | earl-grey-cucumber/Algorithm | /353-Design-Snake-Game/solution.py | 1,815 | 4.1875 | 4 | class SnakeGame(object):
def __init__(self, width,height,food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at ... |
b539f28b44733e7273eb08953096242b84204ecd | earl-grey-cucumber/Algorithm | /257-Binary-Tree-Paths/solution.py | 835 | 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:
# @param {TreeNode} root
# @return {string[]}
def binaryTreePaths(self, root):
if not root:
return []
... |
072abe4ebb071cb1469c7526999edc1260f0ed64 | earl-grey-cucumber/Algorithm | /199-Binary-Tree-Right-Side-View/solution.py | 630 | 3.6875 | 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 rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def... |
e8dfdbea75b2be373150ed085473b4beb80e6de3 | earl-grey-cucumber/Algorithm | /405-Convert-a-Number-to-Hexadecimal/solution.py | 597 | 3.546875 | 4 | class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return "0"
if num < 0:
num += (2 ** 32)
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
resu... |
5d283d8a63254397338a52e0022cba631b766d2b | earl-grey-cucumber/Algorithm | /295-Find-Median-from-Data-Stream/solution.py | 1,081 | 3.71875 | 4 | from heapq import *
class MedianFinder:
def __init__(self):
"""
Initialize your data structure here.
"""
self.heap1, self.heap2 = [], []
def addNum(self, num):
"""
Adds a num into the data structure.
:type num: int
:rtype: void
"""
... |
a0efc7ae49c9182e84b999f911d72b3ede9e8c1d | earl-grey-cucumber/Algorithm | /272-Closest-Binary-Search-Tree-Value-II/solution.py | 1,396 | 3.515625 | 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 closestKValues(self, root, target, k):
def helper1(cur, target, s1):
if not cur:
... |
49c0a3762a452f1230b9defc3cc28e2e57b32d2e | earl-grey-cucumber/Algorithm | /166-Fraction-to-Recurring-Decimal/solution.py | 1,086 | 3.65625 | 4 | class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator == 0 or denominator == 0:
return "0"
sign = (numerator > 0 and denominator > 0) or (numerator... |
88ccc356697102feb1c40297d78606075abfd6e6 | earl-grey-cucumber/Algorithm | /349-Intersection-of-Two-Arrays/solution.py | 340 | 3.71875 | 4 | class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
temp1 = set(nums1)
temp2 = set()
for num in nums2:
if num in temp1:
temp2.add(num)
... |
9dadc5bb31df7aa74c0373694b63b00bb2cd952d | qiaoyulong9999/keep-moving | /crossinexercise/10.findnum.py | 227 | 3.5 | 4 | # -*- coding: utf-8 -*-
for i in range(1,1001):
if i%3 == 2 and i%5 == 2 and i%7 == 2:
#'%'符号是取整除后的余数
#用'and'连接三个判断条件,只有三个条件同时满足才为True
print i
|
98a8060c77d1739e6dbd03744a73f458fc9198f3 | prokarius/hello-world | /Python/Multigram.py | 638 | 3.578125 | 4 | from collections import Counter
def solve():
word = input()
# Try out all possible ranges of the word
for length in range(1, len(word)):
if len(word) % length != 0: continue
count = Counter(word[0:length])
start = length
flag = True
# Check each chunk has the requi... |
fa80d732a413341b76c6e6a617fd8b9fa32e4051 | prokarius/hello-world | /Python/Recount.py | 448 | 3.75 | 4 | from collections import Counter
def main():
names = []
name = ''
# Scan in input
while name != "***":
name = input()
names.append(name)
count = list(Counter(names).items())
count.sort(key=lambda x: x[1], reverse=True)
# Check if the name that appears the most doesn't have... |
af9f92a59066f529c806055323a51741f784e488 | prokarius/hello-world | /Python/JoeIsLearningToSpeak.py | 2,860 | 3.8125 | 4 | import re
import sys
def makeSentences(words):
out = []
curr = []
for i in words:
if i in ['.', ',', ':', ';', '?', '!', '*', '#']:
out.append(curr)
curr = []
else:
curr.append(i)
return out
def scan_into_words(end_char):
words = []
# Scan... |
791d4769463b97804da4658ecbeae624978855d2 | prokarius/hello-world | /Python/Compass.py | 128 | 3.640625 | 4 | N1 = int(raw_input())
N2 = int(raw_input())
N3 = N2 - N1
if N3 < 0:
N3 += 360
if N3 > 180:
N3 -= 360
print N3
|
8dfb7f8ed7e4266e0a961eca4028f0d47d067f0f | prokarius/hello-world | /Python/Base2Palindrome.py | 666 | 3.90625 | 4 | def main():
n = int(input())
n -= 1
# Duct tape
if n == 0:
print(1)
return
if n == 1:
print(3)
return
length = 1
# There are (2**(length-1)/2) base 2 palindromes
while (n >= 2**((length-1)//2)):
n -= 2**((length-1)//2)
length += 1
#... |
111ae6d45369d359767e0dcae5131b02d47d51b2 | prokarius/hello-world | /Python/BiasedStandings.py | 455 | 3.59375 | 4 | numcases = int(raw_input ())
while numcases > 0:
worthless = raw_input()
numteams = int(raw_input())
somelist = []
while numteams > 0:
team = raw_input()
teamdata = [x for x in team.split(' ')]
somelist.append (int (teamdata [1]))
numteams -= 1
somelist.sort... |
e9ceb23b55a3610188d13f427b84f89cf9eab663 | prokarius/hello-world | /Python/BirthdayBoy.py | 1,767 | 3.71875 | 4 | # HAHAHAHA USING BUILTIN LIBRARIES ON KATTIS?! LOL
from datetime import date, timedelta
def printdate(dateObject):
dateObject -= timedelta(days=1)
print(f"{dateObject.month:02}-{dateObject.day:02}")
def main():
gapSize = timedelta(days=0)
bestBirthdays = []
birthdays = []
# Scan in input
... |
934d86b9bb48d249c79c5a85d053c62a2b6b5775 | prokarius/hello-world | /Python/BellRinging.py | 714 | 4.125 | 4 | # n = 2: [(1, 2), (2, 1)]
# n = 3:
# ( 1 , 2 ,*3*)
# ( 1 ,*3*, 2 )
# (*3*, 1 , 2 )
# (*3*, 2 , 1 )
# ( 2 ,*3*, 1 )
# ( 2 , 1 ,*3*)
# Solution to recurse
def recurse(n):
if n == 1:
return [["1"]]
out = []
flag = False
for i in recurse(n-1):
if flag:
for j in range(n):
... |
82e07ba03bb93ce19de54da0e51a1b6613249e89 | amcdaniel86/hello-flask | /main.py | 1,376 | 3.578125 | 4 | from flask import Flask # imports Flask class from the # 'flask' module.
app = Flask(__name__) # 'app' is the object
app.config['DEBUG'] = True # created by the constructor
# Flask. '_name_' is a variable
@app.route("/") # controlled by... |
58ae13be7529c7ce083ea5c600c26c2d02678334 | sdgSnow/Test01 | /venv/TestData.py | 316 | 3.765625 | 4 | class Data():
# def __init__(self):
# print("abcd")
def __init__(self,name,age):
self.name = name
self.age = age
def printData(self):
print("我的名字叫:%s 年龄是:%s" % (self.name,self.age))
ra
# data = Data()
data = Data("沈道固","25")
# data.printData() |
bfe3c82297892b6139e107c5d85fc974d9d2ced0 | winnqiu/ponggame | /player.py | 1,605 | 3.8125 | 4 | from turtle import Turtle
X = 380
Y = 20
FONT = ('Arial', 30, 'bold')
class Player:
def __init__(self, side):
self.paddle = []
self.side = side
self.create_paddle()
self.score = 0
if self.side == 'right':
self.scoreboard_x = 50
else:
... |
9714602688ed5847c04ec7346ba136d31efdc953 | junjieguo/note_junjie | /python/diff_two_dic.py | 283 | 3.765625 | 4 | 1、求python两个字典的差异和异同
from __future__ import division
for key1 in a:
if key1 in b:
print(key1,a[key1],b[key1],a[key1]/b[key1])
else:
print(key1,a[key1],"2019 is null")
for key1 in b:
if key1 in a:
continue
else:
print(key1,b[key1],"2020 is null")
|
1aaff84fada3f52b2b93a8bcbcead79f6b80c055 | PrzemoPoz/p1 | /zjazd2/funkcje/slack3.py | 514 | 3.703125 | 4 | # Napisz program, który wczyta od użytkownika liczbę X, a następnie wyświetli kwadrat z gwiazdek o długości boku X, np.: 4 ->
# ****
# * *
# * *
# ****
def kwadrat(x):
i = 1
while i <= x:
j = 1
napis = ''
while j <= x:
if i == 1 or j==1 or j == x or i == x:
... |
b9e35f4e4888fe5fd0a7a095cebeb7f8ae376a22 | PrzemoPoz/p1 | /zjazd3/klasy/zad2.py | 1,146 | 3.65625 | 4 | class Employee:
def __init__(self, imie, nazwisko, stawka):
self.imie = imie
self.nazwisko = nazwisko
self.stawka = stawka
self.czas = 0
def register_time(self, czas):
self.czas += czas
def pay_salary(self):
temp = self.czas
if self.czas > 8:
... |
22019677e33cf3ce26019dafc1af692e286ab7e1 | PrzemoPoz/p1 | /zjazd2/zbiory/zad13.py | 232 | 3.796875 | 4 | lista1={}
lista1=[x/10 for x in range(1,11)]
print(lista1)
lista2=[(x,x**2,x**3) for x in range (-10,11)]
print(lista2)
napisy=('jędrzej','przemektusz','vejderova')
lista3=[(slowo,len(slowo)) for slowo in napisy]
print(lista3) |
c17af211309c45967aef4687f249f01c4fcfdf84 | PrzemoPoz/p1 | /zjazd2/funkcje/slack8.py | 617 | 3.828125 | 4 | # Napisz program "numer.py", który zamieni wprowadzony przez użytkownika ciąg cyfr na formę tekstową:
# a) znaki nie będące cyframi mają być ignorowane
# b) konwertujemy cyfry, nie liczby, a zatem:
# - 911 to "dziewięć jeden jeden"
# - 1100 to "jeden jeden zero zero"
def numer(ciag):
tekst=''
slownik = {'1': '... |
854fc230d5fb552508b50a273529c59f8e39e550 | PrzemoPoz/p1 | /zjazd2/funkcje/slack7.py | 672 | 3.640625 | 4 | # Napisz program "prk.py", który obliczy wszystkie pierwiastki rzeczywiste równania kwadratowego o postaci ax2+bx+c=0,
# gdzie a, b i c podaje użytkownik.
# Program powinien na początku sprawdzić, czy wprowadzone równanie jest rzeczywiście kwadratowe.
def prk(a,b,c):
delta=b**2-4*a*c
if delta<0:
return... |
6fc1970260bc6d3a8807cd340488aa5658de2076 | PrzemoPoz/p1 | /zjazd3/klasy/zad5.py | 1,779 | 3.734375 | 4 | class CashMachine:
def __init__(self):
self.bank = []
self.broken=False
def __str__(self):
return "CashMachine"
@property
def is_available(self):
return bool(len(self.bank))
def put_money(self, cash):
self.cash = cash
self.bank.extend(self.cash)
... |
a6709dd3f2e5144cd33eb14ae7e7c7e302a03d26 | nrgs/project3 | /Desktop/HuntTheWumpus/cgi-bin/function.py | 2,730 | 3.921875 | 4 | #!/usr/bin/env python3
import random
list1 = [1, 2, 3,4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
#----------------------------------End of the Map--------------------#
#Set up initial room and pick random numbers to put Bats, pits and Wumpus
#put player in one room randomly
def printCave():
pr... |
747c405037c0c97bc81ec927df2bd1554fade850 | madhuhasa/DigitalAlpha | /april10.py | 1,588 | 3.828125 | 4 | # question 1
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df= pd.read_csv("C:/Users/user/Downloads/100SalesRecords.csv")
print(df.columns.values)
print(df.iloc[:10,:10])
plt.figure(figsize=(10,8))
plt.bar(df["Country"],df["Total Profit"])
plot.show()
for i in range(0,... |
ee3d9cc6487dbafb5bc04af41dd32f488b8f0a4a | vishalnayak108/LID-tool | /utils/extractFeatures.py | 1,642 | 3.921875 | 4 | """
Given a word list with language, prepare the data for input to MALLET
"""
import sys
from collections import defaultdict
import codecs
def get_ngrams(word, n):
"""
Extracting all ngrams from a word given a value of n
"""
if word[0] == '#':
word = word[1:]
if n != 1:... |
dd66976949fb72b580a54ff72e4886204fe837da | smaroukis/workoutDB | /gui.py | 4,296 | 3.5 | 4 | """
A program that stores the following workout information:
Type, Intensity, Duration, Description
User can:
View all
Search by Type, Intensity, Duration
Add entry
Update entry
Delete
Close
"""
#TODO restrict to only low, med, high intensities
#TODO restrict only to bike, swim, run
#TODO better user interface (scroll... |
294b5524828ddd29670236880c70280920dd4e89 | Khushal-ag/Python_Programs | /Data Structures/Strings/change_occurence.py | 155 | 3.6875 | 4 | s = input("Enter a string = ")
s1 = s[0]
for i in range(1,len(s)):
if s[i] == s[0]:
s1 += "$"
else:
s1 += s[i]
print("Output =",s1) |
e41fef5a51508ee82cab6b6a07764d06d9c8b821 | Khushal-ag/Python_Programs | /Data Structures/Strings/length.py | 66 | 3.59375 | 4 | s = input("Enter a string = ")
print("Length = {}".format(len(s))) |
d0b79a142b722879d290f835d7bc73b6b7feaf8e | Khushal-ag/Python_Programs | /Basic_programs/armstrong.py | 211 | 3.859375 | 4 | n = int(input("Enter a number = "))
n1 = n
c = 0
s = 0
while (n != 0):
c += 1
n //= 10
n = n1
while (n != 0):
s += pow(n%10,c)
n //= 10
print("Armstrong") if s == n1 else print("Not Armstrong")
|
ed5237595d09a387c68e03dc2965bb063950f0b5 | Khushal-ag/Python_Programs | /Basic_programs/sum.py | 131 | 3.890625 | 4 | num1 = int(input("Enter First number = "))
num2 = int(input("Enter Second number = "))
print("Sum =", num1 + num2, end="\nFinish")
|
59a7795174f177deed3b3fb39edb76a4e3695708 | Khushal-ag/Python_Programs | /File handling/count_line_word_char.py | 286 | 3.84375 | 4 | with open(r"F:\CODES\Python Programs\File handling\Files\count_char_word.txt","r") as fp:
l = fp.readlines()
line = len(l)
word = len((" ".join(l)).split())
char = len(" ".join(l))
print("Total Lines: {}\nTotal Words: {}\nTotal Characters: {}\n".format(line,word,char))
|
ef66055a816b3350c338422a6a48a33d072f7f2d | Khushal-ag/Python_Programs | /Data Structures/Strings/str_ing.py | 137 | 4.03125 | 4 | s = input("Enter a string = ")
if len(s) >= 3:
if s[-3:] == "ing":
s += "ly"
else:
s += "ing"
print("Output =",s) |
f013b87c15f2d21bbf286fa38b12d7da5a5172be | Khushal-ag/Python_Programs | /Data Structures/Dictionary/invert_key-value.py | 216 | 3.640625 | 4 | n,d1,d2 = int(input("Enter key-pairs to be enter: ")),{},{}
for i in range(n):
k = eval(input("Enter key: "))
v = input("Enter value: ")
d1[k] = v
print(d1)
for i in d1.keys():
d2[d1[i]] = i
print(d2) |
e3c662f8291180332491d5b755c9330c4021be0c | Journo-App/thinkful | /test_bicycle.py | 2,236 | 4.03125 | 4 | import unittest
from bicycle import Bikeshop, Customer, Bicycle
class BicycleTestCase(unittest.TestCase):
# Create a bicycle shop that has 6 different bicycle models in stock.
def test_bikeshop_has_six_models(self):
rock_star = Bikeshop(' Rock Star', {'bianchi': 2, 'schwinn': 5, 'abici': 7, 'cinelli':... |
561aebede9af74b6d1028dc9d7c9233c06be928c | s79082/TIstuff | /scripts/TI_automat.py | 616 | 3.5625 | 4 | import sys
# Endzustaende
ends = ["zE", ]
# index: wert
delta = {"z0": {"a": "z1", "b": "z0", "c": "z0"},
"z1": {"a": "z1", "b": "z2", "c": "z0"},
"z2": {"a": "z1", "b": "z0", "c": "zE"},
"zE": {"a": "zE", "b": "zE", "c": "zE"},
}
def deltad(z, w):
if len(w) == 0:
print ("... |
49c87be0a251e9dfbd209b1ac5c25f6cc95faebe | daguy666/scripts | /b64.py | 1,025 | 3.953125 | 4 | #!/usr/bin/env python
#
# Little script with some logic
# to base64 encode and decode depending
# on users input.
#========================================
import sys
def decodeb64(info):
"""This function will decode a base64 string
"""
decode = raw_input("Enter base64 string to decode: \n> ")
result... |
ee9492a87664812566e8e9b2fe5db3f03ddb56fb | DenizenB/advent-of-code | /2019/3a.py | 1,200 | 3.71875 | 4 | def get_delta(bearing):
if bearing == "R":
return (1,0)
elif bearing == "U":
return (0,1)
elif bearing == "L":
return (-1,0)
elif bearing == "D":
return (0,-1)
def build_points(wire_path):
points = set()
point = (0,0)
for direction in wire_path:
delt... |
4e7a67bba2c600c2039e83af3f6e7213b1f9464a | DenizenB/advent-of-code | /2020/day02-b.py | 744 | 3.671875 | 4 | from puzzle import BasePuzzle
class Password:
def __init__(self, line):
rule, self.password = line.split(": ")
positions, self.target_char = rule.split(" ")
self.positions = [int(position) for position in positions.split("-")]
def valid(self):
x, y = self.positions
ret... |
36d8f5a89f33c3d6680031881db93639471298d6 | Laxaria/LearningPyth3 | /UChig Kattis - MSc Computationl Soc Sci/UChigKattisProblem - Squares.py | 494 | 3.515625 | 4 | # https://uchicago.kattis.com/problems/uchicago.mpcs.square
def recursive_exp(x, n):
if n == 0:
print("1")
elif n == 1:
print(x)
elif n % 2 == 0:
while n > 1:
x = x * x
n = n/2
print(x)
elif n % 2 > 0:
z = x
while n > 1:
... |
0b4692180343e2d59f6eecc315b8886072b07dd9 | Laxaria/LearningPyth3 | /PracticePython/Fibonacci.py | 987 | 4.5625 | 5 | # Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
# Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number
# of numbers in the sequence to generate.
# (Hint: The Fibonnaci seqence is a sequence of numbers where t... |
6d288b804d2b5cc07008fd53cf4ff7352052e458 | MelindaD589/Programming-Foundations-Fundamentals | /practice.py | 448 | 4.125 | 4 | # Chapter 1
print("Hello world!")
# Chapter 2
# Exercise 1
name = input("Hi, what's your name? ")
age = int(input("How old are you? "))
if (age < 13):
print("You're too young to register", name)
else:
print("Feel free to join", name)
# Exercise 2
print("Hello world!")
print("Goodbye world!")
# Exer... |
2befb39837887d18bdf85718197f38184025d8c1 | VivekPawar01/PythonDev | /class,obj,init.py | 487 | 3.65625 | 4 | class Student:
def __init__(self,name,age,id,marks):
self.name=name
self.age=age
self.id=id
self.marks=marks
def show(self):
print(f'Name={(self.name)}',end=' & ')
print(f'Age={(self.age)}',end=' & ')
print(f'ID={(self.id)}',end=' & ')
pr... |
718eb6bf03cbaa5af01eca67514daef90130975e | adtabora/ner_tagger | /flask/db.py | 4,004 | 3.65625 | 4 | import sqlite3
import json
conn = None
class DB:
conn = None
def __init__(self):
self.conn = sqlite3.connect('articles.db')
def createTables(self):
self.conn.execute('''
CREATE TABLE ARTICLE(
ID INT PRIMARY KEY NOT NULL,
TITLE TEXT NOT NU... |
9563c07a3f95251b37426bb2998479e57348e644 | emanueldumitru/flask-bootcamp-marcial | /complete-python-developer-2021/First sections/oop.py | 3,442 | 4.125 | 4 | """
__ dunder or magic methods
"""
class PlayerCharacter:
# Class Object Attribute
membership = True
def __init__(self, name, age):
self.name = name
self.age = age
def shout(self):
print(f'my name is {self.name}')
@classmethod # not used often, cls stands for class
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.