blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4fca55684f127b9722aa94370374dd335d5deec2 | rafaelsantosmg/cev_python3 | /cursoemvideo/ex042.py | 964 | 4.1875 | 4 | """Refaça o DESAFIO #35 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado:
EQUILÁTERO quando todos os seguimentos são iguais.
ISÓSCELES quando dois seguimentos são iguais.
ESCALENO quando todos os seguimentos são diferentes."""
from utilidadescev.dado import leiafloat
from utilidadescev.string import linha
# Mostrando o tipo de TRIANGULO:
linha(25, 'cinza')
seg1 = leiafloat('Primeiro seguimento: ')
seg2 = leiafloat('Segundo seguimento: ')
seg3 = leiafloat('Terceiro seguimento: ')
linha(25, 'cinza')
linha(55, 'verde')
if seg1 < seg2 + seg3 and seg2 < seg1 + seg3 and seg3 < seg2 + seg1:
print('Os seguimentos acima podem formar um triângulo ', end='')
if seg1 == seg2 == seg3:
print('EQUITÁTERO!')
elif seg1 != seg2 != seg3 != seg1:
print('ESCALENO')
else:
print('ISÓSCELES')
else:
print('Os seguimentos acima não podem formar um TRIÂNGULO!')
linha(55, 'verde')
| false |
1f2ec4154f887445c0fc077e68df10472da15de3 | rafaelsantosmg/cev_python3 | /cursoemvideo/ex004.py | 540 | 4.25 | 4 | """Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo
primitivo e todas as informações possivel sobre ele."""
valor = input('Digite algo: ')
print('O tipo primitivo desse valor é ', type(valor))
print('Só tem espacoes? ', valor.isspace())
print('É um número', valor.isnumeric())
print('É alfabético? ', valor.isalpha())
print('É alfanumérico? ', valor.isalnum())
print('Está em maiúsculas? ', valor.isupper())
print('Está em minúscula? ', valor.islower())
print('Está capitalizado? ', valor.istitle())
| false |
7f3fb986406be7cc264e925b82258a373ba253cc | rafaelsantosmg/cev_python3 | /cursoemvideo/ex036.py | 1,277 | 4.3125 | 4 | """Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o
salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então
o empréstimo será negado."""
from utilidadescev.dado import leiadinheiro, leiaint
from utilidadescev.string import *
from utilidadescev.moeda import moeda
# Financiamento Imobiliário sem opção de juros.
linha(60, 'magenta')
casa = leiadinheiro('Quanto custa a casa? ')
salario = leiadinheiro('Quanto você ganha? ') * 30 / 100
anos = leiaint('Em quantos anos você quer pagar? ') * 12
linha(60, 'magenta')
parcela = casa / anos
# Condição de financiamento: O valor da parcela não pode exceder 30% do salário do comprador!
if parcela <= salario:
linha(65, 'verde')
print('Seu financiamento foi APROVADO!')
print(f'Valor a ser financiado {moeda(casa)} em {anos} prestações de {moeda(parcela)}')
linha(65, 'verde')
# Se valor da parcela for superior a 30% do salário.
else:
linha(65, 'vermelho')
print('Infelizmente seu financiamento foi REPROVADO!')
print(f'Valor da parcela {moeda(parcela)} e 30% do seu salário {moeda(salario)}')
linha(65, 'vermelho')
linha()
print('Obrigado volte sempre!')
| false |
28214e95bb57a9a092271b6c29e3fd441d386cb5 | danalvin/uni-code | /anne.py | 1,187 | 4.125 | 4 | def intro():
print ("welcome to the Grading system That determines your grades \n ")
print ("Please input your name:")
username = input().upper()
print("\n")
print(f"Would you like to input your scores? {username} (y/n)")
answer = input().lower()
if answer == 'y':
grades()
else:
print("Thank you and come again")
def grades():
print("please input your scores")
grades = input()
new_grade = int(grades)
if new_grade > 100:
print("Please input a value under 100")
grad()
elif new_grade >= 70:
print ("You have the grade A, Congrats")
elif 70 > new_grade >= 60:
print ("Your grade is B, You can achieve way more")
elif 60 > new_grade >= 50 :
print ("Your grade is C, Work Harder!")
elif 50 > new_grade >=40:
print ("our grade is D, Work Harder!")
else:
print ("You have a FAIL")
print ("\n")
print ("Would you like to input new scores? (y/n)")
jibu=input().lower()
if jibu == 'y':
grad()
else:
print("Thank you for using our software!")
def grad():
grades()
if __name__ == "__main__":
intro() | true |
1d501befd99fbe500d192ee81d3b27c2b0fb08ab | Adasumizox/ProgrammingChallenges | /codewars/Python/7 kyu/YoureASquare/is_square_test.py | 1,280 | 4.125 | 4 | from is_square import is_square
import unittest
class TestIsSquare(unittest.TestCase):
def test(self):
self.assertEqual(is_square(-1), False, "-1: Negative numbers cannot be square numbers")
self.assertEqual(is_square( 0), True, "0 is a square number (0 * 0)")
self.assertEqual(is_square( 3), False, "3 is not a square number")
self.assertEqual(is_square( 4), True, "4 is a square number (4 * 4)")
self.assertEqual(is_square(25), True, "25 is a square number (5 * 5)")
self.assertEqual(is_square(26), False, "26 is not a square number")
def test_rand(self):
import random
for _ in range(1,100):
r = random.randint(0, 0xfff0)
self.assertEqual(is_square(r * r), True, "{number} is a square number ({number} * {number})".format(number=(r * r)))
def solution(n):
import math
if n < 0:
return False
r = math.sqrt(n)
r = math.floor(r)
return r * r == n
for _ in range(1,100):
r = random.randint(0,0xffffffff)
self.assertEqual(is_square(r) , solution(r), "Your solution was incorrect on {number}".format(number=r))
if __name__ == '__main__':
unittest.main() | true |
32a3d0eec8d2906c82df3a78f33a978f54942359 | dunghip/C4E-10-DungH | /ss3.2.py | 1,684 | 4.125 | 4 | <<<<<<< HEAD
print("WELCOM TO OUR SHOP")
clothes = ["T-Shirt","Swearter","Jeans"]
print("new item: 'c', item: 'r', update new item:'u', delete item 'd'")
while True:
action = input("what do youn want?")
action = action.upper()
if action == "C":
print("new item :Jeans")
elif action == "R":
print("Item in shop")
itemx = 1
for clothe in clothes:
print("{0}.{1}".format(itemx,clothe))
itemx +=1
elif action == "D":
aa = int(input("Position:"))
clothes.pop(aa)
print("Item in shop")
itemx = 1
for clothe in clothes:
print("{0}.{1}".format(itemx,clothe))
itemx +=1
elif action == "U":
clothes.insert(1,"Skirt")
=======
print("WELCOM TO OUR SHOP")
clothes = ["T-Shirt","Swearter","Jeans"]
print("new item: 'c', item: 'r', update new item:'u', delete item 'd'")
while True:
action = input("what do youn want?")
action = action.upper()
if action == "C":
print("new item :Jeans")
elif action == "R":
print("Item in shop")
itemx = 1
for clothe in clothes:
print("{0}.{1}".format(itemx,clothe))
itemx +=1
elif action == "D":
aa = int(input("Position:"))
clothes.pop(aa)
print("Item in shop")
itemx = 1
for clothe in clothes:
print("{0}.{1}".format(itemx,clothe))
itemx +=1
elif action == "U":
clothes.insert(1,"Skirt")
>>>>>>> 81d5668b9368832001d3290f13dd8ad8a9cf6fe1
| false |
6292f879d9e4750a50779a75e19becbbb573cbf6 | Elena722/Data-Structure | /Queue.py | 1,223 | 4.4375 | 4 | '''The Queue module implements multi-producer, multi-consumer queues. It is especially useful in
threaded programming when information must be exchanged safely between multiple threads. There are three
types of queues provides by queue module,Which are as following : 1. Queue 2. LifoQueue 3. PriorityQueue Exception
which could be come: 1. Full (queue overflow) 2. Empty (queue underflow)'''
# 1) simple example
print('---1-simple example----')
from queue import Queue
question_queue = Queue()
for x in range(1, 10):
temp_dict = ('key', x)
question_queue.put(temp_dict)
while(not question_queue.empty()):
item = question_queue.get()
print(str(item))
# 2) Create Queue
class Queue:
def __init__(self):
self.__queue = []
def push(self, v):
self.__queue.append(v)
def pop(self):
return self.__queue.pop(0)
def __len__(self):
return len(self.__queue)
def is_empty(self):
return self.__queue == []
q = Queue()
print(f"The queue is empty - {q.is_empty()}")
q.push("first")
q.push("second")
print(f"The queue is empty - {q.is_empty()}")
print(f"Queue size - {len(q)}")
print(q.pop())
print(q.pop())
print(f"The queue is empty - {q.is_empty()}") | true |
e8d5f3b501d1acebe6f6e2f435a39d40df9f7ed2 | Zahidsqldba07/practice-python-2 | /08_rock_paper_scissors.py | 1,265 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays
(using input), compare them, print out a message of congratulations to the
winner, and ask if the players want to start a new game)
"""
player1 = str(input("Who is player 1?"))
player2 = str(input("Who is player 2?"))
def move():
player1_move = str(input(player1 + ", what do you choose -- rock, paper or scissors?"))
player2_move = str(input(player2 + ", and you? Rock, paper or scissors?"))
if player1_move == player2_move:
print("Equal game!")
elif player1_move == "rock":
if player2_move == "paper":
print(player2 + ", you win!")
else:
print(player1 + ", you win!")
elif player1_move == "scissors":
if player2_move == "rock":
print(player2 + ", you win!")
else:
print(player1 + ", you win!")
elif player1_move == "paper":
if player2_move == "scissors":
print(player2 + ", you win!")
else:
print(player1 + ", you win!")
another_game = input("Want to play again? Yes or no?")
if another_game == "yes":
move()
else:
print("That was all, folks!")
move() | true |
0943f06a2534c892ca0081a3ab5498aca1c94b9b | Zahidsqldba07/practice-python-2 | /01_character_input.py | 780 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
Extras:
Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint: order of operations exists in Python)
Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same as pressing the ENTER button)
"""
name = input("What is your name?")
age = int(input("How old are you?"))
print_count = int(input("Give me a random number!"))
years_to_100 = str(2018 + 100 - age)
print((name + ", you will be 100 around the year of " + years_to_100 + "\n") * print_count) | true |
5f0c2f5ea2f30c9213d3cb8e9e5865506cf18124 | IzaakWN/CodeSnippets | /python/ReadAndWriteTextFile.py | 498 | 4.15625 | 4 | # https://docs.python.org/3/tutorial/inputoutput.html
# http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
# CREATE
file = open("test.txt", 'w')
file.write("Hello World! This my first line!")
file.write(" And this is a new sentence!")
file.write("\nAnd this is a new line.")
file.close()
# READ
file = open("test.txt", 'r')
print file.read()
file.close()
# EDIT
file = open("test.txt", 'r+')
for line in file:
print line
file.write("\nEDIT: new line!")
file.close() | true |
4e398584c11b03d2fa2a051f4ed8188f1ac15c18 | xasopheno/study | /advent/1/1.py | 576 | 4.1875 | 4 | # Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
data = []
with open("data.txt", "r") as f:
for line in f:
data.append(int(line))
def fuel(mass: int):
f = (mass // 3) - 2
if f <= 0:
return 0
else:
return f
def fuel_recursive(mass):
f = fuel(mass)
total = f
while f > 0:
f = fuel(f)
total += f
return total
result = sum([fuel_recursive(d) for d in data])
print(result)
| true |
e3530991bc947b86955b437ac6581cc94e8929dd | vikul-gupta/wv-python-exercises | /exercise_dictionary_1.py | 283 | 4.59375 | 5 | #Create a dictionary to hold info about pets, with at least 3 key-value pairs.
#Use of a for loop to print out statements like "Willie is a dog."
pets = {'ziggy': 'canary', 'willie': 'dog', 'bobby': 'hamster'}
for name in pets:
print (name.title() + " is a " + pets[name] + ".")
| true |
9afba033ff0c17f098f725a5fe4f4cbf22e3e1c2 | brcabral/curso-python-essencial | /ppe/session04_variaveis/exercicios/Exer03.py | 303 | 4.1875 | 4 | """
Peça ao usuário para digitar 3 valores inteiros e imprima a soma deles
"""
numero1 = int(input("Digite o primeiro número: "))
numero2 = int(input("Digite o segundo número: "))
numero3 = int(input("Digite o terceiro número: "))
print(f"O número digitado foi: {numero1 + numero2 + numero3}.")
| false |
ad9fad5fd8105c6d1f104e8161c060b53956664b | brcabral/curso-python-essencial | /ppe/session05_estruturas_condicionais/exercicios/exer02.py | 372 | 4.21875 | 4 | """
Leia um número fornecido pelo usuário. Se esse número for positivo, calcule a raiz quadrado do número.
Se o número for negativo, mostre uma mensagem dizendo que o número é inválido.
"""
numero = float(input("Digite um número: "))
if numero > 0:
print(f"A raiz quadrada do número digitado é {numero ** 0.5}")
else:
print("O número é inválido!")
| false |
73ba2041d85af943734e73d988f1f94b917e026c | brcabral/curso-python-essencial | /ppe/session09_comprehensions/exemplos/listas_aninhadas.py | 1,638 | 4.75 | 5 | """
Listas aninhadas (Nested Lists)
- Algumas linguagens de programação possuem uma estrutura de dados chamadas de arrays:
- Unidimensionais (Arrays/Vetores);
- Multidimensionais (Matrizes);
Em Python nós temos as Listas
"""
listas = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Em outras linguagens isso é uma matriz 3 x 3
print(f'Lista listas: {listas}')
print(f'Tipo da variável listas = {type(listas)}')
print("--------------------------------------------------")
# Acessando os elementos de uma lista aninhada
listas = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(f'Primeiro elemento da lista: {listas[0]}')
print(f'Segundo elemento do primeiro elemento: {listas[0][1]}')
print(f'Segundo elemento do terceiro elemento: {listas[2][1]}')
print("--------------------------------------------------")
# Iterando com loops em uma lista aninhada
# Usando for
print('>>> Usando for <<<')
for lista in listas:
for numero in lista:
print(numero)
# Usando list comprehension
print('>>> Usando list comprehension <<<')
[[print(numero) for numero in lista] for lista in listas]
print("--------------------------------------------------")
# Gerando uma matriz 3 x 3
matriz = [[numero for numero in range(1, 4)] for valor in range(3)]
print(f'Matriz 3 x 3: {matriz}')
print("--------------------------------------------------")
# Gerando um jogo da velha
velha = [['X' if numero % 2 == 0 else 'O' for numero in range(1, 4)] for valor in range(1, 4)]
print(f'Jogo da velha: {velha}')
print("--------------------------------------------------")
velha = [['*' for i in range(1, 4)] for j in range(1, 4)]
for i in velha:
print(i)
| false |
5f941824a0a8dc514f9bee3ef222cd28c050e81a | brcabral/curso-python-essencial | /ppe/session11_tratando_erros/exemplos/try_except_else_finally.py | 1,691 | 4.34375 | 4 | """
Try / Except / Else / Finally
Else -> É executado somente se não ocorrer o erro.
- Podemos ter apenas 1 else, depois do tratamento de todas as exceções
Finally -> O bloco finally SEMPRE é executado. Independente se houver ou não uma exceção.
- O finally, geralmente, é utilizado para fechar ou desalocar recursos.
Dica de quando e onde tratar o código.
- Toda entrada de dados deve ser tratada
"""
try:
num = int(input('Digite um número inteiro: '))
except ValueError:
print('Valor digitado incorreto')
else:
print(f'Você digitou o número: {num}')
print("--------------------------------------------------")
try:
num = int(input('Digite um número inteiro: '))
except ValueError:
print('Valor digitado incorreto')
else:
print(f'Você digitou o número: {num}')
finally:
print('Executando o finally')
print("--------------------------------------------------")
def dividir(a, b):
try:
return f'O resultado da divisão de {a} / {b} é: {int(a) / int(b)}'
except ValueError:
return 'Valor incorreto'
except ZeroDivisionError:
return 'Não é possível dividir por zero'
num1 = input('Digite o primeiro número inteiro: ')
num2 = input('Digite o segundo número inteiro: ')
print(dividir(num1, num2))
print("--------------------------------------------------")
def dividir(a, b):
try:
return f'O resultado da divisão de {a} / {b} é: {int(a) / int(b)}'
except (ValueError, ZeroDivisionError) as err:
return f'Ocorreu um problema: {err}'
num1 = input('Digite o primeiro número inteiro: ')
num2 = input('Digite o segundo número inteiro: ')
print(dividir(num1, num2))
| false |
7b5788fefc5e4914e3b1cb1b00c88f0bc3def1c5 | brcabral/curso-python-essencial | /ppe/session04_variaveis/exercicios/exer28.py | 388 | 4.1875 | 4 | """
Faça a leitura de três valores e apresente como resultado a soma dos quadrados dos três valores lido
"""
num1 = float(input('Digite o primeiro número: '))
num2 = float(input('Digite o segundo número: '))
num3 = float(input('Digite o terceiro número: '))
resultado = (num1 ** 2) + (num2 ** 2) + (num3 ** 2)
print(f'A soma dos quadrados dos números digitados é: {resultado}')
| false |
786328a9e9c22a379cfdfca0fa768fb52577cc7f | brcabral/curso-python-essencial | /ppe/session04_variaveis/exemplos/escopo_variaveis.py | 849 | 4.15625 | 4 | """
Escopo de variáveis
Dois casos de escopo:
1 - Variáveis globais
- Variáveis globais são reconhecidas em todo o programa
2 - Variáveis locais
- Variáveis locais são reconhecidas apenas no bloco onde foram declaradas
"""
"""
Python é uma linguagem de tipagem dinâmica.
Isso significa que ao declararmos uma variável, nós não colocamos o tipo de dado dela.
Este tipo é inferido ao atribuirmos o valor à mesma
Diferente de C e Java
int numero = 42;
"""
numero = 42 # Variável global
print(f'Variável numero = {numero}')
print(f'Tipo da variável numero = {type(numero)}')
numero = 'Geek University'
print(f'Variável numero = {numero}')
print(f'Tipo da variável numero = {type(numero)}')
num = 5
print(f'Variável num = {num}')
# novo -> variável local
if num > 10:
novo = num + 10
print(novo)
print(novo)
| false |
5b552d454df52f4b4b58c5c813c04943563739d2 | brcabral/curso-python-essencial | /ppe/session13_leitura_escrita_arquivo/exemplos/leitura_de_arquivos.py | 1,118 | 4.40625 | 4 | """
Leitura de Arquivos
Para ler o conteúdo de um arquivo em Python, utilizamos a função open()
open() -> Na forma mais simples da função, passamos apenas um parâmetro de entrada,
que é o caminho do arquivo a ser lido. Essa função retorna um _io.TextIOWrapper
o qual iremos manipular.
OBS.: Por padrão, a função open() abre o arquivo para leitura. Este arquivo deve
existir, caso contrário haverá um erro tipo FileNotFoundError
documentação:
https://docs.python.org/3/library/functions.html#open
"""
arquivo = open('texto.txt')
print(f'Info do arq: {arquivo}')
print(f'Tipo da variável arquivo: {type(arquivo)}')
print("--------------------------------------------------")
# Para ler o conteúdo do arquivo utilizamos a função read()
# A função read() lê todo o conteúdo do arquivo e não apenas uma linha
conteudo_arquivo = arquivo.read()
print(f'Tipo da variável conteudo_arquivo: {type(conteudo_arquivo)}')
print()
print(f'Conteúdo do arquivo: {conteudo_arquivo}')
# OBS: O Python utiliza cursor para trabalhar com arquivos.
# O cursor funciona comoo o cursor de um editor de texto
| false |
1836b180ec993d167a0975e40b8909b81a52066d | brcabral/curso-python-essencial | /ppe/session08_funcoes/exemplos/docstrings.py | 1,002 | 4.15625 | 4 | """
Documentando funções com Docstrings
- Podemos ainda acessar a documentação através da função help()
- Podemos ter acesso a documentação de uma função utilizando a propriedade __doc__
"""
def diz_oi():
"""Uma função simples que retorna s string 'Oi!'"""
return 'Oi!'
print('>>>>> usando o método help <<<<<')
help(diz_oi)
print('>>>>> usando a propriedade __doc__ <<<<<')
print(diz_oi.__doc__)
print("--------------------------------------------------")
def exponencial(numero, potencia=2):
"""
Função que retorna por padrão o quadrado de 'numero' a 'potencia' informada
:param numero:Número que deesejamos gerar o exponencial
:param potencia: Potência que queremos gerar o exponencial. Por padrão é 2
:return: Retorna o exponencial de 'numero' por 'potencia'
"""
return numero ** potencia
print('>>>>> usando o método help <<<<<')
help(exponencial)
print('>>>>> usando a propriedade __doc__ <<<<<')
print(exponencial.__doc__)
| false |
9fa849968ba43d2b35a4af2f1a4911f9776f10f7 | brcabral/curso-python-essencial | /ppe/session09_comprehensions/exemplos/list_comprehension_p1.py | 1,977 | 4.65625 | 5 | """
List Comprehension
- Utilizando List Comprehension nós podemos gerar novas listas com dados processados a partir de outro iterável
# Sintaxe
- [ dado for dado in iterável ]
"""
numeros = [1, 2, 3, 4, 5]
"""
Para entender melhor o que está devemos dividir a expressão em duas partes
- Primeira parte: for numero in numeros
- Segunda parte: numero * 10
"""
result = [numero * 10 for numero in numeros]
print(f'Múltiplos da lista numeros: {result}')
result = [numero / 2 for numero in numeros]
print(f'Quoeficiente da lista numeros: {result}')
def funcao_quadrado(valor):
return valor * valor
result = [funcao_quadrado(numero) for numero in numeros]
print(f'Quadrado da lista numeros: {result}')
print("--------------------------------------------------")
# List Comprehension VS Loop
numeros = [1, 2, 3, 4, 5]
# Loop
numeros_dobrados_for = []
for numero in numeros:
numero = numero * 2
numeros_dobrados_for.append(numero)
print(f'Lista numeros dobrados usando loop: {numeros_dobrados_for}')
# List comprehension
numeros_dobrados_lc = [numero * 2 for numero in numeros]
print(f'Lista numeros dobrados usando list comprehension: {numeros_dobrados_lc}')
print("--------------------------------------------------")
nome = 'Geek University'
print(f'Upper case na variável nome: {[letra.upper() for letra in nome]}')
print("--------------------------------------------------")
amigos = ['maria', 'julia', 'pedro', 'guilherme', 'vanessa']
print(f'Title case na variável amigos: {[letra.title() for letra in amigos]}')
print("--------------------------------------------------")
print(f'Tabuada do 3 =): {[numero * 3 for numero in range(1, 11)]}')
print("--------------------------------------------------")
print(f'Lista booleana: {[bool(valor) for valor in [0, [], "", True, 1, 3.14]]}')
print("--------------------------------------------------")
print(f'Converter numero in string: {[str(numero) for numero in [1, 2, 3, 4, 5]]}')
| false |
71ec05b50c8466d21f7744da5aad5ed601fbcd38 | brcabral/curso-python-essencial | /ppe/session10_lambdas_func_integradas/exemplos/len_abs_sum_round.py | 2,499 | 4.34375 | 4 | """
Len, Abs, Sum, Round
# Len
- len() -> Retorna o tamanho, quantidade de itens, de um iterável
# Abs
- abs() -> Retorna o valor absoluto de um número inteiro ou real. De forma básica, seria o seu valor sem o sinal
# Sum
- sum() -> Recebe como parâmetro um iterável, podendo receber um valor inicial e retorna a soma total dos elementos,
incluíndo o valor inicial.
OBS.: O valor inicial default = 0
# Round
- round() -> Retorna um número arredondado para n dígitos de precisão após a casa decimal.
Se a precisão não for informada retorna o inteiro mais próximo da entrada
"""
# Len
print(f'Quantidade de elementos da string: {len("Geek University")}')
print(f'Quantidade de elementos da lista: {len([1, 2, 3, 4, 5])}')
print(f'Quantidade de elementos da tupla: {len((1, 2, 3, 4, 5))}')
print(f'Quantidade de elementos do conjunto: {len({1, 2, 3, 4, 5})}')
print(f'Quantidade de elementos do dicionário: {len({"a": 1, "b": 2, "c": 3, "d": 4, "e": 5})}')
print(f'Quantidade de elementos do range: {len(range(0, 10))}')
# Quando utilizamos a função len() o Python faz o seguinte
print(f'Quantidade de elementos da string: {"Geek University".__len__()}')
# Dunder -> funções que tem 2 underline antes e 2 depois do nome da função
print("--------------------------------------------------")
# Abs
print(f'Número absoluto de -5: {abs(-5)}')
print(f'Número absoluto de 5: {abs(5)}')
print(f'Número absoluto de 3.14: {abs(3.14)}')
print(f'Número absoluto de -3.14: {abs(-3.14)}')
print("--------------------------------------------------")
# Sum
print(f'A soma da lista de números 1, 2, 3, 4, 5: {sum([1, 2, 3, 4, 5])}')
# passando valor inicial sum(iterável, valor_inicial)
print(f'A soma da lista de números 1, 2, 3, 4, 5, com valor inicial igual a 5: {sum([1, 2, 3, 4, 5], 5)}')
print(f'A soma da tupla de números 1, 2, 3, 4, 5: {sum((1, 2, 3, 4, 5))}')
print(f'A soma do conjunto de números 1, 2, 3, 4, 5: {sum({1, 2, 3, 4, 5})}')
print(f'A soma do dicionário de números 1, 2, 3, 4, 5: {sum({"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}.values())}')
print(f'A soma da lista de números 3.145, 5.678: {sum([3.145, 5.678])}')
print("--------------------------------------------------")
# Round
print(f'round(10.2): {round(10.2)}')
print(f'round(10.2, 3): {round(10.2, 3)}')
print(f'round(10.5): {round(10.5)}')
print(f'round(10.6): {round(10.6)}')
print(f'round(1.2121212121, 2): {round(1.2121212121, 2)}')
print(f'round(1.219999, 5): {round(1.219999, 5)}')
| false |
85d3a5c6bfe6408413d7792069ffc4e88e2f9cf3 | brcabral/curso-python-essencial | /ppe/session04_variaveis/exercicios/exer35.py | 440 | 4.125 | 4 | """
Sejam a e b os catetos de um triângulo, onde a hipotenusa é obtida pela equação:
hipotenusa = raiz(a² + b²). Faça um programa que receba os valores de a e b e calcule
o valor da hipotenusa através da equação. Imprima o resultado dessa operação
"""
a = float(input('Digite o valor de A: '))
b = float(input('Digite o valor de B: '))
hipotenusa = ((a ** 2) + (b ** 2)) ** 0.5
print(f'O valor da hipotenusa é: {hipotenusa}')
| false |
162e17b501d2d2b66e5c78493632d4137160633d | brcabral/curso-python-essencial | /ppe/session16_orientacao_objetos/exemplos/objetos.py | 2,410 | 4.25 | 4 | """
Objetos
-> São instâncias da classe. Podemos criar vários objetos a partir de uma classe.
Podemos pensar nos objetos como variáveis do tipo definido na classe.
"""
class Lampada:
def __init__(self, cor, voltagem, luminosidade):
self.__cor = cor
self.__voltagem = voltagem
self.__luminosidade = luminosidade
self.__ligada = False
def checa_lampada(self):
return self.__ligada
def ligar_desligar(self):
if self.__ligada:
self.__ligada = False
else:
self.__ligada = True
class ContaCorrente:
contador = 999
def __init__(self, limite, saldo):
self.__numero = ContaCorrente.contador + 1
self.__limnite = limite
self.__saldo = saldo
ContaCorrente.contador = self.__numero
class Usuario:
contador = 0
def __init__(self, nome, sobrenome, email, senha):
self.id = Usuario.contador + 1
self.__nome = nome
self.__sobrenome = sobrenome
self.__email = email
self.__senha = senha
Usuario.contador = self.id
# Instâncias/objetos
lamp1 = Lampada('branca', 110, 3500)
cc1 = ContaCorrente(5000, 20000)
user1 = Usuario('Daniela', 'Amorim', 'dani_amorim@email.com.br', '123456')
print(f'A lâmpada está ligada? {lamp1.checa_lampada()}')
lamp1.ligar_desligar()
print(f'A lâmpada está ligada? {lamp1.checa_lampada()}')
input_nome = 'Priscila'
input_sobrenome = 'Miranda'
input_email = 'primir@email.com.br'
input_senha = '123456'
user2 = Usuario(input_nome, input_sobrenome, input_email, input_senha)
print()
print(f'Tipo da variável user2: {type(user2)}')
print(f'Usuário 2: {user2.__dict__}')
print("--------------------------------------------------")
class Cliente:
def __init__(self, nome, sobrenome, cpf):
self.__nome = nome
self.__sobrenome = sobrenome
self.__cpf = cpf
class CC:
def __init__(self, cliente, email, senha):
self.id = Usuario.contador + 1
self.__cliente = cliente
self.__email = email
self.__senha = senha
Usuario.contador = self.id
def mostra_cliente(self):
print(f'O cliente é : {self.__cliente._Cliente__nome}')
cli1 = Cliente('Marcos', 'Almeida', '123.456.789-00')
cc = CC(cli1, 'almeida.marcos@banco.com.br', '159753')
print(f'Dados da CC: {cc.__dict__}')
# print(f'Dados do cliente da CC: {cc.__cliente.__dict__}')
cc.mostra_cliente()
| false |
79e8d7345b5b4f475f8369cf7601d78cc07332fe | duderman/geek_brains | /python/4/5.py | 740 | 4.28125 | 4 | # 5. Реализовать формирование списка, используя функцию range() и возможности генератора.
# В список должны войти четные числа от 100 до 1000 (включая границы).
# Необходимо получить результат вычисления произведения всех элементов списка.
from functools import reduce
def generate_even_list():
"""Iterates over a list of even nums from 100 to 1000
Yields:
int: current num
"""
for i in range(100, 1000):
if i % 2 != 0:
continue
yield i
result = reduce(lambda a, b: a*b, generate_even_list(), 1)
print(f"Result: {result}")
| false |
d19cd22eb7a80c8c495be268607cdc4f9591ab7f | duderman/geek_brains | /python/4/6.py | 1,202 | 4.375 | 4 | # 6. Реализовать два небольших скрипта:
# а) итератор, генерирующий целые числа, начиная с указанного,
# б) итератор, повторяющий элементы некоторого списка, определенного заранее.
from itertools import count, cycle
from utils import generate_random_list
def generate_list(start, end):
"""Generates a list of numbers within a range
Args:
start (int): Start element
end (int): End element
Yields:
int: current element
"""
for i in count(start):
if i == end:
break
yield i
def repeat_list(list, times):
"""Repeats list elements specified number of times
Args:
list (list): List of elements to repeat
times (int): How many times to repeat
Yields:
int: Current element
"""
i = 0
for el in cycle(list):
if i == times:
break
yield el
i += 1
rand_list = generate_random_list(3)
generated_list = [el for el in generate_list(10, 15)]
repeated_list = [el for el in repeat_list(rand_list, 10)]
print(f"Generated: {generated_list}")
print(f"Repeated: {repeated_list}")
| true |
e65adf44a7d919bafdaf86682fa234e0f04ca123 | adannogueira/Curso-Python | /Exercícios/ex009.py | 943 | 4.21875 | 4 | # Faça um programa que leia um número inteiro qualquer e mostre na tela a sua tabuada.
print('\033[31m===Tabuada===\033[m')
n = int(input('Digite um número: '))
print('\n# Multiplicação')
print(f'{n} x 1={n}\n{n:2} x 2={n*2}\n{n} x 3={n*3}\n{n} x 4={n*4}\n{n} x 5={n*5}')
print(f'{n} x 6={n*6}\n{n} x 7={n*7}\n{n} x 8={n*8}\n{n} x 9={n*9}\n{n} x10={n*10}')
print('\n# Divisão')
print(f'{n}/ 1={n}\n{n}/ 2={n/2:.2f}\n{n}/ 3={n/3:.2f}\n{n}/ 4={n/4:.2f}\n{n}/ 5={n/5:.2f}')
print(f'{n}/ 6={n/6:.2f}\n{n}/ 7={n/7:.2f}\n{n}/ 8={n/8:.2f}\n{n}/ 9={n/9:.2f}\n{n}/10={n/10:.2f}')
print('\n# Soma')
print(f'{n}+ 1={n+1}\n{n}+ 2={n+2}\n{n}+ 3={n+3}\n{n}+ 4={n+4}\n{n}+ 5={n+5}')
print(f'{n}+ 6={n+6}\n{n}+ 7={n+7}\n{n}+ 8={n+8}\n{n}+ 9={n+9}\n{n}+10={n+10}')
print('\n# Subtração')
print(f'{n}- 1={n-1}\n{n}- 2={n-2}\n{n}- 3={n-3}\n{n}- 4={n-4}\n{n}- 5={n-5}')
print(f'{n}- 6={n-6}\n{n}- 7={n-7}\n{n}- 8={n-8}\n{n}- 9={n-9}\n{n}-10={n-10}')
| false |
064976a03e4f7d584ee0f62111262a67e1461312 | adannogueira/Curso-Python | /Exercícios/ex035.py | 452 | 4.21875 | 4 | # Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar
# um triângulo.
a = float(input("Digite o tamanho do lado a: "))
b = float(input("Digite o tamanho do lado b: "))
c = float(input("Digite o tamanho do lado c: "))
if (a + b) > c and (a + c) > b and (b + c) > a:
print("Estes três lados formam um triângulo.")
else:
print("É impossível formar um triângulo com essas medidas.")
| false |
7053c34bbc9ca4f6975e9f567ad55c0f96e27a45 | wez1/uni-projects | /lesson9/task2.py | 1,048 | 4.40625 | 4 | #Make a program which reads a text file, which can have any number of floating point numbers,
#which are all in their own lines. The program will calculate and display the sum
# and average (mean) of all these numbers. Make your program fool proof.
#It should handle all common errors and ignore those lines of the input text file,
#which don't have valid numbers.
def getNumbersFromFile(fileName):
"""returns a list of all the floats from a given txt file"""
lines = []
with open(fileName, 'r') as f:
for line in f:
line = line.strip('\n')
try:
lines.append(float(line))
except:
continue
return lines
def sumFloats(l):
"""returns a sum of floats from given list"""
try:
s = sum(l)
return s
except:
print("Something went wrong while summing!")
def main():
""" main program loop"""
print(getNumbersFromFile("nums.txt"))
print(sumFloats(getNumbers("nums.txt")))
if __name__=='__main__':
main()
| true |
612351e8a996df4054309816e8f5d3fd559bc196 | savageinvestors/Hyperskill--Simple-Chatty-Bot-Project | /Stage 4.py | 1,008 | 4.28125 | 4 | bot_name = 'Aid'
birth_year = '2020'
your_name = input('Enter your name: ')
print('Hello! My name is ' + bot_name + '.')
print('I was created in ' + birth_year + '.')
print('Please, remind me your name.')
print('What a great name you have, ' + your_name +'!')
print('Let me guess your age.')
print('Say me remainders of dividing your age by 3, 5 and 7.')
remainder_3 = int(input('The remainder of your age divided by 3: '))
remainder_5 = int(input('The remainder of your age divided by 5: '))
remainder_7 = int(input('The remainder of your age divided by 7: '))
your_age = ((remainder_3 * 70 + remainder_5 * 21 + remainder_7 * 15) % 105)
print("Your age is " + str(your_age) + "; that's a good time to start programming!")
print('Now I will prove to you that I can count to any number you want.')
your_number = int(input())
x = your_number
count = 0
if x <= your_number:
print(str(x * 0) + '!')
while count < x:
count += 1
print(str(count) + '!')
print('Completed, have a nice day!')
| true |
a9ccb868f4cb5609160c55eab7ddad4f27336112 | elsayed-hussein/ProgrammingFoundationsCourses | /04.AlgorithmsCourse/02.Data Structures/queue.py | 403 | 4.125 | 4 | # try out the Python queue functions
from collections import deque
# TODO: create a new empty deque object that will function as a queue
queue = deque()
# TODO: add some items to the queue
queue.append('a')
queue.append('b')
queue.append('c')
queue.append('d')
# TODO: print the queue contents
print(queue)
x = queue.popleft()
print(x)
print(queue)
# TODO: pop an item off the front of the queue
| true |
2ec3d8bf95091cc1d47cc7001fb873ae040b95c4 | gkustik/week2 | /for.py | 1,436 | 4.53125 | 5 | #Цикл позволяет выполнить один и тот же набор действий действия несколько раз. Например, вот как можно напечатать "Привет мир!" 3 раза:
for number in range(3):
print(f"Привет мир {number}!")
print("---------")
#перебрать строку по буквам
for letter in 'python':
print(letter.upper())
print("---------")
# Разбить строку на слова и посчитать длину слов
example = "Я учусь писать код на Python"
for word in example.split():
print(f'Длинна слова "{word}": {len(word)}')
print("---------")
# Цикл для списка или словаря
students_scores = {1, 21, 19, 6, 5}
print(f'Средняя оценка: {sum(students_scores)/len(students_scores)}')
for score in students_scores:
print (score)
print("---------")
students_scores = {1, 21, 19, 6, 5}
print(f'Средняя оценка: {sum(students_scores)/len(students_scores)}')
# расчет средней оценки через цикл
scores_sum = 0
for score in students_scores:
scores_sum += score
print (scores_sum)
print(f'Средняя оценка: {scores_sum/len(students_scores)}')
print("---------")
# Цикл из словаря, для каждого из товара расчитываем скидку
| false |
517bfa1451b8550566dd7f747c7e659d9f367599 | abhijotm/OMIS30_Fall2019 | /Class8/Solution_MontyHallPart1.py | 1,637 | 4.21875 | 4 | # ##################
# author: midavis
# date: 2019-10-22
#
# OMIS 30
# Fall 2019
# Class 8
# Monty Hall Part 1
# #####################################
# set up 3 doors
# ask the user to select one of them
# open another door without a prize in it
# ask the user to switch
# tell the user if they won
# use a random number generator to figure out which door is the prize
import random
winner_door = random.randint(1,3)
# set up the three doors and then name the random one true
doors = {1: False, 2: False, 3: False}
doors[winner_door] = True
# ask the user to select one of them
print('Which door would you like?')
chosen_door = int(input())
# open another door without a prize
if doors[1] == False and 1 != chosen_door:
door_to_open = 1
elif doors[2] == False and 2 != chosen_door:
door_to_open = 2
elif doors[3] == False and 3 != chosen_door:
door_to_open = 3
else:
door_to_open = 0
# list available doors
available_doors = [1,2,3]
available_doors.pop( available_doors.index(door_to_open) )
available_doors.pop( available_doors.index(chosen_door) )
switch_to_door = available_doors[0]
# ask the user to switch
print('Monty opened up door number ' + str(door_to_open) + ' and it is not the prize.')
print('Would you like to switch to door number ' + str(switch_to_door) + '? y/n')
switch = input()
# tell the user if they won
if switch == 'y':
final_door = switch_to_door
elif switch == 'n':
final_door = chosen_door
else:
final_door = 0
if doors[final_door] == True:
print('Congratulations! You won!')
elif doors[final_door] == False:
print('Bummer, you lost!')
else:
print('ERROR')
| true |
d84e4f074767ed8efe1debd5f374cc299818279e | carlosmaniero/python-para-programadores | /source/04/example_04_2.py | 371 | 4.3125 | 4 | name = 'Eleven' # a string
age = 12 # a int
power = 42.0 # a float
type_format = '{} is a {}'
print(type_format.format(name, type(name)))
print(type_format.format(age, type(age)))
print(type_format.format(power, type(power)))
name = 11 # now name is a int
print(type_format.format(name, type(name)))
print('This is a stranger thing!')
| false |
1ca6349906e433fcbf24c0906f4cbceda73b7e61 | AnniePawl/Core-Data-Structures | /Code/bases_workspace.py | 1,966 | 4.34375 | 4 | import string
# BINARY --> DECIMAL PSEUDOCODE
# Think of 0 as "off", and 1 as "on"
# Reverse string so that index corresponds w/ correct power
# Create variable to keep track of sum
# Start walking thru the binary value
# If value 0, move on b/c it is "off"
# If value is 1, raise 2(because binary) to the power of index(b/c index corresponds to power now)
def binary_to_decimal(binary):
"""Converts a binary number into a decimal"""
reversed_binary = binary[::-1] # i = correct power when reversed
decimal = 0
for i, value in enumerate(reversed_binary):
if value == "0":
continue # ignore 0 because no value
decimal += 2**i # multiply 2 by i b/c index = power, add this value to decimal variable
return decimal
def decimal_to_binary(decimal):
binary_result = ''
new_decimal = int(decimal)
while new_decimal > 0:
remainder = new_decimal % 2
binary_result = str(remainder) + binary_result
new_decimal = int(new_decimal / 2)
return binary_result
def hex_to_decimal(hex_val):
"""Converts hex value(str) to decimal(int)"""
reversed_hex = hex_val[::-1] # reverse so power(of 16) = index
decimal = 0 # keep track of sum
hex_conversion = string.hexdigits # access letters a-f
for i, value in enumerate(reversed_hex): # index = power
new_value = hex_conversion.index(value.lower())
decimal += new_value * (16 ** i)
return decimal
def decimal_to_hex(decimal):
"""Converts decimal(int) to hex value(str)"""
hex_result = ''
hex_conversion = string.hexdigits # access letters a-f
while decimal > 0:
remainder = decimal % 16
hex_result = hex_conversion[remainder] + hex_result
decimal = int(decimal / 16)
return hex_result
if __name__ == '__main__':
print(binary_to_decimal("101010"))
print(decimal_to_binary(256))
print(hex_to_decimal("FF"))
print(decimal_to_hex(255))
| true |
23df81d29947b801cb9719930fa3b992c2808527 | feliciahsieh/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 795 | 4.28125 | 4 | #!/usr/bin/python3
"""
add_integer: add two numbers together
"""
def add_integer(a, b):
""" Add two numbers together, a and b
Args:
a (int): first operand
b (int): second operand
"""
# Check for Infinite number
if a == float('inf') or a == -float('inf'):
return float('inf')
if b == float('inf') or b == -float('inf'):
return float('inf')
# Check for NaN
if a != a or b != b:
return float('nan')
if type(a) is not int and type(a) is not float:
raise TypeError("a must be an integer")
elif type(b) is not int and type(b) is not float:
raise TypeError("b must be an integer")
return(int(a) + int(b))
if __name__ == "__main__":
import doctest
doctest.testfile("tests/0-add_integer.txt")
| true |
034afed8119158bc4993a66e908b76c4b2a69157 | feliciahsieh/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/15-roman_to_int.py | 1,581 | 4.3125 | 4 | #!/usr/bin/python3
"""
15-roman_to_int.py
Python program to convert Roman Numerals to Numbers
"""
def value(r):
""" value() returns value of each Roman symbol
Args:
r: roman numeral to evaluate
Returns:
(int): Decimal value of a roman numeral or -1 if error
"""
if (r == 'I'):
return 1
if (r == 'V'):
return 5
if (r == 'X'):
return 10
if (r == 'L'):
return 50
if (r == 'C'):
return 100
if (r == 'D'):
return 500
if (r == 'M'):
return 1000
return -1
def roman_to_int(roman_string):
""" roman_to_int() Calculates Decimal value of Roman Numbers
Args:
roman_string(str): roman number
Returns:
result (int): decimal number of entire roman number
"""
if not isinstance(roman_string, str) or roman_string is None:
return 0
result = 0
i = 0
while (i < len(roman_string)):
# Get value of symbol at roman_string[i]
s1 = value(roman_string[i])
if (i + 1) < len(roman_string):
# Get value of symbol roman_string[i + 1]
s2 = value(roman_string[i + 1])
# Compare both values
if (s1 >= s2):
# Value of current symbol >= next symbol
result = result + s1
i = i + 1
else:
# Value of current symbol is < next symbol
result = result + s2 - s1
i = i + 2
else:
result = result + s1
i = i + 1
return result
| true |
67fa8dad8815ae47d0e4f4b19a37266624193dee | feliciahsieh/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 767 | 4.25 | 4 | #!/usr/bin/python3
"""
print_square: prints a square of # characters
"""
def print_square(size):
"""
prints a square of # characters
Args:
size (int): number of columns of # character
"""
if isinstance(size, float):
raise TypeError("size must be an integer")
if type(size) != int:
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
if type(size) == float:
if size < 0:
raise TypeError("size must be an integer")
else:
raise ValueError("size must be >= 0")
for i in range(size):
print("#" * int(size))
if __name__ == "__main__":
import doctest
doctest.testfile("tests/4-print_square.txt")
| true |
43d4346fd7faf543ab5f0a4f0f8524a305c8ee73 | cbgoodrich/Unit1 | /isItATriangle.py | 383 | 4.15625 | 4 | #Charlie Goodrich
#09/06/17
#isItATriangle.py - tells you if you have a triangle
side1 = float(input("Enter side A: "))
side2 = float(input("Enter side B: "))
side3 = float(input("Enter side C: "))
bigSide = max(side1, side2, side3)
smallSide = min(side1, side2, side3)
perimeter = side1 + side2 + side3
middleSide = perimeter - bigSide - smallSide
print(middleSide + smallSide > bigSide)
| true |
297e546cf1414e1a541e0ed7227964bf34b72587 | DarkGarik/pythonProject_zodiac | /main.py | 2,348 | 4.21875 | 4 | month = input('Введите месяц: ')
month = month.lower()
day = int(input('Введите число: '))
# Овен Овен 21 марта — 19 апреля
# Телец Телец 20 апреля — 20 мая
# Близнецы Близнецы 21 мая — 20 июня
# Рак Рак 21 июня — 22 июля
# Лев Лев 23 июля — 22 августа
# Дева Дева 23 августа — 22 сентября
# Весы Весы 23 сентября — 22 октября
# Скорпион Скорпион 23 октября — 21 ноября
# Стрелец Стрелец 22 ноября — 21 декабря
# Козерог Козерог 22 декабря — 19 января
# Водолей Водолей 20 января — 18 февраля
# Рыбы Рыбы 19 февраля — 20 марта
if (month == "март") and (21 <= day <= 31) or (month == "апрель") and (1 <= day <= 19):
print('Овен')
elif (month == "апрель") and (20 <= day <= 30) or (month == "май") and (1 <= day <= 20):
print('Телец')
elif (month == "май") and (21 <= day <= 31) or (month == "июнь") and (1 <= day <= 20):
print('Близнецы')
elif (month == "июнь") and (21 <= day <= 30) or (month == "июль") and (1 <= day <= 22):
print('Рак')
elif (month == "июль") and (23 <= day <= 31) or (month == "август") and (1 <= day <= 22):
print('Лев')
elif (month == "август") and (23 <= day <= 31) or (month == "сентябрь") and (1 <= day <= 22):
print('Дева')
elif (month == "сентябрь") and (23 <= day <= 30) or (month == "октябрь") and (1 <= day <= 22):
print('Весы')
elif (month == "октябрь") and (23 <= day <= 31) or (month == "ноябрь") and (1 <= day <= 21):
print('Скорпион')
elif (month == "ноябрь") and (22 <= day <= 30) or (month == "декабрь") and (1 <= day <= 21):
print('Стрелец')
elif (month == "декабрь") and (22 <= day <= 31) or (month == "январь") and (1 <= day <= 19):
print('Козерог')
elif (month == "январь") and (20 <= day <= 31) or (month == "февраль") and (1 <= day <= 18):
print('Водолей')
elif (month == "февраль") and (20 <= day <= 31) or (month == "март") and (1 <= day <= 20):
print('Рыбы') | false |
a38c49b4c01b7caeba204bd65bfdaab039ad3cf9 | Noman-Manzoor/python- | /number_guessing.py | 1,162 | 4.1875 | 4 | # this project guess the number whether they are equaql or not
print("||<<||>>> NUMBER GUESSING GAME <<<||>>||")
import random
randomNo = random.randint(1,100)
def checking_equality():
while randomNo > 0:
user_enter = int(input("Enter your favourite number: "))
if user_enter > randomNo:
print("You enterd the number that is greater than the computer selected number.")
print("Because-------")
print(f"Computer guess the number {randomNo} while you enterd the number {user_enter}.")
elif user_enter < randomNo:
print("You enterd the number that is smaller than the computer selected number.")
print("Because-------")
print(f"Computer guess the number {randomNo} while you enterd the number {user_enter}")
else:
print("You enterd the number that is equal than the computer selected number.")
print("Because-------")
print(f"Computer gussess the number {randomNo} while you enterd the number {user_enter}.")
break
checking_equality()
print("GOOD BYEE!!") | true |
e239783c533ed9aff44e7067bf5b395ba3636921 | dalivaleryia/Valery | /lab_4_file_io.py | 2,197 | 4.125 | 4 | # Задача 9
# Скопировать из файла F1 в файл F2 все строки, начинающиеся на букву "A", расположенные между строками с номерами N1 и N2.
# Определить количество слов в первой строке файла F2
try:
fileInput = open("F1.txt", "r")
#print("File " + fileInput.name + " is opened")
except FileNotFoundError:
print ("File is not found")
except IOError:
print("Some incorrect in reading of " + fileInput.name)
try:
allLines = fileInput.readlines()
fileInput.close()
except Exception:
print("Something gone wrong during reading of " + fileInput.name)
numberLines = 0
for line in allLines:
numberLines += 1
try:
firstLine = int(input("Enter an integer value for the line number between 1 and " + str(numberLines) + " from which the check start:\n"))
firstLine -=1
if(firstLine < 0 or firstLine > numberLines):
print("Number is incorrect")
exit(-1)
except Exception:
print("This is not integer value")
exit(-1)
try:
lastLine = int(input("Enter an integer value for the line number between " + str(firstLine + 1) + " and " + str(numberLines) + " from which the check start:\n"))
lastLine -=1
if(lastLine < firstLine):
print("Number is less than than " + str(firstLine + 1))
exit(-1)
if (lastLine > numberLines - 1):
print("Number is more than " + str(numberLines))
exit(-1)
except Exception:
print("This is not integer value")
exit(-1)
# select strings from the list from firstLine to lastList and starting with "A"
checkLines = list((e for i, e in enumerate(allLines) if i in range(firstLine, lastLine + 1) and e[0] == "A"))
if(len(checkLines) != 0):
fileOutput = open("F2.txt", "w")
for item in checkLines:
fileOutput.write("%s\n" % item)
fileOutput.close()
x = checkLines[0].split()
print("Phrase:\"" + checkLines[0] + "\"" + " contains " + str(len(x)) + " words")
else:
print("There is no any string in " + fileInput.name + " that begins with \"A\"")
| false |
06ce3694cb72b6f66b9249f3e0ef73b118ccb993 | pierrerm/UrthecastApplication | /fibonacci.py | 1,064 | 4.3125 | 4 |
def fibonacci(n, n_2=0, n_1=1, current=2):
"""
The n_th fibonacci number.
Parameters
----------
n : int
The index of the fibonacci number to be computed.
n_2 : int, optional
The value of the current-2 fibonacci number.
n_1 : int, optional
The value of the current-1 fibonacci number.
current : int, optional
The index of the current fibonacci number in the recursion.
Returns
-------
int
The value of the n_th fibonacci number.
"""
if (n < 0): # checks validity of input
return 'Invalid input: please enter n >= 0'
elif (n == 0): # base case for recursion
return 0
elif (n == 1): # base case for recursion
return 1
elif (current == n): # stopping condition, n is reached
return n_2 + n_1
else: # recursive step, compute next fib number
new_n_2 = n_1
new_n_1 = n_2 + n_1
return fibonacci(n, n_2=new_n_2, n_1=new_n_1, current=current+1)
print(fibonacci(19))
| true |
0c18e7f113abbb1c3d8c52aa8547a1e5e292496b | arya-pv/pythonjuly2021 | /data_collections/list/list_1.py | 323 | 4.15625 | 4 | lst1=[]
print(type(lst1))
#to add elements into list
lst2=[]
lst2.append(9)
lst2.append(4)
print(lst2)
lst3=[3,4,5]
lst3.append(8) #add element
lst3.remove(4) #to remove elements
lst3.clear() #all elements will be removed and we get empty list
del lst3 #to delete the list itself
print(lst3) #so list is mutable | true |
973315a78dc379f23fb2168a945501a7d40b88e8 | arya-pv/pythonjuly2021 | /oop/constructor/intro.py | 410 | 4.125 | 4 | #constructoe is used to initialize instance variable
class Person:
def __init__(self,name,age,address): #__init__ it is the constructor
self.name=name
self.age=age
self.address=address
def printvalue(self):
print(self.name,self.age,self.address)
obj=Person("anu",23,"paramel house") #by using constructor we put the things inside the object itself
obj.printvalue()
| true |
bf0bc7bc8c4c0b1686a9e21ac119f6b5b9c3a1fe | radhikaarajput/Python_Basics | /lists.py | 1,886 | 4.4375 | 4 | #A list is a collection which is ordered and changeable. In Python lists are written with square brackets
l1=['abc','app','hey']
print(l1)
#access the list items by referring to the index number:
print(l1[1])
#Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc
print(l1[-1])
#specify a range of indexes by specifying where to start and where to end the range
print(l1[1:2])
#By leaving out the end value, the range will go on to the end of the list
print(l1[1:])
#Specify negative indexes if you want to start the search from the end of the list
print(l1[-2:-1])
#o change the value of a specific item, refer to the index number
l1[1]='soft'
print(l1)
#loop through the list items by using a for loop:
for item in l1:
print(item)
#determine if a specified item is present in a list use the in keyword:
if 'soft' in l1:
print("Soft present in List l1")
#determine how many items a list has, use the len() function:
print(len(l1))
#add an item to the end of the list, use the append()
l1.append('priya')
print(l1)
#Insert an item as the second position
l1.insert(2,'surabhi')
print(l1)
#remove() method removes the specified item
l1.remove('soft')
print(l1)
#The pop() method removes the specified index, (or the last item if index is not specified):
l1.pop()
print(l1)
l1.pop(0)
print(l1)
#del keyword removes the specified index
del l1[0]
print(l1)
#The del keyword can also delete the list completely: del l1
#clear() method empties the list : l1.clear()
#Make a copy of a list with the copy() method
l2= l1.copy()
print(l2)
#Join Two Lists
l3=l1+l2
print(l3)
#Another way to join two lists are by appending all the items from list2 into list1, one by one
l1.append(l2)
print(l1)
#se the extend() method, which purpose is to add elements from one list to another list
l1.extend(l2)
print(l1)
| true |
d5ee46fe0b2c27c867b6e3d66bc86ab488aad5dd | radhikaarajput/Python_Basics | /tuples.py | 650 | 4.4375 | 4 | #A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets
tup=('priya','surabhi','zia')
print(tup)
#acessing tuple is same as list
print(tup[0])
print(tup[-1])
print(tup[0:1])
print(tup[-2])
#Iterate through the items and print the values:
for item in tup:
print(item)
#Add Items
#Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
#tup[2]='xxx'
#Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:
del tup
#To join two or more tuples you can use the + operator:
t1=('a','b')
t2=('v','y','z')
t3=t1+t2
print(t3)
| true |
ca441e9731f6180c39b93ebebecd83f513779eab | dillerm/My-Code-Beginner-level- | /readFASTA.py | 893 | 4.40625 | 4 | #The following code is meant to parse a FAFSA file and return the defline and sequence string
#Note that, if a file contains multiple sequences, the defline of sequences after the first...
#...will be indicated by a '>'
fileName = raw_input('Enter FASTA file name: ') #Prompts user for file name
fastaOpen = open(fileName) #Opens FASTA file based on user's entry
defline = fastaOpen.readline() #Reads Description line in FASTA file
if defline.startswith('>'): #Checks whether or not the first line begins with '>'
identifier = defline.lstrip('>;')
print identifier
else:
print 'Not a FASTA file'
def read_fasta_file(): #Reads file and returns the contents of the defline and the sequence string
while 1:
sequence = fastaOpen.read().rstrip()
if sequence == "" or sequence.endswith('*'):
break
print sequence
read_fasta_file()
| true |
b19d638d7ecc67f27304ac54f6b54cd3afc82985 | wduan1025/python-intro | /lecture4/circle.py | 399 | 4.125 | 4 | class Circle:
pi = 3.14159
radius = 0
def set_radius(self, r):
self.radius = r
def get_area(self):
return self.pi * self.radius**2
circle = Circle()
radius=5
circle.set_radius(radius)
print("Area of a radius={r} circle is {s}".format(r=radius, s=circle.get_area()))
circle.pi = 666
print("Area of a radius={r} circle is {s}".format(r=radius, s=circle.get_area()))
| false |
d07f3342be5782360599fdbd468178bd1898799f | rkkaveri/acadview_assignments | /GUI_1.py | 2,575 | 4.46875 | 4 | #Q1.Write a python program using tkinter interface to write Hello World and a exit button that closes the interface.
from tkinter import *
root=Tk()
root.title("Heya!!")
root.geometry('200x100')
label=Label(root,text="Hello World")
label.pack()
button=Button(root,text='Exit',command=root.destroy)
button.pack()
root.mainloop()
#Q2.Write a python program to in the same interface as above and create a action when the button is click it will display some text.
from tkinter import *
root=Tk()
root.title("Heya!!")
root.geometry('500x200')
root.configure(background='blue')
def print_msg():
label=Label(root,text="Welcome to our page user.", font="Courier 15", bg='yellow')
label.pack()
label=Label(root,text="Press Button Print to view the text", font="Courier", bg='red')
label.pack()
b1=Button(root,text='Print',command=print_msg)
b1.pack(side=LEFT)
b2=Button(root,text='Exit',command=root.destroy)
b2.pack(side=RIGHT)
root.mainloop()
#Q3.Create a frame using tkinter with any label text and two buttons.One to exit and other to change the label to some other text.
from tkinter import *
root=Tk()
root.title("Heya!!")
root.geometry('600x200')
root.configure(background='blue')
frame_1=Frame(root,bg='black')
frame_1.pack()
label=Label(frame_1,text="Press 'Print' Button to change text", font="Courier 16 bold underline", bg='red')
label.grid(row=0,column=0)
def print_msg():
label.configure(text="Welcome to our page user.", font="Courier 20", bg='yellow')
label.grid(row=0,column=0)
b1=Button(root,text='Print',activebackground='green' , activeforeground='white',command=print_msg)
b1.pack(fill=X,side=TOP)
b2=Button(root,text='Exit',activebackground='green' , activeforeground='white',command=root.destroy)
b2.pack(fill=X,side=BOTTOM)
root.mainloop()
#Q4. Q4.Write a python program using tkinter interface to take an input in the GUI program and print it.
from tkinter import *
root=Tk()
root.title("Heya!!")
root.geometry('600x200')
root.configure(background='blue')
l1=Label(root,text="Enter Your Name Below:")
l1.pack()
e1=Entry(root)
e1.pack()
def print_msg():
name=e1.get()
print("User name: ",name)
txt="Welcome to our page "+name
label=Label(root,text=txt, font="Courier 16 bold underline", bg='red')
label.pack(fill=X)
b1=Button(root,text='Submit',activebackground='green' , activeforeground='white',command=print_msg)
b1.pack(fill=X,side=TOP)
b2=Button(root,text='Exit',activebackground='green' , activeforeground='white',command=root.destroy)
b2.pack(fill=X,side=BOTTOM)
root.mainloop()
| true |
f3a811d7357b4b8ec1eb3cfd42af654bd1b58dce | rkkaveri/acadview_assignments | /Numpy.py | 1,630 | 4.5 | 4 | #Q1.Create a numpy array with 10 elements of the shape(10,1) using np.random and find out the mean of the elements using basic numpy functions.
import numpy as np
arr=np.random.rand(10,1)
print("Array:\n",arr)
print("Mean: ",arr.mean(axis=0))
#Q2.Create a numpy array with 20 elements of the shape(20,1) using np.random find the variance and standard deviation of the elements.
import numpy as np
arr=np.random.rand(20,1)
print("Array:\n",arr)
print("Mean: ",arr.mean(axis=0))
print("Variance: ",arr.var(axis=0))
print("Standar Deviation: ",arr.std(axis=0))
#Q3.Create a numpy array A of shape(10,20) and B of shape (20,25) using np.random. Print the matrix which is the matrix multiplication of A and B. The shape of the new matrix should be (10,25). Using basic numpy math functions only find the sum of all the elements of the new matrix.
import numpy as np
A=np.random.rand(10,20)
B=np.random.rand(20,25)
C=A.dot(B)
print("\nNew Array: \n",C)
print("Shape of new array: ",np.shape(C))
print("Sum of elements in new array: ",np.sum(C))
#Q4.Create a numpy array A of shape(10,1).Using the basic operations of the numpy array generate an array of shape(10,1) such that each element is the following function applied on each element of A.
#f(x)=1 / (1 + exp(-x))
#Apply this function to each element of A and print the new array holding the value the function returns
'''
Example:
a=[a1,a2,a3]
n(new array to be printed )=[ f(a1), f(a2), f(a3)]
'''
import numpy as np
A=np.random.rand(10,1)
print("\nArray A:\n",A)
f=lambda x:(1/(1+np.exp(-x)))
print("\nNew array:\n",np.array(list(map(f,A))))
| true |
aadd20cc31e00938c7b0702b6ad8993763f75087 | shinysu/workshops | /KCGBridgeCourse/Day2/2_goto_location.py | 484 | 4.53125 | 5 | '''
move the turtle to a location and draw the shape
t.goto(x, y) is used move the turtle to the location(x,y) in screen
'''
import turtle
from random import randint
t = turtle.Turtle()
def draw_shape(t, sides, length):
angle = 360 / sides
for i in range(sides):
t.forward(length)
t.left(angle)
sides = randint(3, 8)
length = randint(50, 300)
t.penup()
t.goto(100, 100)
t.pendown()
t.color("green")
t.begin_fill()
draw_shape(t, sides, length)
t.end_fill() | true |
dca2bc038295cc7033f56be37b9af854e6ef8205 | shinysu/workshops | /KCGBridgeCourse/Day4/2_calculator.py | 314 | 4.25 | 4 | '''
perform arithmetic operations
'''
num1 = int(input("First number: "))
num2 = int(input("Second number: "))
print("Sum = ", num1 + num2)
print("Difference = ", num1 - num2)
print("Product= ", num1 * num2)
print("Quotient= ", num1 / num2)
print("Remainder= ",num1 % num2)
print("Square of num1 = ", num1 ** 2)
| false |
8b1e881217e495e446a37b924a75d3aedd16ec42 | shinysu/workshops | /KCGBridgeCourse/Day11/readline.py | 320 | 4.375 | 4 | '''
Using readline() to read the a single line from the file. It reads the contents of the file one line at a time.
while loop is used to read all lines from the file
'''
with open("input.txt") as reader:
line = reader.readline()
while line != '':
print(line.strip('\n'))
line = reader.readline() | true |
187be36a6e03e94ea4add26df825a075155e1333 | shinysu/workshops | /KCGBridgeCourse/Day3/draw_bot_v5.py | 772 | 4.1875 | 4 | '''
using while loop to execute the loop continuosly
clear() - to clear the screen
'''
import turtle
t = turtle.Turtle()
def draw_circle(radius):
t.circle(radius)
def draw_shape(sides, length):
angle = 360 / sides
for i in range(sides):
t.forward(length)
t.left(angle)
polygon_sides = {'triangle': 3, 'square': 4, 'pentagon': 5, 'hexagon': 6, 'septagon': 7, 'octagon': 8}
while True:
print("What would you like to draw?")
user_input = input().lower()
t.clear()
if user_input == 'circle':
draw_circle(100)
elif user_input in polygon_sides:
draw_shape(polygon_sides[user_input], 100)
elif user_input == 'exit':
break
else:
print("Sorry, can't draw that shape")
print("Thank You!") | true |
4d4b66656e199fa02b710069bff6876d874b6586 | biobeth/snake_club | /resources/2.lists_dicts/Lists_Exercises.py | 1,235 | 4.375 | 4 | ##This is a list of names, note that lists are defined by [] and can contain
##many types of variables including strings, integers and floats
Names = ['Bob', 'Jeff', 'Matt']
##Slicing is how we refer to taking a subsection of the lists.
print(Names[0:2]) ##Prints the first two entries
##A list can be altered
Names[1] = 'Dick'
##A list can also be added to (Note that strings themselves are immutable in python)
Names.append('Pope')
##This does not copy the list, but rather instead makes 2 variables point to the same object
B = Names
##Note, the numbering of the list starts at 0
B[2] = 'Blackbird'
##This returns ['Bob', 'Dick','Blackbird', 'Pope'] as we altered B, which points
##to the same place as Names
print(Names)
##Using Len you can also assess how long a list is
len(Names) #4
##If the list contains integers or floats, adding them is easy using sum()
Num = [7,8,9]
print(sum(Num))
##Exercise:
Ex1 = ['Beth', 'John', 'Astra', 'Shannon', 'Tom']
##Q1: Assess the length of the list
##Q2: Replace the second entry in the list with your favourite colour
##Q3: Add a list entry, is the length of the list now divisible by two?
Ex2 = [7, 9, 12, 3]
##Q4: Add the elements of Ex2 together
| true |
3103b4a10a68e25c305325131e3e846dbcde62a4 | Luviriba/exercicios_python_11-17 | /tarefa15.py | 437 | 4.25 | 4 | # 15. Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.
# farenheit é ((9*celsius)/5)+32
# Kelvin é (°C + 273,15 )= K
celsius = float(input("temperatura: "))
farenheit = ((celsius * 9)/5)+32
kelvin = (celsius + 273.15)
print("{} graus Celsius e igual a {} farenheit".format(celsius, farenheit))
print("{} graus Celsius e igual a {} kelvin".format(celsius, kelvin))
| false |
2024852c5091552c8d581336a5df8cd2c8a03581 | gmodena/python-snippet | /maxsubarray.py | 1,315 | 4.25 | 4 | #!/usr/bin/env python
import doctest
__author__ = "Gabriele Modena <gm@nowave.it>"
"""
Given an array of positive and negative (NON ZERO) numbers find the subarray of maximum sum.
"""
def maxsubarray(a=[-1, 2, 5, -1, 3, -2, 1]):
"""
Linear solution to the max subarray problem.
Base cases
>>> maxsubarray([])
[]
>>> maxsubarray([-1, -2, -3, -1])
[-1]
>>> maxsubarray([0, 1, -1])
[0, 1]
>>> a = [-1, 2, 5, -1, 3, -2, 1]
>>> maxsubarray(a)
[2, 5, -1, 3]
"""
cur_end = 0
cur_sum = 0
cur_start = 0
max_sum = None
max_start = 0
max_end = 0
arr_len = len(a)
for cur_end in range(0, len(a)):
# compute all subarrays till the current element
cur_sum += a[cur_end]
if cur_sum > max_sum:
max_sum = cur_sum
max_start = cur_start
max_end = cur_end
if cur_sum < 0:
cur_sum = 0
cur_start = cur_end + 1
return a[max_start:max_end+1]
if __name__ == '__main__':
doctest.testmod()
try:
a = input("Insert a python list of non zero integers (ie: [-1, 2, 5, -1, 3, -2, 1])\n")
print "Max subarray:", maxsubarray(a)
except:
print "Invalid input"
exit(0) | false |
c840c3822cebbf00fd4e2a208c7d8b452804b9f4 | HerGisl/t111PROG | /max_int.py | 423 | 4.375 | 4 | #The user inputs an integer until a negative number inentered. Algorithm findes
#the maximum positive number input.
num_int = int(input("Input a number: ")) # Do not change this line
max_int = 0
while num_int >= 0:
num_int = int(input("Input a number: ")) # Do not change this line
if num_int > max_int:
max_int = num_int
print("The maximum is", max_int) # Do not change this line
| true |
fd15670cac08a49596b773e3f79a626d3f7e072d | SethHWeidman/algorithms_python | /02_stanford_algorithms/radix_sort.py | 877 | 4.21875 | 4 | '''
https://brilliant.org/wiki/radix-sort/
'''
import math
import random
import typing
def counting_sort_digit(A: typing.List[int], digit: int, radix: int):
B = [0] * len(A)
C = [0] * radix
for el in A:
digit_of_el = int(math.floor(el / (radix ** digit))) % radix
C[digit_of_el] += 1
for i in range(1, radix):
C[i] = C[i] + C[i - 1]
for el in reversed(A):
digit_of_el = int(math.floor(el / (radix ** digit))) % radix
B[C[digit_of_el] - 1] = el
C[digit_of_el] -= 1
return B
def radix_sort(L: typing.List, radix: int):
for i in range(radix):
L = counting_sort_digit(L, i, radix)
return L
if __name__ == '__main__':
alist = random.choices(list(range(0, 999)), k=100)
print("Unsorted list")
print(alist)
print()
print("Sorted list")
print(radix_sort(alist, 10))
| true |
ebae0f2938ae1a04a35e5b4a9b37d15fcf01f604 | MarkMoretto/python-examples-main | /recursion/triangular_number.py | 1,154 | 4.1875 | 4 | #!/bin/python3
# -*- coding: utf-8 -*-
from typing import Iterator
def triangle_num(value: int) -> int:
"""Returns triangular number for a given value.
Parameters
----------
value : int
Integer value to use in triangular number calculaton.
Returns
-------
int
Triangular number.
Examples:
>>> triangle_num(0)
0
>>> triangle_num(1)
1
>>> triangle_num(4)
10
>>> triangle_num(10)
55
>>> triangle_num("A")
Traceback (most recent call last):
...
TypeError: '>' not supported between instances of 'str' and 'int'
>>> triangle_num(-1)
Traceback (most recent call last):
...
TypeError: Please use positive integer value
"""
if value >= 0:
tot : list = [0]
def recur(n: int, t: list) -> Iterator:
if n > 0:
t[0] += n
n -= 1
return recur(n, t)
recur(value, tot)
return tot[0]
raise ValueError("Please use positive integer value.")
if __name__ == "__main__":
import doctest
doctest.testmod()
| true |
18d4c38b4125d83a162a9ce935f794d3b38124fb | Suraj124/python_practice | /09-03-2019/lec_23.py | 475 | 4.125 | 4 | str="Suraj Yadav Suraj Yadav suraj yadav"
print(str.find("Y")) #find() return the position of alphabet or word
print(str.find("aj"))
print(str.find("Ya",(str.find("Ya")+1),len(str))) #find("string",startIndex,EndIndex)
print(str.count("Suraj")) #count()-> Counts the frequency
print("replace()->>"+str.replace("Suraj","Traun"))
print("replace()->> only one string->>"+str.replace("Suraj","Tarun",1))
print("lower()->>"+str.lower())
print("upper()->>"+str.upper())
print("title()->>"+str.title()) | false |
e8caa663133ae5693a956ebe6630b2a346837bd1 | Suraj124/python_practice | /16-03-2019/lec_51.py | 291 | 4.1875 | 4 | num=int(input("Enter a number : "))
if num%2==0:
print(num,"isEven Number")
else:
print(num,"is Odd Number")
##########################################
if num%2==0:print(num,"isEven Number") #
else:print(num,"is Odd Number") #
########################################## | false |
a40b761b8d965e8b09a99c1f47c2faba0b5c9da8 | bovem/algorithms-in-a-nutshell | /python/stack.py | 2,651 | 4.34375 | 4 | # This script implements stack
class Node:
"""
This class is used to represent a Node.
A Node has a value and a pointer to next Node.
...
Attributes
----------
value : int
Value of the node
next : Node
Pointer to next node
Methods
-------
connect(next=Node)
Connects current node to the node specified in parameter
"""
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def connect(self, next):
"""Connects current node to the node specified in parameter
Parameters
----------
next : Node
Node to be connected
"""
self.next = next
class Stack:
"""
This class used to represent a Stack.
Leading Node of Stack is called Top and ending Node of Stack is called Bottom.
...
Attributes
----------
top : Node
Leading Node of Stack
Methods
-------
display()
Prints complete Stack
convert(list)
Converts an array into Stack
push(value)
Pushes value to the top of Stack
pop()
Removes value from the top of Stack
"""
def __init__(self, top=Node()):
self.top = top
def display(self):
"""Prints complete Stack
"""
temp = self.top
print("{}".format(temp.value))
while(temp.next != None):
temp = temp.next
print("-------------")
print("{}".format(temp.value))
def convert(self, arr):
"""Converts an array into Stack
Parameters
----------
arr : list
An array
"""
for a in arr:
if self.top.value == None:
self.top.value = a
elif self.top.next == None:
self.top.next = Node(a)
else:
temp = self.top
while(temp.next != None):
temp = temp.next
temp.next = Node(a)
def push(self, value):
"""Pushes value to the top of Stack
Parameters
----------
value : int
Value to be pushed to Stack
"""
self.top = Node(value, self.top)
def pop(self):
"""Removes value from the top of Stack
Returns
-------
self.top.value : int
Value removed from stack
"""
self.top = self.top.next
return self.top.value
arr = [5, 6, 3, 3, 2, 1, 3, 21]
ll = Stack()
ll.convert(arr)
ll.push(56)
ll.push(4)
ll.push(32)
ll.pop()
ll.push(21)
ll.display() | true |
10b42f3d118663d02bc666f71097d80863af479a | curiousTauseef/210CT-Coursework | /Week-5/Question10.py | 2,973 | 4.28125 | 4 | """
210CT - Programming, Algorithms and Data Structures.
Question10.py
Purpose: A function which extracts the sub-sequence
of maximum length which is in ascending order.
Author : Rithin Chalumuri
Version: 1.0
Date : 02/12/16
"""
def maxSeq(arr):
"""
A function to extract the sub-sequence of maximum length which
is in ascending order.
Parameters:
arr (list); the sequence from which the sub-sequence of maximum length
should be extracted
Returns:
maximumSeq (list); the sub-sequence of maximum length in ascending order
Raises:
TypeError: If user enters an invalid sequence such as dictionaries.
"""
try:
if not(isinstance(arr,list)): #Checking if sequence is invalid or not
raise TypeError
maximumSeq = []
tempSeq = []
if len(arr) == 0 or len(arr) == 1: #if user provides empty or 1 element sequences
return arr
for i in range(len(arr)-1):
tempSeq.append(arr[i]) #add each element to temporary sequence
if arr[i+1]<arr[i]: #When the sequence breaks
if len(maximumSeq) < len(tempSeq):
maximumSeq = tempSeq
tempSeq = [] #Reset the temporary sequence
tempSeq.append(arr[-1]) #Adding the last element in arr, because loop stops at second last element
if len(maximumSeq) < len(tempSeq):
maximumSeq = tempSeq
return maximumSeq
except TypeError:
print("Error: Please provide a sequence of type 'list' and try again.")
# Testing maxSeq Function
if __name__ == "__main__":
test1 = [11,12,13,14,15,16,1,2,3,4,5,16,17,18]
test2 = [0.1,0.2,0.3,0.4,0.05,0.06,0.08,0.1,0.3]
test3 = ["g","h","i","j","k","l","a","b","c"]
test4 = [1,2,3,4,5,0.1,0.2,0.3,0.4,0.5]
tests = [test1,test2,test3,test4]
testresults = [[1,2,3,4,5,16,17,18],[0.05,0.06,0.08,0.1,0.3],["g","h","i","j","k","l"],
[1,2,3,4,5]]
count = 0
passed = 0
failed = 0
for test in tests:
print("Performing Test " + str(count+1) + "; input = "+str(test) + " of " + str(type(test)))
result = maxSeq(test)
if result == testresults[count]:
print("Function Output = " + str(result))
print("Test Passed.")
passed += 1
else:
print("Function Output = " + str(result))
print("Expected Output = " + str(testresults[count]))
print("Test Failed.")
failed += 1
count = count + 1
print("-"*60)
print("Total tests performed: "+str(count))
print("Tests passed: "+str(passed))
print("Tests failed: "+str(failed))
| true |
9e316922dc356c312869b920153a1ed871548dcf | Farizabm/pp2 | /week5/regex.py | 279 | 4.3125 | 4 | import re
txt=str(input())
def match(text):
# regex
pattern = '[A-Z]+[a-z]+$'
# searching pattern
if re.search(pattern, text):
print('Found a match!')
else:
print('Not matched!')
match(txt) | true |
1c228112dd9a4520fe5dae093c86a0e5d38b652d | desmater/dragon_cave | /Map.py | 2,685 | 4.21875 | 4 | #! /usr/bin/python
# --Filename: map.py--
# define the classes Map,
import Creatures
import Main
import random
FILE_VERSION = "0.3"
class Map(object):
"""
Defines the rooms for the game
"""
def __init__(self):
pass
def start_game(self, player):
self.start_room(player)
def start_room(self, player):
option_set = ("creeping", "fight")
gobblin = Creatures.Monster(50, "Gobblin", 3)
player.status_information()
print """
You are in the start room. In front of you is a small gobblin.
He don't look like he will let you go.
What you want to do? (Tipp: type in help for avalible options)
"""
while True:
user_action = raw_input("> ")
if user_action == "fight":
print "Let the fight beginn!"
Main.fight(gobblin, player)
break
elif user_action == "creeping":
if random.randrange(0,2) > 0:
print "He noticed you. Now you have to fight!"
Main.fight(gobblin, player)
break
elif user_action == "help":
Main.help(option_set)
else:
print "Unkown option! Try again!"
self.zentauer_room(player)
def zentauer_room(self, player):
option_set = ("speak", "fight")
zentauer = Creatures.Monster(70, "Zentauer", 15)
player.status_information()
print """
So you enterd the room of the zentauer. Normaly he's a nice guy.
But sometimes he just like to play football with the body of a human.
So don't make him angry!
"""
while True:
user_action = raw_input("> ")
if user_action == "speak":
if random.randrange(0,2) > 0:
print "Your lucky, he will let you pass!"
break
else:
print "It's not your day! He want's to fight you!"
Main.fight(zentauer, player)
break
elif user_action == "fight":
print "Let the fight beginn!"
Main.fight(zentauer, player)
break
elif user_action == "help":
Main.help(option_set)
else:
print "Unkown option! Try again!"
self.little_forest(player)
def little_forest(self, player):
print "a little forest"
player.status_information()
| true |
f54d5be4c1b2b2d5fe94bf15d4a95fa57370b085 | spesavento/Python | /Beginner_Python/if_statements.py | 2,767 | 4.3125 | 4 | 3 == 5
3 != 5
3 < 5
3 > 5
3 <=5
3 >= 5
#and, or, not
(3 < 4) and (5 > 4) #both conditions True
(3 < 4) or (3 > 5) #at least one condition True
not 3 < 2 #True, returns True if value is False
num = int(input('Enter a number: '))
if num < 0:
print(num, 'is negative')
elif num > 100:
print("It's greater than 100")
else:
print("It's between 0 and 100")
#Nesting if statements
snowing = True
temp = -1
if temp < 0:
print('It is freezing')
if snowing:
print('Put on boots')
print('Time for hot chocolate')
print('Bye')
age = 15
status = None #determine the status later using if statements
if (age > 12) and age < 20:
status = 'teenager'
else:
status = 'not teenager'
print(status)
#Shortened -- one line assignment
status = ('teenager' if age > 12 and age < 20 else 'not teenager')
print(status)
#note: 0, empty strings and None equate to False
test_0 = 0
if test_0:
print("It equated to True")
else:
print("It equated to False!")
if test_0 == 0:
print("It equated to True")
else:
print("It equated to False!")
#Exercises
#1. Test if an integer is positive or negative.
# Prompt the user to input a number (use the input() function). You can assume that the input will be some sort of number.
# Convert the string into an integer using the int() function.
# Now check whether the integer is a positive number or a negative number.
# You could also add a test to see if the number is Zero.
my_number = int(input("Please enter a number: "))
if my_number > 0:
print("The number is positive!")
elif my_number < 0:
print("The number is negative!")
else:
print("You entered 0!")
#now let's shorten it
my_number = int(input("Please enter a number: "))
num_type = ('Positive' if my_number > 0 else 'Negative' if my_number < 0 else "Zero")
print(num_type)
#2. Test if a number is odd or even
user_num = int(input("Please enter an integer: "))
if (user_num % 2) == 0:
print("Your number is even")
else:
print("Your number is odd")
#now let's shorten it
user_num = int(input("Please enter an integer: "))
print("Even" if (user_num % 2) == 0 else "Odd")
#3. Kilometres to Miles Converter
# Make sure user entered a positive number
# Verify that the input is a number; if it is not a number then do nothing;
# otherwise convert the distance to miles
try:
my_kilometers = int(input("Please enter a number: "))
except ValueError:
print("That's not an integer!")
if my_kilometers >= 0: #verify it's a positive numeric string
my_kilometers = int(my_kilometers) #convert to integer
my_miles = my_kilometers / 0.6214 #convert
print('The miles conversion is:', round(my_miles, 2), 'miles.')
else:
print("Try again. Please enter a positive number.") | true |
0036d105f8be26693c106c315dda17dc959fb7cb | meyerpa/Python | /Cracking the Coding Interview/Chapter 10 - Sorting and Searching/10_5.py | 1,175 | 4.1875 | 4 | """
10.5 Sparse Search
Given a sorted array of strings that is interspersed with empty strings, write
a method to find the location of a given string.
EXAMPLE
Input: ball, {"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""}
Output: 4
"""
def findString(x, string):
"""Returns the index string is in list x."""
high = len(x) - 1
low = 0
mid = (high + low) / 2
def findStringHelper(x, string, low, high):
# didn't find variable in list
if low > high:
return -1
check = (low + high) / 2 # variable to represent current check for empty strings
addEach = 1
while x[check] == "":
check += addEach
# go through lower
if check > high:
check = mid
addEach = -1
if check == 0:
return -1
# check if current same as string, if so return index
if x[check] == string:
return low
# if larger, search left half
elif x[check] > string:
return findStringHelper(x, string, low, check - 1)
# if lower, search right half
else:
return findStringHelper(x, string, check + 1, high)
| true |
094ff636486146a892d530f66cd5c481f4e35ab6 | meyerpa/Python | /Cracking the Coding Interview/Chapter 16 - Moderate/16_18.py | 466 | 4.1875 | 4 | """
16.18 Pattern Matching
You are given two strings, pattern and value. The pattern string consists of
just the letters a and b, describing a pattern within a string. For example,
the string catcatgocatgo matches teh pattern aabab (where cat is a and go is
b). It also matches patterns like a, ab, and b. Write a method to determine if
value matches pattern.
"""
def matchesPattern(string, pattern):
"""Returns whether string matches the pattern"""
| true |
3278a20d2a9420b1abfd7d8777e2c851ab11ab8b | ELWChadrock/python | /polyassignment.py | 1,507 | 4.1875 | 4 | class User:
name = "Rob"
email = "robbob@hotmail.com"
password = "123456"
def getLoginInfo(self):
entry_name = input("Enter your name: ")
entry_email = input("Enter your email: ")
entry_password = input("Enter your password: ")
if (entry_email == self.email and entry_password == self.password):
print("Welcome ya scrub, {}".format(entry_name))
else:
print("Bro you hacking?")
class Dude(User):
dude_age = 21
bro_status = "Major"
def getLoginInfo(self):
entry_name = input("Enter your name: ")
entry_email = input("Enter your email: ")
entry_status = input("What's your bro status: ")
if (entry_email == self.email and entry_status == self.bro_status):
print("Suh dude {}".format(entry_name))
else:
print("You sketch bruh")
class Friend(User):
friend_age = 30
friend_type = "Super"
def getLoginInfo(self):
entry_name = input("Enter your name: ")
entry_email = input("Enter your email: ")
entry_status = input("How much of a friend are you? ")
if (entry_email == self.email and entry_status == self.friend_type):
print("You're such a nice friend {}".format(entry_name))
else:
print("Are you really my friend?")
customer = User()
customer.getLoginInfo()
bruh = Dude()
bruh.getLoginInfo()
friend = User()
friend.getLoginInfo()
| true |
78bcc96f25e014a2acc7685934c6ed90ac7ce99c | Femi-lawal/data-structures-and-algorithms | /python/questions/apartment_hunting.py | 2,971 | 4.21875 | 4 | # You're looking to move into a new apartment on specific street, and you're
# given a list of contiguous blocks on that street where each block contains an
# apartment that you could move into.
# You also have a list of requirements: a list of buildings that are important
# to you. For instance, you might value having a school and a gym near your
# apartment. The list of blocks that you have contains information at every
# block about all of the buildings that are present and absent at the block in
# question. For instance, for every block, you might know whether a school, a
# pool, an office, and a gym are present.
# In order to optimize your life, you want to pick an apartment block such that
# you minimize the farthest distance you'd have to walk from your apartment to
# reach any of your required buildings.
# Write a function that takes in a list of contiguous blocks on a specific
# street and a list of your required buildings and that returns the location
# (the index) of the block that's most optimal for you.
# If there are multiple most optimal blocks, your function can return the index
# of any one of them.
# Sample Input
# blocks = [
# {
# "gym": false,
# "school": true,
# "store": false,
# },
# {
# "gym": true,
# "school": false,
# "store": false,
# },
# {
# "gym": true,
# "school": true,
# "store": false,
# },
# {
# "gym": false,
# "school": true,
# "store": false,
# },
# {
# "gym": false,
# "school": true,
# "store": true,
# },
# ]
# reqs = ["gym", "school", "store"]
# Sample Output
# 3 // at index 3, the farthest you'd have to walk to reach a gym, a school, or a store is 1 block; at any other index, you'd have to walk farther
# Hints
# For every block, you want to go through every requirement, and for every requirement, you want to find the closest other block with that requirement (or rather, the smallest distance to another block with that requirement). Once you've done that for every requirement and for every block, you want to pick, for every block, the distance of the farthest requirement. You can do this with three nested "for" loops.
# Hint 2
# Is there a way to optimize on the solution mentioned in Hint #1 (that uses three nested "for" loops) by precomputing the smallest distances of every requirement from every block?
# Hint 3
# For every requirement, you should be able to precompute its smallest distances from every block by doing two simple passes though the array of blocks: one pass from left to right and one pass from right to left. Once you have these precomputed values, you can iterate through all of the blocks and pick the biggest of all the precomputed distances at that block.
# Optimal Space & Time Complexity O(br) time | O(br) space - where b is the number of blocks and r is the number of requirements | true |
54750611ee9016716f154e3c942168ea745e1227 | Darrenrodricks/w3resourceBasicPython1 | /w3schoolPractice/secondConverter.py | 528 | 4.28125 | 4 | # Write a Python program to convert seconds to day, hour, minutes and seconds.
s = float(input("Please enter a given amount of seconds: "))
# days = s /86400
# hours = s / 3600
# minutes = s / 60
#
# print("{} seconds, equates to\n{} days\n{} hours\n{} minutes".format(s, days, hours, minutes))
days = s // 86400
time = s % 86400
hours = time // 3600
time2 = s % 3600
minutes = time2 // 60
seconds = s % 60
print("{} seconds, equates to {} days, {} hours, {} minutes and {} seconds".format(s, days, hours, minutes, seconds))
| true |
95c396dfe27f61134c67e6b57a9fc05864e59990 | Darrenrodricks/w3resourceBasicPython1 | /w3schoolPractice/squareRoot.py | 289 | 4.53125 | 5 | # Write a Python program to calculate the hypotenuse of a right angled triangle.
from math import sqrt
print("Give the values of the shorter sides of the triangles")
a = int(input("side 1: "))
b = int(input("side 2: "))
c = sqrt((a **2) + (b **2))
print("Your hypotenuse is {}".format(c))
| true |
ddb65adbefe3d6182750a37fd34417ea2478f61b | mephi007/PythonL1 | /Assignment6/Assignment6a.py | 585 | 4.65625 | 5 | # Write a program to read string and print each character separately.
# a) Slice the string using slice operator [:] slice the portion the strings to create a sub strings.
#asking user to give a string for the slicing operation
str = input("enter a String")
start = eval(input("enter start of the substring")) #starting of the substring
end = eval(input("enter end of the substring, that will be excluded")) #ending of the substring
dif = eval(input("enter difference between characters, enter 1, if you do not want so"))
print(str[start:end:dif]) #printing the substring | true |
8587aca540367cf454fe2de64250e61acd7cb2a7 | mephi007/PythonL1 | /Assignment6/Assignment6c.py | 338 | 4.5 | 4 | # Write a program to read string and print each character separately.
# c) Read string 2 and concatenate with other string using + operator.
#asking user to give a string for the slicing operation
str = input("enter a String")
str1 = input("enter string again")
#printing string1 concating with string2
print(str+str1)
| true |
5607bd240189359a1a1d2e84a6466c2c9db49d2e | mephi007/PythonL1 | /Assignment14.py | 1,932 | 4.375 | 4 | # Write a program to create two list A & B such that List A contains Employee Id,
# List B contain Employee name (minimum 10 entries in each list) & perform following operation
#Print all names on to screen
#Read the index from the user and print the corresponding name from both list
#Print the names from 4th position to 9th position
#Print all names from 3rd position till end of the list
#Repeat list elements by specified number of times (N- times, where N is entered by user)
#Concatenate two lists and print the output.
#Print element of list A and B side by side.(i.e. List-A First element, List-B First element)
#create two list A & B such that List A contains Employee Id,
# List B contain Employee name
listA = [2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014]
listB = ["sumit", "sam", "sameer", "mayank", "naman", "vishal", "deepti", "sagarika", "vinod", "raju"]
#Print all names on to screen
for i in range(10):
print(listB[i])
#Read the index from the user and print the corresponding name from both list
x = eval(input("Enter a index whose detail you want to see"))
print(listA[x]," ",listB[x])
#Print the names from 4th position to 9th position
print("printing names from 4th position to 9th position")
print(listA[4:9]," ",listB[4:9])
#Print all names from 3rd position till end of the list
print("printing names from 3rd position till the end")
print(listA[3::]," ",listB[3::])
#Repeat list elements by specified number of times (N- times, where N is entered by user)
y = eval(input("Enter how many times do you want to repeat list elements"))
print(listA*y, " ", listB*y)
#Concatenate two lists and print the output.
listConcat = listA+ listB
print("Concated list :: ", listConcat)
#Print element of list A and B side by side.(i.e. List-A First element, List-B First element)
print("print elements of both the list side by side")
for i in range(10):
print(listA[i], " ", listB[i])
| true |
17a0bbe8d8aee9b6f9815e53e2b9d91da908b587 | Manan861/class98 | /function.py | 290 | 4.25 | 4 | def countWords():
fileName=input("Type in the file name: ")
WordCount=0
file=open(fileName,'r')
for line in file:
words=line.split()
WordCount=WordCount+len(words)
print("Number of words in the file are: " )
print(WordCount)
countWords()
| true |
342f1310298f8b6059d6dab4d9da1e205c7866f1 | amitfld/amitpro1 | /if_targilim/tar3.py | 312 | 4.15625 | 4 | age = int(input('enter age: ')) #מקבל גיל ובודק באיזה קבוצת גילאים הוא: ילד, מבוגר, זקן
if(age < 0):
print('error')
elif (0 <= age <= 18):
print('child')
elif 19 <= age <= 60:
print('adult')
elif 61 <= age <= 120:
print('senior')
else:print('error')
| false |
41d9680bd3e9ce3c93dd10f6907ad5cbb545b402 | MohamedRamadan96/Python-Problem-6 | /Problem 6.py | 293 | 4.15625 | 4 | # Question 6 : Given a list of numbers,
# Iterate it and print only those numbers which are divisible of 5
def find_Dividable(numberList):
for num in numberList:
if (num % 5 == 0):
print(num)
numList = [10,20,30,40,50,44,22,14,23,96]
find_Dividable(numList) | true |
52e57d4a5f1823f35fe57e40f1d964cc8a010c2d | trevorwjames/DS-Unit-3-Sprint-2-SQL-and-Databases | /Study Guide/study_part1.py | 1,009 | 4.1875 | 4 | """
Study guide practicing importing data to sqlite file
"""
import sqlite3
# directions
sl_conn = sqlite3.connect('study_part1.sqlite3')
sl_curs = sl_conn.cursor()
"""
student - string
studied - string
grade - int
age - int
sex - string
"""
sl_curs.execute("DROP TABLE IF EXISTS students;")
sl_conn.commit()
create_table = """
CREATE TABLE students (
student TEXT,
studied TEXT,
grade INT,
age INT,
sex TEXT
);
"""
sl_curs.execute(create_table)
sl_conn.commit()
students = [
('Lion-O', 'True', 85, 24, 'Male'),
('Cheetara', 'True', 95, 22, 'Female'),
('Mumm-Ra', 'False', 65, 153, 'Male'),
('Snarf', 'False', 70, 15, 'Male'),
('Panthro', 'True', 80, 30, 'Male')
]
for student in students:
insert = f"""
INSERT INTO students (student, studied, grade, age, sex)
VALUES {student};"""
sl_curs.execute(insert)
sl_conn.commit()
sl_curs.execute('SELECT * FROM students;')
results = sl_curs.fetchall()
print(results)
| false |
a77fab309a482d95d2009590a9820b2b707a44e0 | varshithayeslur/internship | /labquestions/interrogative.py | 227 | 4.15625 | 4 | while(True):
inp = input("enter the string")
if inp =='done':
break
elif inp.endswith ("?"):
print(f"the string{inp} is interrogative")
else:
print(f"the string{inp} is assertive") | true |
48204c5c848f5ecc932ad0ab9b99cda03c82c4e5 | yknyim/while-loop-git | /square2.py | 223 | 4.15625 | 4 |
stars = 0
my_stars = int(input("How big is the square? "))
while stars < my_stars:
print('*' * my_stars)
stars += 1
# stars = int(input("How big is the square? "))
# for i in range(stars):
# print('*' * stars) | false |
4ff8a6115710b55be6adb075259e9e1fce1f06ab | JlucasS777/Aprendendo-Python | /Aprendendo Python/cursopythonudamy/aula2.py | 379 | 4.25 | 4 | #print (1+2)
#print('luiz','Otavio')
#print('luiz','Otavio',sep='<<<<<')# A função sep serve para substituir o espaço atribuido automaticamente na vírgulo por qualquer outra coisa que eu colocar
#print('luiz','e','Otavio',sep='-',end='=')#A função end coloca o que eu indicar no final do programa
print('824.176.070-18')
print('824','176','070',sep='.',end='-'
'18')
| false |
f6c9046cb45883f6c109fb43b9aecb6c8d70d5fe | jcoumont/challenge-card-game-becode | /utils/player.py | 2,549 | 4.15625 | 4 | import random
from typing import List
from utils.card import Card
class Player:
"""Class defining a player characterized by:
- his name
- his list of cards to play - cards
- his list of history card (played card) - history
"""
history: List[Card]
cards: List[Card]
def __init__(self, name: str, interactive: bool = False):
"""
Constructor
:param name : A str that is the player name
:param interactive : A bool that indicate if the player
chooses himself the card to play
"""
self.name = name
self.history = []
self.cards = []
self.interactive = interactive
def __str__(self):
return f"{self.name}"
def __repr__(self):
return f"{self.name}"
def play(self) -> Card:
"""
Function that will play a random card or ask the player
to choose it if interactive is True.
:return A Card that is the played card
"""
# Choose the card to play
if self.interactive:
# Display all available card
for i in range(1, len(self.cards) + 1):
print(f"{i} : {self.cards[i-1]}")
while True:
try:
in_choice = int(input("Which card to play ? (number)"))
played_card = self.cards[in_choice - 1]
break
except Exception:
pass
else:
played_card = random.choice(self.cards)
# Update the history and the cards still to play
self.history.append(played_card)
self.cards.remove(played_card)
# Print of the play
print(f"{self.name} {self.turn_count} played: {played_card}")
return played_card
def add_card(self, card: Card):
"""
Function that will add a card in the player's hand (cards)
:param card : a Card that will be added in the player's hand
"""
self.cards.append(card)
@property
def turn_count(self) -> int:
"""
Property that will give the count of played turns
:return: an int that is the count of played turns
"""
return len(self.history)
@property
def number_of_cards(self) -> int:
"""
Property that will give the amount of cards in the player's hand
(cards to play)
:return: an int that is the amount of cards in the player's hand
"""
return len(self.cards)
| true |
740535f64286d7fbbef838448c1cf568a86c9301 | rutujamadhure/Data-Structures | /circularQueue_linkedlist.py | 1,655 | 4.21875 | 4 | #Circular Queue using Linked List
#self.front points to the first node and self.rear points to the last node.(so, self.rear.next=self.front) The last node has the address of first node stored in 'next'.
class Node:
def __init__(self,data):
self.data=data
self.next=None
class Circular_queue:
def __init__(self):
self.front=None
self.rear=None
def enqueue(self,data):
if self.front==self.rear==None:
self.front=self.rear=Node(data)
else: #insert at rear end
new_node=Node(data)
new_node.next=self.rear.next #or new_node.next=self.front
self.rear.next=new_node
self.rear=new_node
def dequeue(self):
if self.front==self.rear==None:
print('Queue is empty')
return None
value=self.front.data
if self.front==self.rear:
self.front=self.rear=None
else:
self.rear.next=self.front.next
self.front=self.front.next
return value
def traverse(self):
if self.front==self.rear==None:
print('queue is empty')
return None
elif self.front==self.rear:
print(self.front.data)
else:
temp=self.front
while True:
print(temp.data,end=" ")
temp=temp.next
if temp==self.front:
break
Q=Circular_queue()
Q.enqueue(4)
Q.enqueue(8)
Q.enqueue(3)
Q.enqueue(9)
Q.dequeue()
Q.traverse()
| true |
3914fe9cae740a0faa368eefa10fd7b46ef10bd7 | jamesnorth/project_euler | /python/prob1.py | 468 | 4.28125 | 4 |
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we
get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
multiples = []
for n in range(1000):
if n % 3 == 0 or n % 5 == 0:
multiples.append(n)
print multiples
acc = 0
for val in multiples:
acc = acc + val
print acc
### OR #####
# print sum(x for x in xrange(1, 1000) if x%3==0 or x%5==0)
| true |
4ad4625b41159e61880a47a5f96a80cddbc84109 | vova0808/KPI-Python-tasks | /lab4_3.py | 1,098 | 4.125 | 4 | """ This program takes input as a command line argument.
Input is a string, that consists of openings and
closings parenthesees. If input containing right sequence of parenthesees,
program return "YES", else return "NO"
"""
import sys
user_input = sys.argv[1]
count = 0
#boolean variable for tracking if quantity of openings is in respect of quantity of closings
matched = True
#iterate over string and counting both opening and closing parenthesis
for i in user_input:
if i == "(":
count += 1
elif i == ")":
count -= 1
# if count is less that 0 it means that quantity of closing parenthesis are greater than opening, so matched will be False
if count < 0:
matched = False
#check if we have opening bracket at the start of string and closing in the end.
if user_input[0] == ")" or user_input[-1] == "(":
matched = False
#if quantity of closings and closings parenthesis are equal and matched, return True
if count == 0 and matched == True:
print "YES"
else:
print "NO"
| true |
550982d8dd41b51811249ae07611de16715db3ae | Sakhile08/python_pre_bootcamp_challenges | /Task_8.py | 214 | 4.21875 | 4 | def convert_num_into_time(num):
hour = num//60
hour1 = num%60
minute = hour1%60
print(hour, "hours", minute, "minutes")
num = int(input("Enter the number: "))
convert_num_into_time(num)
| true |
07a2a654569074f4292401debd3f89d5be5ed64c | AnoopMasterCoder/python-course-docs | /9. Chapter 9/09_pr11.py | 237 | 4.15625 | 4 | import os
oldname = input("Enter the name of the file to rename")
newname = input("Enter the new name of the file")
with open(oldname, 'r') as f:
text = f.read()
with open(newname, 'w') as f:
f.write(text)
os.remove(oldname)
| true |
b1065fb96f872b798b88dacadc3dafb754035b61 | AnoopMasterCoder/python-course-docs | /3. Chapter 3/04_string_functions.py | 263 | 4.1875 | 4 | myStr = "abcdefghijklmnopqrstuvwxyzaaab"
print(len(myStr))
print(myStr.endswith("xyz"))
print(myStr.startswith("abcd"))
print(myStr.count('ab'))
myStr = "my name is harry name"
print(myStr.capitalize())
print(myStr.find("name"))
print(myStr.replace("name", "date")) | false |
5e54db6a29767f63886b463ab791ed0b3418b9ec | JSisques/Udemy-Python-The-Art-Of-Coding | /Challenge 06 - Grade Sorter App/Main.py | 793 | 4.125 | 4 | import math
print("Welcome to the Grade Sorter App")
print()
firstGrade = int(input("What is your first grade (0-100): "))
secondGrade = int(input("What is your second grade (0-100): "))
thirdGrade = int(input("What is your third grade (0-100): "))
fourthGrade = int(input("What is your fourth grade (0-100): "))
print()
grades = [firstGrade, secondGrade, thirdGrade, fourthGrade]
print("Your grades are: " + str(grades))
print()
grades.sort(reverse=True)
print("Your grades from the highest to lowest are: " + str(grades))
print("The lowest grades now will be dropped.")
removedValue = grades.pop()
print("Removed value: " + str(removedValue))
removedValue = grades.pop()
print("Removed value: " + str(removedValue))
print()
print("Your grades are " + str(grades))
print("Nice work!")
| true |
b3e3493755d04586feb4040209ea7dc552f3fdb6 | RatanjotPabla/Python- | /Assignments/Repetition2/forSumSqaures.py | 1,055 | 4.125 | 4 | #Name: Ratanjot Pabla
#StudentNo: 32700826
#Date_Submitted: October 26, 2018
#File_Name: forSumSquares.py
#Teacher_Name: Mr. Sarros
#Purpose: This program will output the result for the sum of all the numbers from 1 to 100 within a 'for' loop. Each output should begin on a newline.
#--------------------------------------------------------------------------------------------------------------------------------------------------------------
total = 0 #The variable called total is assigned the value of 0.
for count in range(1,101): #The 'for' loop. The condition being for count in range of (1,101) which will take the following line and do it from 1 to 100.
total = (total+ count**2) #The variable total is then equal to count squared plus the previous total. Adding the total with the count squared is what makes it
#the program to calculate the sum.
print(total) #This prints all sums from 1 to 100, with each count being on a new line.
| true |
4d9444b60bd916a46ffbef6acf5b7e64280de8de | RatanjotPabla/Python- | /Assignments/Python Selection 5/selectionAssignment5.py | 2,895 | 4.5 | 4 | #Name: Ratanjot Pabla
#StudentNo: 32700826
#Date_Submitted: October 17, 2018
#File_Name: selectionAssignment5.py
#Teacher_Name: Mr. Sarros
#Purpose: This program is used to help the driver decide if they will need to get gas or if they will
#make it with the amount they have left. We must calculate the tank capacity, gas gauge and the highway MPG to solve for the total
#miles they can travel or require and the gallons they have left or rquire to travel the full 200 miles until the next gas station.
tank_Capacity = float(input("What is the capacity of the gas tank, in gallons?"))
#This will prompt the user for their gas tank capacity in gallons.
gas_Gauge = float(input("What is the indication of your gas gauge in decimal? (Ex: 50% is equal to 0.5)"))
#This will prompt the user for their gas gauge in decimal.
highway_MPG = float(input("What is the miles per gallon your car achieves on the highway?"))
#This will prompt the user for their MPG of their car they achieve on the highway.
miles_Total = (highway_MPG*tank_Capacity*gas_Gauge) #This tells you how many miles you can travel in total
miles_Left = (miles_Total-200) #This does the calculation of the number of miles you have left after travelling the full 200 miles.
miles_Required = (200 - miles_Total) #This does the calculation of the number of miles you need more to reach the full 200 milles.
gallons_Left = (tank_Capacity-(200/gas_Gauge/highway_MPG))
#This will do the calculation of finding out the number of gallons you have left after travelling the full 200 miles.
gallons_Required = ((200/gas_Gauge/highway_MPG)-tank_Capacity)
#This will do the calculation of the number of gallon they require more to reach the full 200 miles.
if miles_Total>= 200:
print("""Safe to proceed. You can cross the 200 miles with %.2f remaining miles to travel in the tank. You also have %.2f gallon(s) left"""%
(miles_Left,gallons_Left))
#If the car can travel the full 200 miles and and have gas left over, this will print out that it is safe to proceed. It will also print out that
#the remaining of miles they have left that they can travel until they have an empty tank and the number of galllons they have left over.
else:
print("""Get gas. You will be able to travel only %i miles and will need enough gas to travel another %.2f until the next gas station. You will
need another %.2f to reach the full 200 miles."""%(miles_Total,miles_Required,gallons_Required))
#If the car can not travel the full 200 miles, it will print out to the user that they must get gas. It will also print out the number of miles they
#are short by to reach the full 200 miles and also the number of gallons they require to reach the full 200 miles.
| true |
c2419bb0c54ada972a37cd7d3b53f6b31ac50217 | RatanjotPabla/Python- | /Assignments/Repetition1/smallLargeAvg.py | 2,625 | 4.375 | 4 | #Name: Ratanjot Pabla
#StudentNo: 32700826
#Date_Submitted: October 25, 2018
#File_Name: smallLargeAvg.py
#Teacher_Name: Mr. Sarros
#Purpose: This program is used to figure out the smallest, largest and the average number in the collection of numbers the user inputs. First, the user is
#prompted to input the amount of numbers that they will like to input into the program. Then the user will be able to input "x" amount of numbers
#and have any value to it between 0-1000000000. Then once the user has finished inputting their collection of numbers, it will output the smallest
#number, largest number and the average throughout all the numbers in the collection.
N_Value = int(input("How many numbers would you like to have?")) #Prompts the user to input the 'x' amount of numbers they want in their collection.
counter,total = 0,0 #The variables called 'counter' and 'total' are both assigned the value of 0.
smallest,largest = 1000000000,0 #The variables called 'smallest' is assigned the value of 1000000000 and the variable 'largest' is assigned the value of 0.
while counter<N_Value: #While the counter is less than the amount of numbers in the collection
counter+=1 #The counter counts how many numbers the user has inputted, by increasing the counter by 1 each time a number is inputted into the program.
value = float(input("Enter a number:")) #Prompts the user to input the value of their number which will be a part of their collection of numbers.
total+= value #The total counter will continuously add the value of the number being inputted from value1 into their collection.
if value<smallest: #If the value is smaller than 1000000000, then it will replace the number in "value" and assign it into the variable "smallest."
smallest = value
if value>largest: #If the value is larger than 0, then it will replace the number in "value" and assign it into the variable "largest."
largest = value
average = (total/N_Value) #This will find the average by adding the value of all the numbers in the collection and dividing it by the number in "N_Value."
print("""The smallest number in your collection of numbers is %.2f. The largest number in your collection of numbers is
%.2f. The average of your list of numbers is %.3f"""%(smallest, largest, average))
#Finally, the program will output the smallest, largest, and the average from the collection of numbers inputted by the user.
| true |
10be6f1645ed4324a87cc047b739a675f749b95b | alextai1998/PythonGameProg | /Semester 1/Python/Python Final Project/Part 1 - CodinGame/mimeType.py | 780 | 4.25 | 4 | """
MIME types are used in numerous internet protocols to associate a media type (html, image, video ...)
with the content sent. The MIME type is generally inferred from the extension of the file to be sent.
This program makes it possible to detect the MIME type of a file based on its name.
"""
mimes = {} # Generate hash table
n = int(input()) # Entries amount
q = int(input()) # Data amount
for i in range(n):
mime = input().split()
mimes[mime[0].lower()] = mime[1] # Assign input data into dict; Case sensitive
for j in range(q):
fname = input().split(".") # Split with period, list
if len(fname) != 1: # Determine length of file name list
print(mimes.get(fname[-1].lower(), "UNKNOWN")) # Case sensitive
else:
print("UNKNOWN")
| true |
24fa29c99b84d80adc58b3debfd23103718bc2ff | alextai1998/PythonGameProg | /Semester 1/Python/pluralizer.py | 1,021 | 4.15625 | 4 | """
This program pluralizes the noun entered...or at least attempts to.
"""
numbers = {1: "One ", 2: "Two ", 3: "Three ", 4: "Four ", 5: "Five ", 6: "Six ", 7: "seven ", 8: "eight ", 9: "nine ", 10: "ten "} # Text version of numbers
exceptions = {"man": "men", "fish": "fish", "roof": "roofs", "focus": "foci", "child": "children", "person": "people"} # Lists out common exceptions
noun = input("Enter a noun! ")
num = int(input("How many? "))
if 1 < num <= 10:
if noun in exceptions:
print(numbers[num] + exceptions[noun])
exit()
elif noun[-1:] == "a" or noun[-1:] == "i" or noun[-1:] == "o" or noun[-1:] == "u" or noun[-1:] == "s" or noun[-1:] == "x" or noun[-1:] == "z" or noun[-1:] == "ch" or noun[-1:] == "sh":
noun += "es"
elif noun[-1:] == "f":
noun = noun.replace("f", "ves")
elif "oo" in noun:
noun = noun.replace("oo", "ee")
elif noun[-1:] == "y":
noun = noun.replace("y", "ies")
else:
noun += "s"
print(numbers[num] + noun)
| false |
1a03d7dc68c39ed2a73dd8371e4242e4f1533bde | alextai1998/PythonGameProg | /Semester 1/Python/cypher.py | 1,250 | 4.28125 | 4 | def get_alphabet():
"""
This function returns the alphabet in a list
:return: list
"""
alphabet = [chr(97+a) for a in range(26)]
return alphabet
def cypher_alphabet(key="money"):
"""
Creates the cypher alphabet with the key provided
:param key: string
:return: dictionary
"""
alphabet = get_alphabet()
cypher = list(key) + [a for a in alphabet if a not in key]
cypher_d = {a: c for a, c in zip(alphabet, cypher)}
return cypher_d
def encrypt(msg, key="money"):
"""
Encrypts the input msg using the key provided
:param msg: string
:param key: string
:return encrypted_msg: string
"""
# Cypher the alphabet
cypher = cypher_alphabet(key)
encrypted_msg = ""
for s in msg:
encrypted_msg += cypher.get(s, s)
return encrypted_msg
def decrypt(encrypted_msg, key="money"):
"""
Decrypts the input msg with the key provided
:param encrypted_msg: string
:param key: string
:return msg: string
"""
# Cypher the alphabet
cypher = cypher_alphabet(key)
reversed_cypher = {v: k for k, v in cypher.items()}
msg = ""
for s in encrypted_msg:
msg += reversed_cypher.get(s, s)
return msg
| true |
ed515c90c3c2a5dbcd62d490ca247c1caef4cc8d | alextai1998/PythonGameProg | /Semester 1/Python/Python Final Project/Part 1 - CodinGame/theDescent.py | 1,037 | 4.28125 | 4 | """
This program finds the highest mountain out of a list of mountains.
The while loop represents the game.
Each iteration represents a turn of the game
where you are given inputs (the heights of the mountains)
and where you have to print an output (the index of the mountain to fire on)
The inputs you are given are automatically updated according to your last actions.
"""
# game loop
while True:
heights = [] # generates a list first
for i in range(8): # iterate through 8 indices
mountain_h = int(input()) # represents the height of one mountain.
heights.append(mountain_h) # append the data inputted by the game into the list
hello = list(enumerate(heights)) # creates a list with heights and the index
newList = [(v, k) for k, v in hello] # switch the index with the heights
newList.sort() # sort the new list
shootList = [v for k, v in newList] # remove the heights to generate a list of indices
print(shootList[7]) # The index of the mountain to fire on.
| true |
07040c757fe0ee5061fd8522582e285e5eb9ea0f | mateuscorreiamartins/Curso-de-Python | /PythonExercicios/ex026.py | 499 | 4.125 | 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 a primeira vez;
# Em que posição ela aparece a última vez.
frase = input('Digite uma frase: ').strip()
print('A letra A aparece {} vezes. '.format(frase.upper().count('A')))
print('A letra A aparece a primeira vez na posição {}.'.format(frase.upper().find('A') + 1))
print('A letra A aparece a última vez na posição {}.'.format(frase.upper().rfind('A') + 1))
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.