blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
e9ac9d13981164b604ec49de918ed89047d8dc1a | ttund21/LearningPython | /PythonBrasilExercicios/ExercicioComStrings/Respostas/14_Questao.py | 576 | 3.984375 | 4 | def leet(palavra):
leet ={'A':'4', 'B':'13', 'C':')', 'D':'[)', 'E':'3', 'F':'|=', 'G':'6', 'H':'|-|', 'I':'|', 'J':']', 'K':'|<', 'L':'1', 'M':'|Y|', 'N':'/\/', 'O':'0', 'P':'|>',
'Q':'0,', 'R':'|2', 'S':'5', 'T':'7', 'U':'[_]', 'V':'\/', 'W':'\\v/', 'X':'}{', 'Y':'`/', 'Z':'2'}
listword = list(pal... |
80e16bb0e5606e4c0af187f28cebb94a42a70344 | ttund21/LearningPython | /PythonBrasilExercicios/ExercicioComStrings/Respostas/3_Questao.py | 195 | 3.96875 | 4 | """3
3. Nome na vertical. Faça um programa que solicite o nome do usuário e imprima-o na vertical.
F
U
L
A
N
O
"""
nome = input('Nome: ')
for i in nome:
print(f'{i.upper()}')
|
3c5b93ada3494080bb38780c9b84ac31b3e48f0f | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaDeRepeticao/Respostas/10_Questao.py | 244 | 4.09375 | 4 | # 10. Faça um programa que receba dois números inteiros e gere os números inteiros que estão no intervalo compreendido por eles.
num1 = int(input('Número 1:'))
num2 = int(input('Número 2:'))
for i in range(num1 + 1, num2):
print(i)
|
c5e14dd3bb3bd198c4d732330af9032436e6e1e8 | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaDeDecisao/Respostas/2_Questao.py | 203 | 4.15625 | 4 | # 2. Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo.
valor = int(input('Escreva uma valor: '))
if valor < 0:
print('Negativo')
else:
print('Positivo')
|
48764775256fb267fb43b3ec171dc5f64dd64b9f | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaDeRepeticao/Respostas/8_Questao.py | 232 | 4.03125 | 4 | # 8. Faça um programa que leia 5 números e informe a soma e a média dos números.
num = []
for i in range(5):
num.append(float(input(f'{i + 1} Número: ')))
print(f'\nSoma: { sum(num) }, Média: { sum(num) / len(num) } ')
|
6b74aacd9ccf2727774007babf9fbceac71bb7f0 | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaDeDecisao/Respostas/21_Questao.py | 1,237 | 3.71875 | 4 | # 21. Faça um Programa para um caixa eletrônico. O programa deverá perguntar ao usuário a valor do saque e depois informar quantas notas de cada valor serão fornecidas. As notas disponíveis serão as de 1, 5, 10, 50 e 100 reais. O valor mínimo é de 10 reais e o máximo de 600 reais. O programa não deve se preocupar com a... |
763d5dea7341516acec1a39d9fc06c5cd42cd977 | ttund21/LearningPython | /ATMcPython/Parte_I/Cap2_ControleDeFluxo/Programs/Import/login.py | 1,105 | 3.71875 | 4 | from sys import exit
luser = ''
lpass = ''
user= 'admin'
passwd = 'admin'
while True:
chance = 6
print('WeLcOmE tO My FiRsT pRoGrAm!\n')
print('1 - Create Account\n2 - Sign In\n3 - Exit')
resp = input('>>> ')
if resp == '1':
print('\nWelcome to account creator. Now put your username and ... |
25eaf1a6004b1a4d2cba27e87b0ea1050906bc57 | ttund21/LearningPython | /Exemplos/Programas/AnalizadorCaractere.py | 5,180 | 4.0625 | 4 | # ------------------------------------------ Funções ------------------------------------------
def tratamento_letra(arq): # Vai tratar o arquivo removendo espaços e quebra linhas
registro = arq.replace(" ", "").replace("\n", "")
return registro
def tratamento_palavra(arq): # Vai tratar o arquivo removendo ... |
7f9f05b42746ca2c4e93663e4be9feddc9ec5a9f | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaDeDecisao/Respostas/27_Questao.py | 1,090 | 3.953125 | 4 | # 27. Uma fruteira está vendendo frutas com a seguinte tabela de preços:
# Até 5 Kg Acima de 5 Kg
# Morango R$ 2,50 por Kg R$ 2,20 por Kg
# Maçã R$ 1,80 por Kg R$ 1,50 por Kg
#Se o cliente comprar mais de 8 Kg em frutas ou o valor total da compra u... |
f6307d2ea1bf9199b1693920cfc303f56eeda2ea | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaDeRepeticao/Respostas/26_Questao.py | 773 | 3.859375 | 4 | # 26. Numa eleição existem três candidatos. Faça um programa que peça o número total de eleitores. Peça para cada eleitor votar e ao final mostrar o número de votos de cada candidato.
cand1 = 0
cand2 = 0
cand3 = 0
numEle = int(input('Número de eleitores: '))
for i in range(numEle):
while True:
eleitor = ... |
a59d97454c8043a8789c33e946f767cbc27edbba | ttund21/LearningPython | /ATMcPython/Parte_I/Cap5_DicionariosEstruturacaoDeDados/ProjetoPratico/InventarioJogoFantasia/inventory.py | 324 | 3.953125 | 4 | def displayInventory(inventory):
total = 0
print('Inventory:')
for item, amount in inventory.items():
total += amount
print(f'{amount} {item}')
print(f'Total number of items: {total}')
inventory = {'rope':1, 'torch':6, 'gold coin':42, 'dagger':1, 'arrow':12}
displayInventory(inventor... |
99555fece465e48fefe1700a320defc59fc6aa3b | ttund21/LearningPython | /PythonBrasilExercicios/ExercicioComStrings/Respostas/10_Questao.py | 1,000 | 3.921875 | 4 | # 10. Número por extenso. Escreva um programa que solicite ao usuário a digitação de um número até 99 e imprima-o na tela por extenso.
unidade = {1:'Um', 2:'Dois', 3:'Três', 4:'Quatro', 5:'Cinco', 6:'Seis', 7:'Sete', 8:'Oito', 9:'Nove', 10:'Dez',
11:'Onze', 12:'Doze', 13:'Treze',14:'Quatorze', 15:'Quinze', 16:... |
359b6ee86ec9bd325026ae0121a00981f894171f | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaSequencial/Respostas/14_Questao.py | 831 | 3.59375 | 4 | # 14. João Papo-de-Pescador, homem de bem, comprou um microcomputador para controlar o rendimento diário de seu trabalho. Toda vez que ele traz um peso de peixes maior que o estabelecido pelo regulamento de pesca do estado de São Paulo (50 quilos) deve pagar uma multa de R$ 4,00 por quilo excedente. João precisa que vo... |
a89b7beb4621c92bb11042bc38315ec76cf2f519 | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaDeRepeticao/Respostas/11_Questao.py | 248 | 4.125 | 4 | # 11. Altere o programa anterior para mostrar no final a soma dos números.
num1 = int(input('Número 1: '))
num2 = int(input('Número 2: '))
soma = 0
for i in range(num1 + 1, num2):
soma += i
print(i, end=' ')
print(f'\nSoma: {soma}')
|
307061bebf37ea094098d3a33f3cacb6342a8be6 | ttund21/LearningPython | /Tkinter/Arquivos/ListBox.py | 855 | 3.765625 | 4 | from tkinter import Tk, Listbox, Button
# Frame
root = Tk()
root.resizable(False, False)
root.title("List Box")
# Funções
def limpar_lista(li):
li.delete(0, "end")
def exibir_item(li):
print(li.get("active"))
# List Box
lista = Listbox(root, selectmode="extended") # extended faz selecionar mais de um item
... |
6045c40188c97e3a94e6d1c8785967c9e8062210 | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaDeRepeticao/Respostas/35_Questao.py | 401 | 3.9375 | 4 | # 35. Encontrar números primos é uma tarefa difícil. Faça um programa que gera uma lista dos números primos existentes entre 1 e um número inteiro informado pelo usuário.
def primo(num):
for i in range(2, num + 1):
if i == num:
print(num, end = ' ')
elif num % i == 0:
break
... |
cb682d0784b282f4e81d3781247084eaddc3aadc | torga/operadores-mutacao-interface | /operadores_de_mutacao/troca_variavel_interface/dir_var_rep_const.py | 931 | 3.90625 | 4 | # PROGRAMA ORIGINAL
'''
num_aleatorio = 10 #VARIAVEL GLOBAL
def correr_numero(a): #VARIAVEL DE INTERFACE
numero = a #VARIAVEL LOCAL RECEBENDO VARIAVEL DE INTERFACE
for numero in range(a,num_aleatorio,2): #TEMOS CONSTANTES UTILIZADAS NA FUNCAO
print(retornar_numero(a)) #COMUNICACAO COM OUTRA FUNCAO
def... |
48e79437bb8a291425f00501ccadc931b9f496b5 | Lingesh2311/Python-Basics | /Machine Learning Algorithms/Introduction - Scikit Learn/scikit.py | 404 | 3.515625 | 4 | import seaborn as sns
import matplotlib.pyplot as plt
sns.set()
iris = sns.load_dataset('iris')
# Print the dataframe
print(iris.head())
# Display a pairplot
sns.pairplot(iris, hue='species', height=1.5)
plt.show()
# Features
X_iris = iris.drop('species', axis=1)
print(f"Shape of Feature Matrix: {X_iris.shape}")
... |
40a8caf1dd59ad47329f834c8b8a31bd3d13d851 | Lingesh2311/Python-Basics | /OOP-in-Python/Classes&Instances1.py | 576 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 7 21:08:11 2019
@author: Lingesh K
"""
class Employee:
pass
# Creating instances of the class Employee
emp1 = Employee()
emp2 = Employee()
# Giving details about the first employee
emp1.first = 'Lingesh'
emp1.last = 'K'
emp1.pay = 20000
emp1.email ... |
0a9a27b30920f84c9a53a1fa781bcd685be527c1 | n-someya/nlp-test | /test.py | 685 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import count_word
test_text = u"That statement is only true in general if your database is initialized using the “C” locale (the North America/English-friendly UNIX default). Running with “C” used to be extremely common, but is less and less so, as modern operating systems automagically choose ... |
35c9fd68f562bce7e22dc4bc62ea5a8340dbdd25 | Mujju-palaan/Python | /74.py | 135 | 3.828125 | 4 | import math
from formula import*
x= 123
y= 343
print("Print the average:" +' '+ str(average(x,y)))
avg = average(x,y)
print(sqrt(avg)) |
cdafe507e8516d8d159ac4b5187cdb424b6eef8a | Mujju-palaan/Python | /raw_input.py | 304 | 3.90625 | 4 | print("enter a number:")
number1 = int(raw_input())
print("enter another number:")
number2= int(raw_input())
print("the sum is: " + str(number1+number2))
print("the multiplication is: " + str(number1 * number2))
print("the division is:" + str(number1/number2))
print("the sub is:" + str(number1-number2)) |
bf80df161b39f16e53a395e5ac177afca976a262 | Mujju-palaan/Python | /loopswithlist39.py | 201 | 4.15625 | 4 | numbers = [1,2,3,4,5,6,7,8,9,10]
for i in range(0,len (numbers)):
print(numbers[i])
for i in range(0,len (numbers),2):
print(numbers[i])
for i in range(0,len (numbers),3):
print(numbers[i]) |
b0483fa755ef33755e1174ef8959a3182cd8b3d1 | Mujju-palaan/Python | /79class.py | 354 | 4.03125 | 4 | class Name:
#constructor method - instantiation
def__init__(self,first,middle,last):
self.first = first
self.middle = middle
self.last = last
#to-string method
def__str__(self):
return self.first + ' ' +self.middle +' ' + self.last
aName = Name('Mary','Elizabeth','Smith... |
8850ef370d6f020742541cb5d4b93ef54e4a3fb1 | Mujju-palaan/Python | /81exc.py | 431 | 3.71875 | 4 | class Person:
def__init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
def__str__(self):
return self.name + ' ' + self.sex + ' ' + str(self.age)
def changeName(self, name):
self.name = name
def changeAge(self, age):
self.age = a... |
2cb4e65cb4830b81be9f16514ed4efb8d1134f44 | Mujju-palaan/Python | /69HYPOTENOUS.nestedscope.py | 326 | 4.09375 | 4 | import math
def hypotenuse(s1, s2):
def square(num):
return num * num
return math.sqrt(square(s1) + square(s2))
print("Enter the length on side 1: ")
side1 = int(raw_input())
print("Enter the length of side 2: ")
side2 = int(raw_input())
hyp = hypotenuse(side1 , side2)
print("The hypotenuse is " + str(... |
27ba16ac7df87b8ecb063b061c4e10f2f30460dd | Seljelid/aoc2020 | /src/20201215.py | 1,556 | 3.75 | 4 | from collections import defaultdict
with open("data/20201215.txt") as f:
line = f.readline()
def dont_speak():
starting_numbers = line.strip().split(",")
starting_numbers = [int(number) for number in starting_numbers]
spoken_numbers = []
for i in range(2020 - len(starting_numbers)):
whil... |
11971748c55e7bad1c848bd1d7545276e1750c3c | merlin428/merlin | /pythoncollections/lists/list_sum.py | 71 | 3.625 | 4 | nums=[10,20,30,40]
total=0
for num in nums:
total+=num
print(total) |
07408cd8b4f6632da3ba4e5550b77dbdf526623d | merlin428/merlin | /pythoncollections/Dictionary/employee_prblm.py | 436 | 3.796875 | 4 | #key id name designation salary
#print employee salary
#employee salary
#check for gender key if not add gender key value pair
#iterate all key value pairs
employee={"name":"rincy","id":100,"design":"developer","salary":25000}
print(employee["name"])
print(employee["salary"])
if "gender" in employee:
print("allr... |
63423b6a9027b5affa37ebe9440667d04cc1e06a | xiaozurong/xzr | /ex5-2.py | 132 | 3.734375 | 4 | def isOdd(num):
if num %2==0:
return True
else:
return False
n=eval(input())
print(isPrime(n))
|
af8350990d5b388f424cda2e869cce598151327b | mywork-dragon/NeuralPy | /neuralpy/activation_functions/softmax.py | 2,238 | 3.609375 | 4 | """Softmax Activation Function"""
from torch.nn import Softmax as _Softmax
from .utils import get_activation_details, validate_name_field
class Softmax:
"""
Applies the Softmax function to the input Tensor rescaling input to the range [0,1].
Supported Arguments
dim=None: (Interger) A... |
3f5a3f7322165ecc035bf51d2bbf17a6be7b0755 | meenakshikavaseri/python-challenge | /PyBank/main.py | 4,444 | 4.0625 | 4 | # First we'll import the os module
# This will allow us to create file paths across operating systems
import os
# Module for reading CSV files
import csv
csvpath = os.path.join('.', 'Resources', 'budget_data.csv')
#print(csvpath)
#set the counter
counter = -1
#Your task is to create a Python script that analyzes th... |
932994ba6697e9530571a9d173189de411761451 | UW-ParksidePhysics/Hansen-Erik | /univariate_statistics_11.py | 820 | 3.5625 | 4 | from numpy import *
from Final_exam.two_column_text_read_11 import x1, y1
# written by E.Hansen
# write try:/except ImportError statement when importing module
def univariate_statistics():
"""outputs the statistics into an array"""
if len(x1) >= 3: # check for length of list
if len(y1) >= 1: # ... |
2b4fb796578e1a6ef4bc3153f51ef8efc20e018c | geckoblu/mailindicator | /mailindicator/__init__.py | 935 | 3.671875 | 4 | """-"""
VERSION = '0.5.2'
class Mail:
"""Mail object."""
def __init__(self, m_id, m_from, subject, date):
self.id = m_id
self.mfrom = m_from
self.subject = subject
self.date = date
def __str__(self):
return 'Mail[id:"%s", mfrom:"%s", subject:"%s", date:"%s"]' % \
... |
66290916afe52889fabe92ff2938a4b2691093b3 | pjdevs/pyautomata | /automata/utils/unordered_pairs.py | 1,477 | 3.640625 | 4 | from .decorators import constant
class UnorderedPair:
"""
Class for an unordered, "constant" and hashable pair of hashable and ordereable objects, i.e. `UnorderedPair(1, 3) == UnorderedPair(3, 1)`.
"""
def __init__(self, a, b):
self._a = a if a <= b else b
self._b = b if b > a else a
... |
9f870b089b828b276d727d95e6cab15a29efde67 | aaronko423/Battleship | /tests/test_board.py | 543 | 3.59375 | 4 | import unittest
from app.gameboard import GameBoard
class TestBoard(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_grid_created(self):
g = GameBoard()
self.assertIsInstance(g.grid, list, "grid property is a list")
def test_letter_from_co... |
052da7665ac984360e26358c09bb5586ea0e5761 | VigneshSella/ML-TradingBot | /main/api_calls.py | 2,383 | 3.546875 | 4 | import requests
import pandas as pd
API_URL = "https://www.alphavantage.co/query"
API_KEY = "JLF3VYO6W156F6WT"
time_series_functions = {
'TIME_SERIES_INTRADAY': 'Time Series',
'TIME_SERIES_DAILY': 'Time Series (Daily)',
'TIME_SERIES_DAILY_ADJUSTED': 'Time Series (Daily)',
'TIME_SERIES_WEEKLY': 'Weekly... |
c7b972dd253e1b9077bde47ce33e03bbf08c7fd2 | jack-morrison/cs-review | /CTCI/chapter_1/1.2/run.py | 370 | 3.703125 | 4 | from isPermutation import *
# True -- these are permutations of each other
inputT1 = "jackmorrison"
inputT2 = "nkmorcrijaso"
# False -- these are not permutations of each other
inputF1 = "lksjdf"
inputF2 = "kjhsfkjasfef"
dict1 = string_to_dict_of_counts(inputF1)
dict2 = string_to_dict_of_counts(inputF2)
answer = ch... |
2f49e48afb1a70d6544346fc48033071ab932584 | jack-morrison/cs-review | /python/sorting_algorithms/quick_sort/quick_sort.py | 658 | 4.03125 | 4 | # quick_sort.py
# implements the quick sort algorithm
def swap(arr, a, b):
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
def quick_sort(arr, left, right):
if left < right:
pivotIndex = right
wall = partition(arr, pivotIndex, left, right)
quick_sort(arr, left, wall-1)
qui... |
c08c64a8095e69a4459688c742fc1be0b7c353c1 | jack-morrison/cs-review | /CTCI/chapter_1/1.1/hasUniqueChars.py | 587 | 3.90625 | 4 | # Implement an algorithm to determine if a string has allunique characters.
# What if you cannot use additional data structures?
def hasUniqueChars(stringIn):
if (len(stringIn) > 128): # ASCII characters are the first 128 Unicode values
return False
char_set = [False for _ in range(128)]
for cha... |
4c9dc5c764e8ec7b584270d5ba36d20a9e616270 | xdlgj/chaoboliu | /考试.py | 557 | 3.828125 | 4 | distance = float(input("请输入距离"))
money = 0
sum = 0
for i in range(0,60):
if distance <= 6:
money = 3
elif 6 < distance and distance <= 12:
money = 4
elif 12 < distance and distance <= 22:
money = 5
elif 22 < distance and distance <= 32:
money = 6
elif distance > 32:
if (distance-32)%20 == 0:
money =... |
8a51fc4ac8b9916acbf3a0484a85f9d2e10194e4 | xdlgj/chaoboliu | /练习2.py | 941 | 4 | 4 | '''
def a(b,c):
g = b+ " " +c
return g.title()
s = a("l","e")
print(s)
'''
'''
def a(names):
for name in names:
g = "Hello!"+name.title()+"!"
print(g)
s=["zhangfei","guanyu"]
a(s)
'''
'''
def a(ktvv):
for ktv in ktvv:
mv = "有请麦霸:"+" "+ktv+" "+"唱一首不同版青藏高原!"
print(mv)
mtv=["刘欢","那英","毕福剑","迪克牛仔"]
a(mtv)
'''
... |
dea488edbe22f5986b4a37d62a2c3585dadd242c | vivekhariharan-zz/hunchbox | /munging/datamunger.py | 3,423 | 3.578125 | 4 |
import collections
class DataMunger:
def __init__(self):
pass
def create_random_validation_set(self, trainingData, percentSplit = 0.3):
''' Splits the given numpy array data into training and validation
(random split)
inputs:
@train... |
f9b8c83314df1f3c4feb64c89d32cbe135a224d8 | EndyViegas/jogo_da_velha | /classes/jogodavelha.py | 3,422 | 3.609375 | 4 | class JogoDaVelha():
def __init__(self):
self._coordernadas = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
def jogaO(self, x, y):
if self._coordernadas[x][y] == ' ':
self._coordernadas[x][y] = 'O'
return True
else:
return False
... |
7ec1200bb85a803109f532c1fb860df19f5386b0 | coding-admin/wdi-july-2019 | /08-programming-fundamentals-collections-and-iteration/final/ttc.py | 1,461 | 3.546875 | 4 | from data import stations_with_line_numbers
from pprint import pprint
stations = stations_with_line_numbers
for k,v in stations.items():
print(k, v)
# print(stations.keys())
pprint(stations.values(), indent=4, width=4)
# for station, line_number in stations.items():
# if line_number == 'Line 3':
# print(sta... |
71877f5949a2bbba74dfa1f6a983bd4713fd2947 | anderson-dan-w/Words | /wordplay/interactive.py | 1,964 | 3.609375 | 4 | #!/usr/bin/env python3
import collections
import copy
import itertools
from general import dwanderson
from general import tools
WORDS = dwanderson.readin_words()
@tools.timeme
def unleave(string, MIN=None):
string = string.upper().replace(" ","")
nletts = len(string)
if MIN is None:
MIN = nletts... |
ef60029a44f5930fb9fddecdc45774eb5a8145e8 | anderson-dan-w/Words | /wordplay/tests/test_anagram.py | 6,389 | 3.578125 | 4 | import unittest
import collections
from wordplay import anagram as A
class TestAnagram(unittest.TestCase):
def test__calc_value(self):
a, b = "A", "B"
a_value, b_value = A.constants.PRIMEABET[a], A.constants.PRIMEABET[b]
aa_value = a_value * a_value
ab_value = a_value * b_value
... |
e373c0be245de470c7c6feb87c550c9b547fedcf | corentinthomasset/ConUHacksV | /embedded/hw_control/single_buzz.py | 1,504 | 3.625 | 4 | #!/usr/bin/env python
import RPi.GPIO as GPIO
import time
# Set #17 as buzzer pin
BeepPin = 5
#def print_message():
# print ("========================================")
# print ("| Beep |")
# print ("| ------------------------------ |")
# print ("| Buzzer connect to GPIO0 ... |
d20f5827cf203a786ec183ba1c24a1e2cea4d838 | JeroendeBruijnHU/Progammeren | /Les 9/test_9_3.py | 391 | 3.5 | 4 | import csv
with open("scorelijst.csv", 'r') as CSVFILE:
lezer = csv.reader(CSVFILE, delimiter=";")
highscore = 0
datum = 0
speler = 0
for row in lezer:
if int(row[2]) > highscore:
highscore = int((row[2]))
datum = (row[1])
speler = (row[0])
print("... |
2bde87b9ee4c5a3ebef39b498d7e82a280b2b361 | JeroendeBruijnHU/Progammeren | /Les 3/Opdrachten/3_3.py | 220 | 3.703125 | 4 | ja = ('ja')
nee = ('nee')
age = eval(input("Geef je leeftijd"))
pp = eval(input("Nederlndsa paspoort:"))
if age >= 18 and (pp == ja):
print("Gefeliciteerd, je mag stemmen")
else:
print("Je mag niet stemmen") |
864149e147c58099588fcf36792e82520e69d96f | Dalibaba/snake | /snake/snake.py | 2,216 | 3.984375 | 4 | """
Snake class
"""
import constants
import random
directions = ["UP", "RIGHT", "DOWN", "LEFT"]
class Snake:
"""
Create Snake with starting position and direction
"""
def __init__(self, world_min_x, world_max_x, world_min_y, world_max_y, size_x=10, size_y=10):
self.x = (world_min_x + world_m... |
b40e33da2921f65b680455fd7106b2082c80aaa2 | mlnance/Lau_Lab_ALAD | /calc_nearest_neighbors_no_revisit.py | 5,905 | 3.5 | 4 | #!/usr/bin/python
__author__="morganlnance"
'''
NOT AS OPTIMIZED OF A SOLUTION TO THE NEAREST-NEIBHOR, KNOT-FIXING PROBLEM
Usage: python <script.py> /path/to/string_<>.dat
Take each image ii along a string, in sequence
Calculate the distance between ii and every other image
in the string that is not the same as ima... |
4d1461b45f262b610147ecc7078a6321151889ec | mlnance/Lau_Lab_ALAD | /push_string.py | 16,864 | 3.828125 | 4 | #!/usr/bin/python
__author__="morganlnance"
## period used for simulated annealing function
period = 25
'''
Usage: python <script>.py string_cycle#.dat nvars cycle_number
Arguments: string_cycle#.dat (/path/to/the string.dat file)
nvars (the number of variables defining one image)
c... |
4146553946937c41ad0140a20ad997eb24879091 | fahirazahra/Python-Projects-PROTEK | /Praktikum 10/Latihan no. 2.py | 588 | 3.546875 | 4 | # Script kode program memasukkan inputan data ke file.txt
openFile = open('d:/Latihan no. 2.txt', 'w')
while True:
NIM = input('Masukkan NIM : ')
Nama = input('Masukkan Nama Mahasiswa : ')
Alamat = input('Masukkan Alamat : ')
result = (NIM + '|' + Nama + '|' + Alamat)... |
d949fcb8b440554a7fbacbcdf71520281e7ddc67 | fahirazahra/Python-Projects-PROTEK | /Praktikum 07/Latihan/Latihan no. 3.py | 687 | 3.8125 | 4 | # Script menghitung rata-rata
print('--------------------------------------------------------------')
print(' PROGRAM HITUNG RATA-RATA')
print('--------------------------------------------------------------')
BilBul = int(input('Masukkan bilangan bulat : '))
while True:
try:
jumlah = 0
... |
d61c1ec9b6f470f29b93bcb7148ec0ce003b2a4d | fahirazahra/Python-Projects-PROTEK | /Praktikum 08/Langkah Kerja 1-8.py | 1,851 | 4.09375 | 4 | a = [1, 5, 6, 3, 6, 9, 11, 20, 12]
b = [7, 4, 5, 6, 7, 1, 12, 5, 9]
print('a =', a)
print('b =', b)
print('--------------------------------------------------------------------------------------')
# Sisipkan nilai 10 ke dalam indeks ke-3 dari a
a.insert(3, 10)
print('Nilai 10 masuk ke dalam indeks ke-3 dari a :'... |
76ea36c570960dc19f2e7f8518daf7865f727c92 | fahirazahra/Python-Projects-PROTEK | /UTS/UTS Soal no. 2.py | 342 | 3.578125 | 4 | # Script menghitung jarak tempuh pada mobil
def jarakTempuh(v, t):
rumus = ((v*t)+1/2*(a*(t**2)))
return rumus
v = int(input('Masukkan Kecepatan Mula-Mula (V0) : '))
a = int(input('Percepatan (a) : '))
t = 0
while (t<10):
t+=1
rumus = ((v*t)+1/2*(a*(t**2)))
print('t = ', t, '', '', 'S(t) = ' + st... |
a21d9bbad32381d741a1117b94ba3419d927a6bd | fahirazahra/Python-Projects-PROTEK | /UTS/UTS Soal no. 1.py | 513 | 3.59375 | 4 | # Script Menghitung score BMI
def BMI(B, T):
score = (B/((T/100)**2))
if(score<18):
status = 'KURUS'
elif(score>=18) and (score<23):
status = 'IDEAL'
elif(score>=23) and (score<27):
status = 'GEMUK'
elif(score>=27) and (score<35):
status = 'OBESITAS'
elif(score>=... |
1e0a3fa42bedcfac91c273eae095e08f198ce856 | k0ngui/adventofcode | /1/taxicab_2.py | 742 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def distance(data):
moves = []
with open(data, 'r') as f:
moves = f.read().rstrip().split(", ")
# North, East, South, West
orientations = [(1, 0), (0, -1), (-1, 0), (0, 1)]
o_i = 0
position = (0, 0)
visited = set()
for move in mo... |
d3927ffae627c4db265fd5f514c431fda50bd60f | fuxingbit/python | /day9/rlock.py | 747 | 3.71875 | 4 | # @Time :2018/7/15 下午2:20
# @Author :Jennings
# @Email :zjn@wiwi.ink
import threading, time
def run1():
print("grab the first part data")
lock.acquire()
global num
num += 1
lock.release()
return num
def run2():
print("grab the second part data")
lock.acquire()
global num2
num2 += 1
lock.release... |
d7f3d0b49566f1d69914704bcb7a6ceb2157a197 | fuxingbit/python | /day7/yichang.py | 813 | 3.625 | 4 | # @Time : 2018/7/2 19:49
# @Author : Jennings
# @Email : zjn@wiwi.ink
class Dog(object):
def __init__(self, name):
self.name = name
def eat(self, food):
print("%s is eatting ...%s " % (self.name, food))
def bulk(self):
print("%s is yelling...." % self.name)
# d = Dog("Alex")
# ch... |
1a304ceb64d94626520c1c78d04b2b05cede2f2d | fuxingbit/python | /day1/one.py | 135 | 3.921875 | 4 | name = input("name:")
age = input("age:")
info = '''
---------info of %s --------
name:%s
age:%s
''' % (name, name, age)
print(info)
|
a360ff6389cc579f5f1a0e0c10252120b9bd20b2 | fuxingbit/python | /day3/rename.py | 499 | 3.5 | 4 | __author__ = "Jenliver"
__date__ = "2017/09/09"
import sys
f = open("yesterday2","r",encoding="utf-8")
f_new = open("yesterday2.new","w",encoding="utf-8")
# for line in f:
# if "hello" in line:
# line = line.replace("hello","hello world")
# f_new.write(line)
# f.close()
# f_new.close()
find_str = s... |
2c46cfb3e6491cd5d29d8c21901bf891476e839c | Jonnylazzeri/us_states_game | /main.py | 1,142 | 3.78125 | 4 | import turtle
import pandas
screen = turtle.Screen()
screen.title("U.S. States Game")
score = 0
answered_states = []
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
data = pandas.read_csv('50_states.csv')
states = data.state.to_list()
while score < 50:
answer_state = screen.textinput(t... |
fa2b7396c4e3fb4c66846537851134097ac06deb | liwenjie0/python01 | /pachong/luntan_title.py | 1,595 | 3.546875 | 4 | # 操作系统windows10,python 3.5
# 获取kukupig论坛帖子的标题和链接
#未完成!!!!!!!!!!!!!!!!!!!!
import urllib.request
from bs4 import BeautifulSoup
import threading
import re
class MyThread(threading.Thread) :
def __init__(self,func,args):
threading.Thread.__init__(self)
self.func=func
self.args=args
def ru... |
3f9e6e9b91a4ccea69a72ecfd420b68676248c5d | michaelJwilson/hilbert | /remap/demo/vec3.py | 3,648 | 3.5 | 4 | #!/usr/bin/python
import sys
from math import *
epsilon = 1e-9
try:
# Use fast vec3 implementation if Numpy is available
import numpy as N
class vec3(N.ndarray):
"""A simple 3D vector class, using Numpy for fast array operations."""
def __new__(cls, *args):
a = N.ndarray.__new... |
ca99e9c3cd4f78e87ba6130929727ba373427d21 | LukeG-dev/CIS-2348 | /Homework 2/ZYlab_5.py | 803 | 3.859375 | 4 | # Luke Gilin 1216992
# Zybooks 9.10 CIS 2348 LAB: Word frequencies (lists)
import csv
# Get file name from user
filename = input()
# Open file in read only mode
with open(filename, 'r') as csvfile:
frequency_count = csv.reader(csvfile, delimiter=',')
for row in frequency_count:
word_list ... |
f244d849618b2cb81171763cbc94bddb59e2b63e | LukeG-dev/CIS-2348 | /Homework 3/HW3_11.18.py | 467 | 3.546875 | 4 | # Luke Gilin 1216992
if __name__ == '__main__':
# List to store input
inputlist = input().split()
# List to store positive integers
poslist = []
inputlist = [int(i) for i in inputlist]
# add non-negitive values to poslist
for number in inputlist:
if number >= 0:
... |
69ba98a8c14e62037d3016662fc7d6e571187c67 | LukeG-dev/CIS-2348 | /homework1/3.18.py | 888 | 4.21875 | 4 | # Luke Gilin
import math
wall_H = float(input("Enter wall height (feet):\n"))
wall_W = float(input("Enter wall width (feet):\n"))
wall_A = wall_H * wall_W # Calculate wall area
print("Wall area:", '{:.0f}'.format(wall_A), "square feet")
paintNeeded = wall_A / 350 # Calculate Paint needed for wall
pri... |
5226c99becd7721dcced90cd85b26526fa8880c8 | ashish-dalal-bitspilani/python_recipes | /python_cookbook/edition_one/Chapter_One/recipe_two.py | 597 | 4.625 | 5 | # Chapter 1
# Section 1.2
# Swapping values without using a temporary variable
# Python's automatic tuple packing (happens on the right side)
# and unpacking are used to achieve swap readily
a,b,c = 1,2,3
print("pre swap values")
print('a : {}, b : {}, c : {}'.format(a,b,c))
a,b,c = b,c,a
print("post swap values")
p... |
89165f3f9fd65f69f7a3ed151685e9458ef9ac99 | MarkDNL/rpistar | /star.py | 1,000 | 3.546875 | 4 | from gpiozero import LEDBoard
class Star(LEDBoard):
# Set up a Star using GPIO Zero to build a class.
# To use:
# star = Star() for a simple instance using LED class.
# star = Star(pwm=True) for a version which can use PWM.
# See example files in this repo for more examples of use...
def __init_... |
65a4dbc8246f55ece3d2d1e40ad3c2025dfc4a4e | mdelafuen/Week3 | /FtoCConvert.py | 182 | 3.84375 | 4 |
def main ():
temp_in_c = float(input("What is the Celcius temperature?"))
temp_in_f = temp_in_c * 1.8 + 32
print(f"The Farenheit temperature is {temp_in_f}")
main() |
8997c17233da24e62157cb4673b7fbbfdce02020 | ES2Spring2019-ComputinginEngineering/project-one-alymo | /4_plotting_period_and_length.py | 621 | 4.09375 | 4 | #Step 4: Plotting Pendulum Length and Period
#Mo Liu and Alyssa Attonito
#This section generates log-log graphs to showcase the difference between the simulation and real-world data.
import matplotlib.pyplot as plt
#Note: Input numbers here to graph in the plot
Length_of_Pendulum= [0.12065, 0.2159, 0.3429, 0.4699, 0... |
8166104b560df774e64eb0a163cfc5a52b87272d | rupin-1801/python-programs-1st-year | /year_at_100_age.py | 145 | 3.828125 | 4 | n=input("Enter your name: ")
a=int(input("Enter your age: "))
print("{} will be of 100 years in {} year, as he is now 18".format(n,2020-a+100))
|
21ecd2d1172e6348755c402f5c4fd1c599bf42e0 | rupin-1801/python-programs-1st-year | /python_quiz_1.py | 1,019 | 3.96875 | 4 | s=input("Enter your name:")
print("Welcome Mr. %s to Python quiz"%(s))
q1="""Q-1: What is the correct Syntax for Dictionary?
A. dic={1,'b':2,'c'}
B. dic={3:'aa';2:34}
C. dic={1:'bad',2:'good'}
D. d={'e';'f',3;'p')"""
q2='''Q-2: Find out incorrect statement:
A. print("%d + %d is %d".format(a,b,c))
B. print("... |
c1aea5286320ee0a4b086e0a9038239892e05b3f | FearlessClock/RobotFactory | /Player/UserAction.py | 465 | 3.65625 | 4 | """ Class representing the actions a user can perform on a square.
A user action is anything that the creature won't do by it self
like cleaning up a mess or making more food"""
class UserAction:
def __init__(self, name, actionTask):
self.name = name
self.actionTask = actionTask
def get... |
d3fab4c523ac7690cdf1e655c7e9364b008b85df | FearlessClock/RobotFactory | /UI/Button.py | 666 | 3.640625 | 4 | import pygame
from pygame.math import Vector2
from pygame.rect import Rect
class Button:
""" rect = Rect object, Position and size of the button
color = Color of the button in RGB (R,G,B)
"""
def __init__(self, rect, color, text, callback):
self.rect: Rect = rect
self.color = colo... |
43ab394f43b06ace4fffb0b09c18d01c04c0b962 | CruzAmbrocio/python-factorial | /application.py | 1,161 | 4.28125 | 4 | """This program calculates a Fibonacci number"""
import os
def fib(number):
"""Generates a Fibonacci number."""
if number == 0:
return 0
if number == 1:
return 1
total = fib(number-1) + fib(number-2)
return total
def typenum():
"""Function that allows the user to enter a numbe... |
2b6150aba7c2ba1e8fc17abe9523e69779f1a9db | Sunny-jain/python_small_project | /rock_paper_scissors.py | 2,591 | 3.640625 | 4 | from tkinter import *
import random
top = Tk()
click=True
top.iconbitmap(r'C:\Users\dell\Documents\Downloads\icon.ico')
top.title("rock, paper, scissors game")
top.resizable(width=False,height=False)
rbutton=""
pbutton=""
sbutton=""
def play():
global rbutton,pbutton,sbutton
rbutton=Button(top,t... |
b897b4746078930f6ad491e1ddaaab4471cf98ba | Lcarera/Trabajo-Practico-1 | /ej12.py | 391 | 3.65625 | 4 | """Devuelve cuantas vocales tiene una cadena, ingresada por el usuario."""
def contarVocales(cadena):
"""Cuenta las vocales de una cadena."""
vocal = 0
for c in cadena:
if c in "aeiouAEIOU":
vocal = vocal + 1
return vocal
cadena= input("Ingrese una cadena y se devolvera cuantas voca... |
95c11512136c758f51ae686b4ac904be82f361ee | Lcarera/Trabajo-Practico-1 | /ej4y5.py | 1,202 | 4.3125 | 4 | """El programa da 3 opciones.
Dependiendo de la opcion elegida pide la temperatura y la devuelva convertida,
o devuelve una tabla de conversion."""
def conversorC(f):
"""Convierte grados Celsius a Fahrenheit."""
Celsius= (f-32)*5/9
return "{0:.2f}".format(Celsius)
def conversorF(c):
"""Convierte grados... |
764c6372258f6920cc1be072b0eeb880559de843 | Lcarera/Trabajo-Practico-1 | /Ejercicio 9/ej9.py | 331 | 3.6875 | 4 | """Pide que se ingrese una contraseña hasta que sea igual a una ya predefinida"""
CONTRASEÑA= "master$123"
contra = ""
while not contra == CONTRASEÑA:
contra= input("Ingrese la contraseña: ")
if contra == CONTRASEÑA:
print("Contraseña correcta")
break
else:
print("Contraseña incorrec... |
de2e0b570733aeec39a53cca6acbd5a6111597ea | moocstudent/python-test | /lesson1/forLoop.py | 148 | 4.125 | 4 | friends = ['jack','kyo','ukyo','lucy']
for i,name in enumerate(friends):
print("iteration {iteration} is {name}".format(iteration=i,name=name))
|
653a9bd75b58de94a70e4280e8305daa7358e54a | hvishal512/MA5470-Numerical-Analysis | /Assignment/iterative_solvers.py | 1,457 | 3.609375 | 4 | import numpy as np
''' Jacobi and Gauss-Siedel iterative schemes to solve Ax = b'''
### JACOBI method ###
def jacobi_solver(A,b,x0,num_itr):
D = np.diag(A)
R = A - np.diagflat(D)
x = x0
for i in range(num_itr):
temp = (b - np.dot(R,x))/ D
x = temp
return x
### GAUSS-SIEDEL me... |
b03d35c90a20509a8bbde1aab8a0dbf55f256ddb | code-amir/Website-Blocker-Python-Script | /website_blocker.py | 1,707 | 3.625 | 4 | import time
from datetime import datetime as dt
#About Host file: Host file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name shoul... |
cc8e7d537c5e503be86cb69288216d0bb8a75311 | Zackster310/CarClass | /Class creation python.py | 675 | 3.578125 | 4 | class Car:
def __init__(self, name, brand, color, maxSpeed, numberPlate):
self.name = name
self.brand = brand
self.color = color
self.maxSpeed = maxSpeed
self.numberPlate = numberPlate
def changeColor(self,newColor):
self.color = newColor
def getS... |
29322f2c5a750b532c5faccb5549d29841bd5b14 | miku/khwarizmi | /sorting/median.py | 645 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
"""
Swap the median element with the middle element. Create two smaller
problems, solve these.
Subproblems: Find the median of an unsorted list efficiently.
"""
def sort(A):
medianSort(A, 0, len(A))
def medianSort(A, left, right):
if left > right:
# find median ... |
9d37bd5d84fde912bc0631150f138a1e50abdbef | jschaf/My-Hackerrank-Problems | /sequence_Equation_Unfinished.py | 341 | 3.96875 | 4 | #!/bin/python3
# https://www.hackerrank.com/challenges/permutation-equation/problem
import sys
def permutationEquation(p):
for a in p:
print(a)
if __name__ == "__main__":
n = int(input().strip())
p = list(map(int, input().strip().split(' ')))
result = permutationEquation(p)
print ("\n".joi... |
3adc007102e64524b7aec46c2a6bef2041de7143 | compstruct/DropBack | /dropback/DropBack.py | 6,130 | 3.6875 | 4 | """
An emulation of the DropBack algorithm using Chainer.
https://arxiv.org/abs/1806.06949
Author: Maximilian Golub
"""
import chainer
import time
import os
if chainer.backends.cuda.available:
import cupy as xp
else:
import numpy as xp
class DropBack(chainer.training.StandardUpdater):
def __init__(sel... |
ee2cb190034aae964ec2c8f7de5a95ddd8cc7f3e | ankurpandeyvns/PythonPractice | /Program14.py | 809 | 3.890625 | 4 | def insert(self,data):
new_node=Node(data)
if self.head is None:
self.head=new_node
return
temp=self.head
while temp:
if new_node.data<temp.data:
prev=temp
temp=temp.left
else:
prev=temp
temp=temp.right
if new_node.data<... |
3cea9cf3688bb754018df090ae1a477b4b25bc40 | zmt123sdu/Huffman-compression-image-text | /text/demo_huffman_compression.py | 1,035 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
demo_huffman_compression.py
Utilities for Huffman compression of text (8 bit / symbol)
"""
from huffman_compression_utils import HuffmanEncode, HuffmanDecode
# Huffman encoding
file_source = "sample_text_source.txt";
file_encoded = "sample_text_encoded";
HuffmanEnco... |
c8635f8015f615163eed14aaced643c66a695e24 | ComeSSomeAll/algosProgramms | /problems3/3C.py | 543 | 3.546875 | 4 | fin = open("isheap.in")
fout = open("isheap.out", "w")
N = int(fin.readline())
arr = list(fin.readline().split())
for i in range(N):
arr[i] = int(arr[i])
def isHeap(arr, n):
for i in range(int((n - 2) / 2) + 1):
if arr[2 * i + 1] < arr[i]:
return False
if (2 * i + 2... |
c69111a39b40a363fd7edb7d391acbb09ca2eddc | ComeSSomeAll/algosProgramms | /problems3/3A.py | 1,089 | 3.734375 | 4 | def leftBinSearch(A, key):
left = -1
right = len(A)
while right > left + 1:
middle = (left + right) // 2
if A[middle] >= key:
right = middle
else:
left = middle
if right < len(A) and A[right] == key:
return right
else:
retur... |
1771618b573a48c8f0c19fbce9d50bf705fd481e | joedo29/Self-Taught-Python | /NestedStatementsAndScope.py | 1,367 | 4.46875 | 4 | # Author Joe Do
# Nested Statement and Scope in Python
'''
It is important to understand how Python deals with the variable names you assign.
When you create a variable name in Python the name is stored in a *name-space*.
Variable names also have a *scope*, the scope determines the visibility of that variable name to ... |
f3822088131255682b7fa0414d749097bfdd500c | joedo29/Self-Taught-Python | /Generator.py | 2,240 | 3.96875 | 4 | # Author: Joe Do
# Generator
# The generator functions will automatically suspend and resume their execution
# and state around the last point of value generation
# The main advantage here is that instead of having to compute an entire series
# of values upfront and the generator functions can be suspended,
# this feat... |
0cd39e694f3407d07c2e191bdb4301d2c57ed5e6 | joedo29/Self-Taught-Python | /BankAccountOOP/main.py | 901 | 4 | 4 | # main.py
# Author: Joe Do
# Date: March 28, 2018
import random
from bank_account import BankAccount
from customer import Customer
inputName = input('What is your name? ')
inputAddress = input('What is your address? ')
inputDOB = input('What is your DOB? yyyy-mm-dd ')
inputDeposit = int(input('How much would y... |
072ad3929e779ef840bc40875ff1eccaf7e55c1a | joedo29/Self-Taught-Python | /Files.py | 1,452 | 4.65625 | 5 | # Joe Do
# Python uses file objects to interact with external files on your computer.
# These file objects can be any sort of file you have on your computer,
# whether it be an audio file, a text file, emails, Excel documents, etc.
# Note: You will probably need to install certain libraries or modules to interact with ... |
0183945151a5cb6f6370a701bdb6e7cd1fdb656e | psyoblade/leetcode | /easy/MergeTwoList.py | 1,544 | 4.0625 | 4 |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def append(self, val):
head = self.head
if head == None:
head = ListNode(val)
else:
head.next = ListNode(val)
def mergeTwoLists(self, l1, l... |
ab8c783133aa150146ca7f93a1167a1c9fc66de1 | shilpa5g/Python-Program- | /python_coding_practice/count_vowel.py | 182 | 3.65625 | 4 | vowels = 'aeiou'
string = input(" enter a string: ")
string = string.casefold()
count = {}.fromkeys(vowels,0)
for c in string:
if c in count:
count[c] += 1
print(count)
|
911641ceec5dec20babbf692594b79126f43d9b6 | shilpa5g/Python-Program- | /python basic coding/sum_of_digit.py | 136 | 4.1875 | 4 | num = int(input("enter a number: "))
sum = 0
while num > 0:
n = num % 10
sum += n
num //= 10
print("sum of the digit: ",sum) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.