blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
57501bc781022c39240df5cb23dcd8f67c74c53a | bruhmentomori/python | /lek3.py | 726 | 3.9375 | 4 | print("Välkommen till mitt räkneprogram")
operator = input("Välj räknesätt +, -, *, /:")
try:
tal1 = int(input("Mata in ett heltal: "))
except:
print("Du måste skriva in en siffra")
tal1 = 0
try:
tal2 = int(input("Mata in ett till heltal: "))
except:
print("Du måste skriva in en siffra: ")
... |
285a777fbb3fe740b2b16f2eb7696923f0c0ac08 | luisdaRC/test_py | /main.py | 3,199 | 3.71875 | 4 | #Changes
def practica():
goleadores_2014 = {"Muller": ("Alemania", 5),
"Dempsey": ("USA", 2),
"James": ("Colombia", 6),
"Muller": ("Alemania", 5),
"Schurrle": ("Alemania", 3),
"Messi": ("Argentina", 4)... |
d0434e4c42c139b85ec28c175749bb189d2a19bf | Francisco-LT/trybe-exercices | /bloco36/dia2/reverse.py | 377 | 4.25 | 4 | # def reverse(list):
# reversed_list = []
# for item in list:
# reversed_list.insert(0, item)
# print(reversed_list)
# return reversed_list
def reverse(list):
if len(list) < 2:
return list
else:
print(f"list{list[1:]}, {list[0]}")
return reverse(list[1:]) + ... |
5910d4439a26badf770e1aa6fdf08d46f4be93e6 | danrludwig/CS-1400 | /CS 1400/Ludwig-Daniel-Assn13/assn13-task2.py | 527 | 4.03125 | 4 | from password import Password
def main():
password = Password()
while True:
passGuess = input('Enter password: ')
password.setPassword(passGuess)
if password.isValid() is True:
print('Valid Password')
else:
print('Invalid Password\n', password... |
aea6faec795ead1e46971ee3a3efa97f4dc08c9e | ALXTorresC/productosDesktop | /digito.py | 807 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Tkinter Python 3.7
from tkinter import *
def ventana():
window = Tk()
window.title("Tkinter")
window.geometry('350x200')
lbl = Label(window, text="Introduce un número")
lbl.grid(column=0, row=0)
result = Label(window,text="")
txt = Entry(win... |
c775866c264defa931101643723c011c93b2fa9f | mopeneye/CREDITRISK_PREDICTION_MACHINLEARNING_PYTHON | /CreditRiskPrediction.py | 19,441 | 3.625 | 4 | #
# Problem
# Establishing a machine learning model to classify credit risk.
#
# Data Set Story
#
# Data set source: https://archive.ics.uci.edu/ml/datasets/statlog+(german+credit+data)
#
# There are observations of 1000 individuals.
# Variables
#
# Age: Age
#
# Sex: Gender
#
# Job: Job-Ability (0 - unsk... |
a50af9f75080606073a752281f515057d3544564 | AlexLecq/algotraining | /syracuse_algo.py | 643 | 3.796875 | 4 | #Entrainement à l'épreuve Algo BTS SIO
number_enter = ""
number_vol = 0
trig = False
while(type(number_enter) is not int):
try:
number_enter = int(input("Veuillez saisir un nombre entier positif : "))
if(number_enter < 0):
number_enter = ""
except ValueError:
print("Ceci n'est pas un entier positif")
for... |
d2d8f309a900c4642f0e7c66b3d33e26cabaf4e9 | synaplasticity/py_kata | /ProductOfFibNumbers/product_fib_num.py | 597 | 4.34375 | 4 | def fibonacci(number):
if number == 0 or number == 1:
return number*number
else:
return fibonacci(number - 1) + fibonacci(number - 2)
def product_fib_num(product):
"""
Returns a list of the two consecutive fibonacci numbers
that give the provided product and a boolean indcating if
... |
4feaa6f54c0f3936461284ca0f3ef691bec7a559 | rockneurotiko/ViolentPython | /Chapter-2/AnonymousFTPScanner.py | 3,522 | 3.703125 | 4 | import ftplib
import optparse
import re
from threading import *
maxConnections = 20 # The number of max connections at time
connection_lock = BoundedSemaphore(value=maxConnections) #The Semaphore to control the max connections
def anonLogin(* hostname):
"""
anonLogin tries to do the anonymous connec... |
3abc9bc82008facaecb41970af680588e087612c | nedsanchezca/Juegode21 | /Juego_21.py | 3,378 | 4.09375 | 4 | #Programa que sirve como juego de 21, cuya principal caracteristica es que no tiene asignaciones
import random
""""Funcion que permite dar carta apartir de un mazo"""
def darMazo():
return [['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']]
""""Funcion que permite asignar un valor a la car... |
fda8998e0a52b89047d60b48acbc66138f07d1e3 | billafy/Sample-Regression-Models-Python | /LinearRegression.py | 1,429 | 4.0625 | 4 | import numpy as np # Python Library used for efficient computation on arrays
import scipy as sp # Science Python basically
from scipy import stats # Importing stats module from scipy
import matplotlib.pyplot as mpl # Matrices and Graph Plot Library called to plot our graph
x = [5,7,8,7,2,17,2,9,4,11,12,9,6] # random s... |
caef72e12a5dfdee3d73c8b832077622c7ccaf08 | smaeil/Des-101-m | /odd_even_sum(ismail_ahmadi).py | 355 | 4.0625 | 4 | number = int(input('Please enter a number that all odds and even numbers can be sumec upto: '))
odd_total = 0
even_total = 0
for n1 in range(1, (number + 1), 2):
odd_total += n1
for n2 in range(2, (number + 1), 2):
even_total += n2
print('The Sume of even Numbers upto {} is ={} and sum of even is ={}'.form... |
eb8eb12677310dcad5e6e67c8af08b7fa1b39000 | kblicharski/big-data-hackathon-2017 | /tutorial_scripts/pandas_video_tutorial.py | 915 | 4.03125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import style
style.use('ggplot')
# How to create a DataFrame?
web_stats = {'Day': [1, 2, 3, 4, 5, 6],
'Visitors': [43, 53, 34, 45, 64, 34],
'Bounce_Rate': [65, 72, 62, 64, 54, 66]}
df = pd.DataFrame(web_st... |
861ce17144191ed60bdfe7938c4de8a3cb7d0fe5 | LeonardoLDSZ/PythonNt | /app/variaveis.py | 335 | 3.71875 | 4 | #string = str --------- FUNÇÕES
nome = 'Leonardo'
#inteiro = int ---- FUNÇÕES
idade = 10
#float ----- função
# salario = float(input('Digite seu salario: '))
# print(f'Salario: {salario}')
# Boaleana - TRUE OR FALSE - Variável LÓGICA
verdadeiro = True
falso = False
bebe = bool(input('Voce bebe?'))
print(f'Bebe: {... |
b544a1b3eefab89ecb8fd6d93768ffbcbd99e16c | LeonardoLDSZ/PythonNt | /app/app/15-2-Classes.py | 849 | 4.0625 | 4 | # Classes
# Variáveis de classe
# Métodos de classe
# self
class Calculadora:
n1 = 0
n2 = 0
def soma(self):
resultado = self.n1 + self.n2
return resultado
def subtracao(self):
resultado = self.n1 - self.n2
return resultado
def multiplicacao(self):... |
ce9673a77c9479c98b2adbedfc49603a2ba60ece | LeonardoLDSZ/PythonNt | /app/inicio.py | 555 | 4.09375 | 4 | # #---- Imprimir info na tela (COMENTÁRIO)
# #CTRL+K CTRL+C
print('\n') # pular de linha
print('*'*50)
print('Olá', 'Joelma', 'do Calypso')
print('Olá' + 'Chimbinha' + 'do Calypso')
print('\n')
# Pegar entrada do usuário
nome = input('Digite seu nome: ') #ler
sobrenome = input('Digite seu so... |
26060fca3e7b21456256310d8f73d0ae4bf92c4b | LeonardoLDSZ/PythonNt | /app/app/10-ex_dict.py | 456 | 4.03125 | 4 |
#--- Cadastro de cerveja
marca = input('Digite a marca da cerveja: ')
tipo = input('Digite o tipo da cerveja: ')
#---- Criando um dicionario vazio
cervas = {}
#--- Criando as chaves/valores apos a criacao do dicionario
cervas['marca'] = marca
cervas['tipo'] = tipo
#---- Criando o dicionario com as chave... |
027769fe44d4c08972c3741924a7492247503142 | stolaf-acm/vindinium-python | /example.py | 718 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Example program using the vindinium package
import vindinium
client = vindinium.client()
# Initialization / Configuration of the game goes here
client.setKey('your_key')
client.setParam('mode', 'training')
# Begin the game
client.startGame()
# This is the main loop ... |
1687b77c4b2d3c44b6871e653a974153db7d3f96 | ntuthukojr/holbertonschool-higher_level_programming-6 | /0x07-python-test_driven_development/0-add_integer.py | 578 | 4.125 | 4 | #!/usr/bin/python3
"""Add integer module."""
def add_integer(a, b=98):
"""
Add integer function.
@a: integer or float to be added.
@b: integer or float to be added (default set to 98).
Returns the result of the sum.
"""
if not isinstance(a, int) and not isinstance(a, float):
raise... |
121163d7ae0f64e8294a005550e6f052ce276477 | ntuthukojr/holbertonschool-higher_level_programming-6 | /0x0A-python-inheritance/4-inherits_from.py | 259 | 3.75 | 4 | #!/usr/bin/python3
"""Only a sub class of module"""
def inherits_from(obj, a_class):
"""Returns True if obj is an instance of a class that inherited
from a_class; False otherwise"""
return (type(obj) is not a_class and isinstance(obj, a_class))
|
53acf1631239ce2a0e369c83c395a8096394f7c6 | ntuthukojr/holbertonschool-higher_level_programming-6 | /0x0A-python-inheritance/100-my_int.py | 311 | 3.703125 | 4 | #!/usr/bin/python3
"""MyInt class Module"""
class MyInt(int):
"""Class MyInt that inherits from int"""
def __eq__(self, other):
"""Inverts == and !="""
return not super().__eq__(other)
def __ne__(self, other):
"""Inverts == and !="""
return not self.__eq__(other)
|
430943c3678d42e89da21a4906ff6ca160f60f37 | evnewlund9/repo-evnewlund | /PythonCode/letterFrequency2.py | 819 | 4.0625 | 4 | def letterFrequency(phrase):
string1 = ".,;:!? "
for i in string1:
phrase = phrase.replace(i,"")
phrase = phrase.lower()
phrase = [i for i in phrase]
phrase.sort()
dictionary = {}
for letter in phrase:
if letter not in dictionary:
dictionary[letter] = 1
el... |
6d68b8627f25314a66c63a8597376046a834a4b2 | evnewlund9/repo-evnewlund | /PythonCode/binary.py | 668 | 4.0625 | 4 | def binaryToInt(binary_string):
binary = [character for character in binary_string]
binary.reverse()
x = 0
base_ten_number = 0
for i in binary:
base_ten_number = base_ten_number + (2 * int(i)) ** x
x = x + 1
return base_ten_number
def main():
binary_string = str(input("Input... |
9acd9e00cfcfc930041f285225f5fb9c084dc94f | evnewlund9/repo-evnewlund | /PythonCode/rankandSuitCount.py | 510 | 3.71875 | 4 | def rankandSuitCount(hand):
card_rank = {}
card_suit = {}
for card in hand:
if card[0] not in card_rank:
card_rank[card[0]] = 1
else:
card_rank[card[0]] += 1
if card[1] not in card_suit:
card_suit[card[1]] = 1
else:
card_suit[ca... |
85c9d985cb91e3af51bd3358b0e66813df2d2f66 | evnewlund9/repo-evnewlund | /PythonCode/test.py | 581 | 3.6875 | 4 | from turtle import *
import tkinter.messagebox
import tkinter
window = tkinter.Tk()
canvas = ScrolledCanvas(window,600,600,600,600)
t = RawTurtle(canvas)
screen = t.getscreen()
screen.setworldcoordinates(-500,-500,500,500)
frame = tkinter.Frame(window)
frame.pack()
window.title("What kind of farm do you have?")
def... |
df7369f0ae106b4cdbfe5f289d1556ac0021b1c3 | evnewlund9/repo-evnewlund | /PythonCode/turtle_matrix.py | 629 | 3.84375 | 4 | import turtle
import sparse
import matrix
import random
def showMatrix(turtle_object,m,n):
screen = turtle.getscreen()
screen.tracer(0)
value = 1
x = 0
m = matrix.matrix(n,0)
while x <= n:
x = x + 1
num1 = random.randint(0,n-1)
num2 = random.randint(0,n-1)
m[num1... |
87ee73accac83e33eb0bf032d403ca1fa16c3b63 | evnewlund9/repo-evnewlund | /PythonCode/reverse_string.py | 414 | 4.28125 | 4 | def reverse(string):
list = [character for character in string]
x = 0
n = -1
while x <= ((len(list))/2)-1:
a = list[x]
b = list[n]
list[x] = b
list[n] = a
x = x + 1
n = n - 1
stringFinal = ""
for letter in list:
stringFinal += letter
re... |
394bc8e14a370f22d39fc84f176275c58d1ac349 | evnewlund9/repo-evnewlund | /PythonCode/alternating_sum.py | 414 | 4.125 | 4 | def altSum(values):
sum = 0
for i in range(1,(len(values) + 1),2):
sum = sum + (int(values[i]) - int(values[(i - 1)]))
return sum
def main():
values = []
num = "0"
while num != "":
values.append(num)
num = input("Enter a floating point value: ")
answer = str(altSum(v... |
308cce9f2d44d377db2566246fc29ef76f977432 | abochkarev/simple-python-exercises | /test15.py | 461 | 3.9375 | 4 | from common import show
@show
def find_longest_word(list_):
if not list_:
raise RuntimeError("List shouldn't be none or empty")
max_length = len(list_[0])
for i in xrange(1, len(list_)):
if len(list_[i]) > max_length:
max_length = len(list_[i])
return max_length
assert fi... |
11411d0b5837eb137b68c5a751c36568a213ad52 | abochkarev/simple-python-exercises | /test27.py | 415 | 3.703125 | 4 | from common import show
@show
def for_loop(list_):
res_list_ = []
for i in list_:
res_list_.append(len(i))
return res_list_
@show
def map_(list_):
return map(len, list_)
@show
def list_comprehension(list_):
return [len(i) for i in list_]
list_ = ["a", "bb", "ccc"]
assert for_loop(lis... |
69cab52c841abc15caa898d0602a5ece350c2e76 | abochkarev/simple-python-exercises | /test38.py | 357 | 3.546875 | 4 | def calc_words_average(file_name):
word_lens = 0
word_counts = 0
with open(file_name) as f:
while True:
data = f.readline().strip()
if not data:
break
word_lens += len(data)
word_counts += 1
return word_lens / word_counts
print ca... |
8e00e1ad02a850917c6bc6d04b5c827d65ca5ca0 | abochkarev/simple-python-exercises | /test1.py | 145 | 3.53125 | 4 | from common import show
@show
def max(a, b):
return a if a >= b else b
assert max(1, 3) == 3
assert max(3, 1) == 3
assert max(2, 2) == 2
|
dc4e919f72c815bbb536ee2a1533b2736ce2b7f3 | abochkarev/simple-python-exercises | /test43.py | 1,192 | 3.546875 | 4 | from collections import defaultdict
class FileReader(object):
def __init__(self, file_name):
super(FileReader, self).__init__()
self.file_name = file_name
def read_file(self):
with open(self.file_name, mode='r') as f:
while True:
line = f.readline()
... |
440598418bc4e3f8e9062e81d369bc770bbde4bc | anujpuri72/LeetCodeSubmissions | /MayChallenge/Week1/CousinsinBinaryTree.py | 1,408 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def lookup(self, root: TreeNode, x: int):
if (root == None):
return -999999
el... |
7d664b1fbf29656fc2244808a506cd3a83687a29 | jggautier/tabulate | /src/tabulate | 11,727 | 3.640625 | 4 | #!/usr/bin/env python3
import pdb
import argparse
import textwrap
import shutil
import itertools
from itertools import combinations_with_replacement
import logging
import sys
def make_parser():
parser = argparse.ArgumentParser(
description='Make fixed-width plaintext table with multi-line cell '
... |
a71c7b7eed40abbc353d208d3e214b448a57f807 | somayejalilii/python_project3 | /login.py | 1,438 | 3.734375 | 4 | import pandas as pd
import hashlib
import csv
class User:
def __init__(self, username, password):
self.password = password
self.username = username
@staticmethod
def log_in():
file_path = "account.csv"
def_account = pd.read_csv(file_path)
lst_username... |
7294ac7e6fa9a8e9d9b17cc661f639f7a04c289f | vdubrovskiy/Python | /new.py | 738 | 4.21875 | 4 | # -------------------------------------------------------
# import library
import math
# -------------------------------------------------------
# calculate rect. square
height = 10
width = 20
rectangle_square = height * width
print("Площадь прямоугольника:", rectangle_square)
# --------------------------------------... |
2c49b99944d44d68b6997edde1614acbc86bc301 | marcosmcz/The-Impact-of-The-Minimum-Wage-On-Other-Wages | /dataCleaningRound3.py | 2,293 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 20 01:38:04 2018
@author: User
"""
import pandas as pd
import numpy as np
df = pd.read_csv('minWageData.csv')
#####convert education column to ordered numerics
#create a dictionary
clean = {'Typical education needed for entry': {"Doctoral or professio... |
56c29eb34d1603305f5233dbc9003f46663fc8b8 | AmazedCape518/Python | /FuelEfficiency.py | 540 | 3.921875 | 4 | # Chap8ex9
# Luke De Guelle
# A program that determines the fuel efficiency
def main():
odometer = eval(input("Enter the starting odometer: "))
counter = 1
cont = 1
while(cont!= '\n')
print("Leg number ", counter,".")
odo = eval(input("Enter the odometer value: "))
gas = eval(input("Enter the amou... |
5d0fa3d6ddd3354a3865391afc456f234f733909 | Deepak-Vengatesan/Skillrack-Daily-Challenge-Sloution | /21-7-2021.py | 375 | 3.671875 | 4 | class Fruit:
count = 0
totalQuantity= 0
def __init__(self,name,quantity):
self.name = name
self.quantity = quantity
Fruit.count += 1
Fruit.totalQuantity += quantity
def __del__(self):
Fruit.count -= 1
Fruit.totalQuantity -= self.quantity
def __str__... |
716a6d37b848e9a87d458ad92c365f2292189ac5 | alialwahish/strsAndLists | /stringAndLists.py | 416 | 3.859375 | 4 | words = "It's thanksgiving day. It's my birthday,too!"
words=words.replace("day","month")
print(words)
x = [2,54,-2,7,12,98]
min =x[0]
max =x[0]
for val in x:
if val > max:
max=val
if val < min:
min=val
print "Max is:", max, "Min is:", min
y = ["hello",2,54,-2,7,12,98,"world"]
print "first wor... |
acf45ca7eb0ab0c92eaaf3bc52727ce8652f9f19 | nptit/Check_iO | /Scientific Expedition/verify_anagrams.py | 464 | 3.8125 | 4 | from collections import Counter
def verify_anagrams(x, y):
return True if Counter(a.lower() for a in x if a.isalpha()) == \
Counter(b.lower() for b in y if b.isalpha()) else False
if __name__ == '__main__':
assert isinstance(verify_anagrams("a", 'z'), bool), "Boolean!"
assert verify_anagrams("Pro... |
99494eb07c62209d729ebcc05fdf59ed3b2fe126 | nptit/Check_iO | /Mine/broken_clock.py | 1,438 | 3.59375 | 4 | def seconds_to_hms(seconds):
h, mins = divmod(seconds, 3600)
m, s = divmod(mins, 60)
return '{:0>2}:{:0>2}:{:0>2}'.format(h, m, s)
def to_seconds(time, t_value=None):
if isinstance(time, str):
return sum(int(a) * b for a, b in zip(time.split(':'), (3600, 60, 1)))
if t_value.startswith('sec... |
9842a1aa6dc27d12fba03027c00e0f2249455dc9 | nptit/Check_iO | /Home/median.py | 603 | 3.859375 | 4 | def checkio(lst):
length = len(lst)
lst = sorted(lst)
if length % 2 == 0:
mid = int(length / 2)
return (lst[mid] + lst[mid-1]) / 2
return lst[int(length / 2)]
if __name__ == '__main__':
assert checkio([1, 2, 3, 4, 5]) == 3, "Sorted list"
assert checkio([3, 1, 2, 5, 3]) == 3, "No... |
826a6ae785689b53d4d2bcc22310bd55ad124849 | nptit/Check_iO | /Alice In Wonderland/the_hidden_word.py | 1,219 | 3.8125 | 4 | from itertools import zip_longest
def checkio(text, word):
def result(start, line_num, horizontal=True):
if horizontal:
return [line_num, start + 1, line_num, start + len(word)]
return [start + 1, line_num, start + len(word), line_num]
horizontal = list()
for dex, line in enum... |
169fac0c9c3ca48eeca323770a8f476277bb45bf | nptit/Check_iO | /Incomplete/network_loops.py | 1,836 | 3.625 | 4 | def find_cycle(connections):
d = dict()
for a, b in connections:
try:
d[a].add(b)
except KeyError:
d[a] = {b}
print(d)
find_cycle(((1, 2), (2, 3), (3, 4), (4, 5), (5, 7),
(7, 6), (8, 5), (8, 4), (8, 1), (1, 5), (2, 4)))
# [1, 2, 3, 4, 5, 8, 1]... |
fe25a0f536bf2af5019f65aa6b24d47a75732947 | littlewhiteJ/LeetcodeSolutions | /867.py | 542 | 3.625 | 4 | # maybe best Solution
class Solution(object):
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
return [list(line) for line in zip(*A)]
'''
# my Solution
class Solution(object):
def transpose(self, A):
"""
:type A: List[Li... |
21f7c1a054fdf173f8ce0deeddc438600a277c49 | Sandy4321/pytorch-resample | /pytorch_resample/utils.py | 496 | 3.703125 | 4 | import math
import random
__all__ = ['random_poisson']
def random_poisson(rate, rng=random):
"""Sample a random value from a Poisson distribution.
This implementation is done in pure Python. Using PyTorch would be much slower.
References:
- https://www.wikiwand.com/en/Poisson_distribution#/Gen... |
37035e0594027f3bfc86c3c2a1b8cbe29d072df2 | luoluo964/Website-link-crawling-template | /main.py | 1,712 | 3.5 | 4 | import requests
import parsel
#返回页面的全部代码
def get_http(myurl):
#伪造的UA头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
}
response=requests.get(myurl,headers=headers)
data=response.text
data.en... |
b0cd7324e8b0835b40f9c1efbb48ff372ce54386 | adyrmishi/100daysofcode | /rock_paper_scissors.py | 843 | 4.15625 | 4 | rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''... |
14d8730bb5d268b254b63dd6230007ca584d1958 | Pokeluigi/Full_Moon_Escape | /for_and_while_loops.py | 1,987 | 3.875 | 4 | #favourite_drinks = ["coke", "fanta", "tonic"]
#for drink in favourite_drinks:
# print(drink)
#favourite_drinks = ["coke", "fanta", "tonic"]
#for i in favourite_drinks:
# print(i)
#for thing in iterable:
# do stuff
#for i in range(10):
# print(i)
#for i in range(0, 51, 5): #(start(the index... |
a8563b5a5cfb8fd42a1aa937a002a7c5bd49c1c7 | WRHR/python-notes | /basics/functions.py | 513 | 3.796875 | 4 | # A function is a block of code that only runs when it is called, no braces uses indentation with tabs and spaces
# create func
def sayHello(name = 'Human Person'):
print(f'Hello {name}')
sayHello('Bob')
sayHello()
# Return val
def getSum(num1, num2):
total = num1 + num2
return total
getSum(25, 5)
# A lam... |
8f3bb29526d1e093ebee5a5fa33c07cbfa56d2b5 | gustavo-depaula/stalin-sort | /python/benchmark.py | 611 | 3.546875 | 4 | import timeit
# tests a sort function on list of lengths 10 to ten million.
def benchmark(sort_fun):
length_exponents = [1, 2, 3, 4, 5, 6, 7]
repetitions = 10
for exponent in length_exponents:
length = 10 ** exponent
res = benchmark_length(sort_fun, length, repetitions)
print(f'Sorting {repetitions} ... |
c9d9129901ca087a89f82d58c68a45bf3b35cf0a | neuwangmq/gitskill | /iterator.py | 132 | 3.921875 | 4 | d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print key
for value in d.itervalues():
print value
for k,v in d.iteritems():
print k,v |
bc34228e297b625d332ca96e085857eae76beb9f | neuwangmq/gitskill | /multi.py | 43 | 3.5625 | 4 | a = input("input a number:\n")
print(a*a)
|
53bf0300d334909355777fa043e37beb823bd7d2 | NixonRosario/Encryption-and-Decryption | /main.py | 2,772 | 4.1875 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
# The Encryption Function
def cipher_encrypt(plain_text, key): # key is used has an swifting value
encrypted... |
93e90078409a13ca5d54b0aa6a19af1d8df6bb76 | jake-stewart/pygrid | /draw_grid.py | 3,348 | 3.53125 | 4 | from pygrid import PyGrid
import math
# adds drawing functionality
# when using a mouse, mouse events are sent periodically
# that means mouse events will not register for every cell
# this class figures out which cells the mouse traversed over
# and sends them to an on_mouse_event method
class DrawGrid(PyGrid):
... |
2c08ad7796c277e07d58e22085a4eaeba6f380fb | zhaoyongjun0911/- | /个人项目/0-1背包问题.py | 5,381 | 3.984375 | 4 | # 三维列表,存放整个文件各组数据价值的列表,该列表分为若干子列表,每个子列表用于存储一组价值数据,每个子列表的数据又按照三个一组分为若干个列表
global profit
profit = []
# 三维列表,存放整个文件各组数据重量的列表,同profit
global weight
weight = []
# 三维列表,存放整个文件各组数据价值-重量-价值重量比的列表,该列表分为若干子列表,每个子列表用于存储一组价值-重量-价值重量比数据,每个子列表
# 的数据为一个九元组,包含三条价值数据-三条重量数据-三条价值重量比信息
global prowei
prowei = []
# 存放价值初始数据,即刚读入并... |
69b6abc0b48b7aeba70e606d7a7e17542cd09924 | judsonwebb/SportsAnalytics | /Regression.py | 6,840 | 3.703125 | 4 | """
Sports Analytics
"""
import numeric
import codeskulptor
import urllib2
import comp140_module6 as sports
def read_matrix(filename):
"""
Parse data at the input filename into a matrix.
"""
ordered_data=[]
url = codeskulptor.file2url(filename)
netfile = urllib2.urlopen(url)
for line in ne... |
5bf3ff360b4e18e36467b50b865514e3f8eaef89 | peterdocter/small-spider-project | /synchronous/sample/thread_test1.py | 836 | 3.796875 | 4 | import _thread
import threading
import time
def _thread_handle(thread_name, delay):
for num in range(10):
time.sleep(delay)
print("{}的num:{}".format(thread_name, num))
def threading_handle(delay=1):
for num in range(10):
time.sleep(delay)
print("{}-num-{}".format(threading.cu... |
249e0802f3665f16a695b84faef88692ba7dfa25 | taruchit/CodeChef_Beginner | /Flow010.py | 395 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 13 16:43:13 2021
@author: pc
"""
#Number of testcases
T=int(input())
#Input, computation and output
for i in range(T):
id=input()
if(id=='B' or id=='b'):
print("BattleShip")
elif(id=='C' or id=='c'):
print("Cruiser")
elif(id=='D' or id=='... |
a9ccfc50a33f44b713443d50c365faf62abb495e | taruchit/CodeChef_Beginner | /Flow013.py | 314 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 13 11:23:00 2021
@author: pc
"""
#Number of testcases
T=int(input())
#Input, computation and output
for i in range(T):
N=input().split(" ")
A=int(N[0])
B=int(N[1])
C=int(N[2])
if((A+B+C)==180):
print("YES")
else:
print("NO") |
8a14238ded132a4ce8ff644f3cf5ac6b99c619d8 | taruchit/CodeChef_Beginner | /SecondLargest.py | 328 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 9 23:29:54 2021
@author: pc
"""
#Number of testcases
T=int(input())
#Input, Computation and Output
for i in range(T):
temp=input().split(" ")
N=list()
N.append(int(temp[0]))
N.append(int(temp[1]))
N.append(int(temp[2]))
N.sort()
print(N[1])
... |
29d0f0a5b83dbbcee5f053a2455f9c8722b6cb51 | MrYsLab/pseudo-microbit | /neopixel.py | 2,943 | 4.21875 | 4 | """
The neopixel module lets you use Neopixel (WS2812) individually
addressable RGB LED strips with the Microbit.
Note to use the neopixel module, you need to import it separately with:
import neopixel
Note
From our tests, the Microbit Neopixel module can drive up to around 256
Neopixels. Anything above that and yo... |
630ce08828c6dbb4c9121499ea76b21374e97efa | sminix/skill-challenges | /word_funnel1.py | 2,293 | 3.796875 | 4 | '''
Sam Minix
5/28/2020
https://www.reddit.com/r/dailyprogrammer/comments/98ufvz/20180820_challenge_366_easy_word_funnel_1/
Given two strings of letters, determine whether the second can be made from the first by removing one letter.
The remaining letters must stay in the same order.
'''
def word_funnel1 (str1, str2):
... |
9d7df65d3a7a46a8c762c189d76bdebc04db78a9 | Baude04/Translation-tool-for-Pirates-Gold | /fonctions.py | 299 | 4.1875 | 4 | def without_accent(string):
result = ""
for i in range(0,len(string)):
if string[i] in ["é","è","ê"]:
letter = "e"
elif string[i] in ["à", "â"]:
letter = "a"
else:
letter = string[i]
result += letter
return result
|
638715d691110084c104bba50daefd5675aea398 | baif666/ROSALIND_problem | /find_all_substring.py | 501 | 4.25 | 4 | def find_all(string, substr):
'''Find all the indexs of substring in string.'''
#Initialize start index
i = -1
#Creat a empty list to store result
result = []
while True:
i = string.find(substr, i+1)
if i < 0:
break
result.append(i)
return result
... |
752ab686e61aef181c8301fbc5a0b7b5f3c4f6a5 | eldq5d/UMKC-490-Python | /Lab2/Task 2.2.py | 326 | 3.9375 | 4 | # With any given number n, Write a program to generate a dictionary that contains (k, k*k).
# Print the dictionary generated and the series should include both 1 and k.
n = int(input("Enter an integer to create a dictionary: "))
dictionary1 = {}
for i in range(1, n+1):
dictionary1[i] = i*i
i += 1
print(diction... |
f17fa85bade1d23b68e4ef8516eb587d3a0f63f3 | maliksh7/Data-Structure-and-Algorithms-in-Python | /Assignments/a08/a08.py | 2,087 | 3.703125 | 4 | class HashMap:
def __init__(self):
self.size = 10
self.map = [None] * self.size
def _get_hash(self, key):
if type(key) == int:
return key % 10
if type(key) == str:
return len(key) % 10
if type(key) == tuple:
return len(key) % 10
def add(self, key, value):
hashed_key = self._get_hash(key)
... |
8da0284269b489e21ea98fedc85936c64618c917 | maliksh7/Data-Structure-and-Algorithms-in-Python | /a06/a06.py | 4,070 | 3.5625 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def dfs(self):
print(self.val)
if self.left:
self.left.dfs()
if self.right:
self.right.dfs()
def dfs_inoder(self):
if self.left:
self.left.dfs_inoder()
... |
32ef8db9fd30ff2bfb08c19dfde5c0733bb80767 | vinobc/UGE1176 | /nmbrs.py | 402 | 4.03125 | 4 | #!/usr/local/bin/python3
from decimal import Decimal
def main():
x = Decimal(".20")
y = Decimal(".60")
a = x + x + x - y
print(f"a is {a}")
print(type(a))
# b = 10/3
# print(f"b is {b}")
# print(type(b))
# c = 10//3
# print(f"c is {c}")
# print(type(c))
# d = 10**3
# ... |
26057466c749ab510bd9b99790af6b0eb93b5cf0 | vinobc/UGE1176 | /while.py | 290 | 3.8125 | 4 | pwd = "octopus"
res = ""
user_auth = False
attempt = 0
max_attempts = 3
while res != pwd:
attempt += 1
if attempt > max_attempts: break
res = input("Enter the password:")
else:
user_auth = True
print("Successfully logged in" if user_auth else "try again in one hour..") |
3cc4e9f05c3e59dea68ad6604b87117b859d377a | LouisKamp/unipython | /Exercise project 1/data_load.py | 1,359 | 4.09375 | 4 | # %%
import numpy as np
import pandas as pd
from pandas.core.frame import DataFrame
from constants import dataColumn, bacteriaValues
# %%
def dataLoad(filename: str) -> DataFrame:
"""Loads data from a space separated values file
Keyword arguments:
filename: str -- The name of the file to be loaded
R... |
82bad5160889c903a78a44a5a470627302bd73ec | oregzoltan/trial-exam-python-2016-06-06 | /2.py | 444 | 3.84375 | 4 | # Create a function that takes a filename as string parameter,
# and counts the occurances of the letter "a", and returns it as a number.
# It should not break if the file not exists just return 0
def count_a(name):
try:
f = open(name)
text = f.read()
except:
return 0
f.close()
... |
805d6f805b9f558ac4a2d19e706b211173938a19 | pritesprite/prite | /game.py | 2,508 | 3.5 | 4 | #all immport
import random
import time
#Set up command
class Player():
def __init__(self):
self.player_hungry = 2
self.player_health = 10
self.inventory = {}
def has_item(self,item):
item_count = self.inventory.get(item, 0)
if item_count > 0:
r... |
3e562ee261acc916e0c25a44f5b4084c5489eb68 | setsumei1974/AlienArmageddon | /alien_invasion.py | 1,238 | 3.5625 | 4 | #Module for Functionality of the Game
import pygame
from pygame.sprite import Group
#Module to Import Settings
from settings import Settings
#Module to Import the Ship
from ship import Ship
#Module to Import the Alien
from alien import Alien
#Module to Import the Functions of the Game
import game_functions as gf
d... |
08c0b696d0bc9a5a584881af22d71378dcc06515 | crazynoodle/Noodle-s-git | /python-code/fib.py | 226 | 3.96875 | 4 | def fib2(n): #return Fibonacci series up to n
"""Return a list containing the Fibonacci series up to n."""
result = []
a,b = 0,1
while a < n:
result.append(a) # see below
a,b = b,a+b
return result
|
b126f74d86f783cafb4639aeb4aeb01587496a27 | dennisurtubia/Automato-Finito | /src/estado.py | 580 | 3.796875 | 4 | class Estado:
def __init__(self, nome):
""" Description
Método construtor de estado, define os atributos que um estado deve ter
:type nome: str
:param nome: Nome ou descrição do estado
"""
self.nome = nome
self.inicial = False
self.final = False
def getNome(self):
... |
b0cad0b1e60d45bc598647fa74cb1c584f23eeaa | JGMEYER/py-traffic-sim | /src/physics/pathing.py | 1,939 | 4.1875 | 4 | from abc import ABC, abstractmethod
from typing import Tuple
import numpy as np
class Trajectory(ABC):
@abstractmethod
def move(self, max_move_dist) -> (Tuple[float, float], float):
"""Move the point along the trajectory towards its target by the
specified distance.
If the point woul... |
4716a82fc74372b92fb9cf7e0d068cf3bbc662ac | carlosvcerqueira/Projetos-Python | /ex036.py | 437 | 3.859375 | 4 | casa = float(input('Valor da casa: R$'))
salario = float(input('Salário do comprador: R$'))
prazo = int(input('Quantos anos de financiamento? '))
prestação = casa / (prazo * 12)
mínimo = salario * 30 / 100
print('Para pagar uma casa de R${:.2f} em {} anos a prestação será de R${:.2f}.'.format(casa, prazo, prestaçã... |
9f49c6b3aebb19090fffff52065ef0b1230d4549 | carlosvcerqueira/Projetos-Python | /ex038.py | 363 | 4.09375 | 4 | from time import sleep
print('-=-'* 10)
print('ANALISADOR DE NÚMEROS')
print('-=-' * 10)
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
print('ANALISANDO...')
sleep(3)
if n1 > n2:
print('O primeiro valor é maior.')
elif n1 < n2:
print('O segundo valor é maior.')
else:... |
8a9af8bdf68db8fda144b35601ca9dab76408632 | carlosvcerqueira/Projetos-Python | /ex031.py | 201 | 3.75 | 4 | km = float(input('Quantos km você irá viajar? '))
if km <= 200:
print('O valor da passagem é R${:.2f}'.format(km * 0.50))
else:
print('O valor da passagem é R${:.2f}'.format(km * 0.45)) |
e373a41f098dcdafad1fe9c6d97ec298aac91cad | carlosvcerqueira/Projetos-Python | /ex045.py | 1,281 | 3.765625 | 4 | from time import sleep
from random import randint
itens = ('Pedra', 'Papel', 'Tesoura')
computador = randint(0, 2)
print('''Suas opções:
[0] PEDRA
[1] PAPEL
[2] TESOURA''')
jogador = int(input('Qual sua jogada? '))
print('PEDRA...')
sleep(0.7)
print('PAPEL...')
sleep(0.7)
print('TESOURA!!!')
sleep(1)
pri... |
778390bb9e7055402c0d55bd63d14c4e2086a827 | soldierloko/Curso-em-Video | /Ex_44.py | 1,267 | 3.765625 | 4 | #Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento:
#A vista Dinheiro ou Cheque: 10% de Desconto
#A vista no cartão: 5% de Desconto
#2x No cartão: preço normal
#3x ou mais no cartão: 20% de juros
vProduto = float(input('Digite o valor do Produto... |
b652abe6ca74239b17389be5f7a947fab50069d3 | soldierloko/Curso-em-Video | /Ex_41.py | 588 | 4.0625 | 4 | #A confederação nacional de natação precisa de um programa que leia o ano de nascimento de um atleta e mostre sua categoria, de acordo com a idade
#Até 9 anos: MIRIM
#Até 14 anos: INFANTIL
#Até 19 anos: JUNIOR
#Até 20 anos: SÊNIOR
#Acima: MASTER
from datetime import date
vAno = int(input('Digite o ano de Nascimento: ... |
2c437396a0a3fd9686bbf94fdec8445c42c1f649 | soldierloko/Curso-em-Video | /Ex_58.py | 735 | 4.0625 | 4 | #Melhore o Jogo Desafio 028 onde o computador vai pensar em um n´úmro entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer.
from random import randint
vPc = randint(0,10)
print('Acabei de pensar em um númerp entre 0 e 10.')
print('Ser... |
220f08fca0713fc8ed3c2ce02e23fbc24eb45165 | soldierloko/Curso-em-Video | /Ex_82.py | 642 | 4.0625 | 4 | #Crie um programa que vai ler vários números e colocar em uma lista
#Depois disso, crie duas listas extras que vão conter apenas os valores pares e impares digitados, respectivamentes
#Ao final, mostre o conteúdo das 3 listas geradas
lista = []
par = []
impar = []
while True:
n = int(input("Digite um número: "))... |
a5209df360f77046a2fdbd832238265a0461e478 | soldierloko/Curso-em-Video | /Ex_38.py | 503 | 3.859375 | 4 | #Escreva umn programa que leia 2 números inteiros e compare-os, mostrando na tela uma mensagem:
#O Primeiro valor é maior
#O Segundo valor é menor
#Ambos os valores são iguais
vn1 = int(input("Digite o Primeiro Valor: "))
vn2 = int(input("Digite o Segundo Valor: "))
if vn1>vn2:
print('O primeiro Valor {} é maior... |
6dd66f64267394e60fe06601a74f39f9b15ac48f | Aaryan-kapur/hactktoberfesttimebois2021 | /AvastYe.py | 5,609 | 3.953125 | 4 | #You are a part of a pirate ship that survives by looting islands. Your crew has the
#responsibility of devising a plan to efficiently rob the islands where each island is divided
#into smaller land parts due to the river flowing through it. Each land part is joined to another
#land part by a bridge. (i.e. one land par... |
3be669c9b967be7ac8e0d3601b7793842e34d2c5 | xia0nan/Project-Euler | /problem015.py | 554 | 3.5 | 4 | """
Author: Nan <xnone0104@gmail.com>
https://projecteuler.net/problem=15
[Lattice paths]
Starting in the top left corner of a 2×2 grid,
and only being able to move to the right and down,
there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
"""
def count_... |
b651ff2da4c5f138ee573fa738e96326476e8bd0 | xia0nan/Project-Euler | /problem003.py | 663 | 3.796875 | 4 | __author__ = "xiaonan"
"""
Largest prime factor
Problem 3
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
def isprime(number):
if number < 2:
return False
elif number == 2 or number == 3:
return True
elif number % 2 == 0 or number % 3 == 0:
... |
5854831f486c7fc9fa8ff44083186ba604419c3b | xia0nan/Project-Euler | /problem006.py | 450 | 3.703125 | 4 | __author__ = "xiaonan"
"""
Solution for: https://projecteuler.net/problem=6
"""
def sum_of_square(number):
result = 0
for i in xrange(number):
result += (i+1)**2
print "sum_of_square", result
return result
def square_of_sum(number):
result = 0
for i in xrange(number):
result += i + 1
print "square_of_sum"... |
affa5bd44bd4bd55231e33e2cae6abf86a3b2a82 | usupsuparma/Object-Oriented-Programming-Python | /Getter and Setter.py | 784 | 3.796875 | 4 | class Hero:
def __init__(self, name, armor, health):
self.name = name
self.__armor = armor
self.__health = health
@property
def info(self):
return "name {} : \n\thealth {} \n\tarmor {}".format(self.name, self.__health, self.__armor)
@property
def armor(self):
... |
cbbe2621cdcb691ad6046ed26e1b70038ed8d8bd | stepheneasleywalsh/computerProgrammingIWeek5Lesson2 | /main.py | 484 | 3.859375 | 4 | # THE BIO FUNCTION
def bio(name,born,pronoun):
age = 2021-born
future = born+67
print("----------------------------------------")
print(name.capitalize(), "was born in", born)
print(pronoun.capitalize(), "will turn", age, "years old this year")
print(pronoun.capitalize(), "will be 67 in the year... |
e28dc8156acba525f2fdf65ea3cc9fc990770114 | AdorableNewYs/learn_sicp | /practice_1_19.py | 328 | 3.703125 | 4 | def even(n):
return n % 2 == 0
def fib(n):
def fib_iter(a,b,p,q,count):
if count == 0:
return b
elif even(count):
return fib_iter(a,b,p*p + q*q,2*p*q + q*q,count / 2)
else:
return fib_iter(b*q + a*q + a*p,b*p + a*q,p,q,count-1)
return fib_iter(1,0... |
ad9c8bed2c23d82a0df3a4e65ce05df16c9032ea | Utkarshmalik99/Python | /Python_Program_for_n-th_Fibonacci_number.py | 198 | 4.21875 | 4 | n=int(input("enter the n'th number:"))
def fibonacci(n):
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
print("N'th fibonacci number is ",fibonacci(n))
|
c7660f95432c083ccc5af38f284d340ea33db9d9 | Utkarshmalik99/Python | /Python Program for simple interest.py | 313 | 3.890625 | 4 | def simple_interest(p,r,t):
if p==0 or r==0 or t==0:
return 0
else:
simple_interest=(p*r*t)/100
return simple_interest
p=int(input("enter the value of p: "))
r=int(input("enter the value of r: "))
t=int(input("enter the value of t: "))
print("simple_interest is ",simple_interest(p,r,t))
|
b32db989e7f68bf9b1bc7b93739dc8e353db82cb | Utkarshmalik99/Python | /Sum_of_squares_of_first_n_natural_numbers.py | 205 | 4.09375 | 4 | n=int(input("enter the n'th natural number:"))
def squareSum(n):
sum=0
for n in range(1,n+1):
sum+=(n*n)
return sum
print("Sum of squares of first n entered natural numbers is",squaresum(n))
|
fd340d5fef141c91bbcb13c89cfe22cbcea0ccce | MarcosParengo/Unsam-2do-cuatri-2021 | /mate III/clase 4 pruebas/graficos/6. zip y leyendas/main.py | 512 | 3.6875 | 4 | import matplotlib.pyplot as plt
zip_generator=zip([1,2,3,4,5],[60,70,80,90,100])
x,y=zip(*zip_generator)
print(x)
print(y)
plt.figure()
plt.scatter(x[:3],y[:3],s=100,c='red',label='Ingresos más bajos')
plt.scatter(x[2:],y[2:],s=50,c='green',label='Ingresos más altos')
#x[:2],y[:2] -> ((1, 2), (60, 70))
#x[2:],y[2:] -> ... |
332b8139b6d2b2e56a93720a436b40a1b8827807 | bingecodingJC/NLPTA-Group-Flying-Circus | /data_merge.py | 5,522 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 4 10:14:22 2018
@author: ZHANG Xin(Serene)
"""
import pandas as pd
from datetime import datetime
from datetime import timedelta
def month_transfer(month):
# this function is to convert the type of month
if month == 'January':
month_number = 1
if mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.