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 |
|---|---|---|---|---|---|---|
bd0d86565d9a8380c8ede6fc6a36249d4b134ffb | arabindamahato/personal_python_program | /risagrud/function/actual_argument/default_argument.py | 690 | 4.5625 | 5 | ''' In default argument the function contain already a arguments. if we give any veriable
at the time of function calling then it takes explicitely . If we dont give any arguments then
the function receives the default arguments'''
'''Sometimes we can provide default values for our positional arguments. '''
def wish(... |
90aba704a0cf75e1359c3585d1986dbb7a5b826d | arabindamahato/personal_python_program | /programming_class_akshaysir/find_last_digit.py | 353 | 4.28125 | 4 | print('To find the last digit of any number')
n=int(input('Enter your no : '))
o=n%10
print('The last digit of {} is {}'.format(n,o))
#To find last digit of a given no without using modulas and arithmatic operator
print('To find last digit of a given no')
n=(input('Enter your no : '))
o=n[-1]
p=int(o)
print('The las... |
1005780057842370fb6348a74f77054eb42a71f7 | Laurensvaldez/PythonCrashCourse | /CH5: If Statements/try_it_yourself_ch5_5_10.py | 545 | 4.03125 | 4 | # do the following to create a program that simulates how websites ensure that everyone has a unique username
current_users = ['laurens', 'rensley', 'jeremy', 'ian', 'ergin']
new_users = ['jonathan', 'khristian', 'domingo', 'ian', 'ergin']
current_users_lower = [user.lower() for user in current_users]
for new_user i... |
e4bc895b6c639fda81703d162b07034888231d50 | Laurensvaldez/PythonCrashCourse | /CH8: Functions/try_it_yourself_ch8_8_8.py | 986 | 4.375 | 4 | # Start with your program from exercise 8-7. Write a while loop that allows users to enter an album's artist and title.
# Once you have that information, call make_album() with the user's input and print the dictionary that's created.
# Be sure to include a quit value in the while loop.
def make_album(artist, title, t... |
9cb4ce71d22344f24e1d3cc338bb9e83ed1ad3ad | Laurensvaldez/PythonCrashCourse | /CH8: Functions/making_pizzas.py | 1,837 | 4.3125 | 4 | # In this file we will import the function of pizza_import.py
import pizza_import
print("Importing all the functions in the module")
pizza_import.make_pizza(16, 'pepperoni')
pizza_import.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
print("-------------------------------------------")
# To use the import... |
fce2b46e2edfe1a84b98b69cdebf3fc7ac90d97b | Laurensvaldez/PythonCrashCourse | /CH5: If Statements/try_it_yourself_ch5_5_6.py | 410 | 3.9375 | 4 | # write an if-elif-else chain that determines a person's stage of life. Set a value for the variable age, and then:
person = int(1.99)
if person <2:
print ("You are a baby.")
elif person <4:
print ("You are a toddler.")
elif person <13:
print("You are a kid.")
elif person <20:
print("You are a teenage... |
146541bd8096d3dada3b6b651f7d74caf3d8fe68 | Laurensvaldez/PythonCrashCourse | /CH9: Classes/9-6_ice_cream_stand.py | 2,095 | 4.5625 | 5 | # Write a class called IceCreamStand that inherits from the Restaurant class you wrote in Exercise 9-1 or Exercise 9-4
# Either version of the class will work; just pick the one you like better
class Restaurant:
"""A simple restaurant class"""
def __init__(self, restaurant_name, cuisine_type):
"""Initi... |
f14e51cff185f2277385b1a0d580fd0a077e7195 | Laurensvaldez/PythonCrashCourse | /Ch6: Dictionaries/try_it_yourself_ch6_6_1.py | 514 | 4.3125 | 4 | # Try it yourself challenge 6-1
# Person
# Use a dictionary to store information about a person you know.
# Store their first name, last name, age, and the city in which they live. You should have keys such as
# first_name, last_name, age, and city. Print each piece of information stored in your dictionary.
person = ... |
755616213684796cb48d924e5bf927e994e030d1 | Laurensvaldez/PythonCrashCourse | /CH4: working with lists/try_it_yourself_ch4_4_11.py | 500 | 4.21875 | 4 | print ("More Loops")
# all versions of foods.py in this section have avoided using for loops when printing to save space
# Choose a version of foods.py, and write two for loops to print each list of foods
my_foods = ['pizza', 'falafel', 'carrot cake']
print ("My favorite foods are: ")
for food in my_foods:
print... |
42f2ffcbb27880696f75427c05e0977c1432c0ed | Laurensvaldez/PythonCrashCourse | /CH8: Functions/try_it_yourself_ch8_8_14.py | 415 | 3.671875 | 4 | def make_car(manufacturar, model, **extra_info):
"""Write function that stores information about a car in a dictionary."""
car_dict = {}
car_dict['manufacturar_name'] = manufacturar.title()
car_dict['model_name'] = model.title()
for key, value in extra_info.items():
car_dict[key] = value
... |
2593aeaf239015183c48861a96af3d1feb21d6d3 | Laurensvaldez/PythonCrashCourse | /CH9: Classes/9-5_login_attempts.py | 2,622 | 4.46875 | 4 | # Add an attribute called login_attempts to your User class from Exercise 9-3
class User:
"""A class to describe a user"""
# Create two attributes called first_name and last_name
# and then create several other attributes that are typically stored in a user profile
def __init__(self, first_name, last_n... |
a4ca9323e0c5bbd2cd4f81cb49151482d2a3d802 | phu-mai/calculate | /calculate.py | 777 | 4.125 | 4 | from datetime import datetime
def string_to_date(input):
return datetime.strptime(input, "%d/%m/%Y")
def check_date(input):
if string_to_date(input) < datetime.strptime("01/01/1900", "%d/%m/%Y") or string_to_date(input) > datetime.strptime("31/12/2999", "%d/%m/%Y"):
return False
else:
retu... |
0503c26bc5c814aba63beb1ac0781db0ce194f5f | dzwduan/CS61A | /Lec/Lec09/gcd.py | 300 | 3.90625 | 4 | #python3 -m doctest -v ex.py
def gcd(m,n):
"""Returns the lagest k that divides both by m and n.
k,m,n are all positive integers.
>>> gcd(12,8)
4
>>> gcd(20,40)
20
"""
if m==n:
return m
elif m<n:
return gcd(n,m)
else:
return gcd(m-n,n) |
3f64bed0bc77f15de807b3694b294240e6b3a93b | bmcclannahan/sort-testing | /sorts.py | 611 | 3.90625 | 4 |
def is_sorted(arr):
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
return False
return True
def swap(a, b, arr):
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
def insertion_sort(start, end, arr):
for i in range(start, end):
curr = i
while curr >= 1 and arr... |
bf6296c1d7583330c86b7670cdb4dca12e286e24 | thinkofmia/Team-MIA-Shopee-Code-League-2021 | /03 Programming Contest/shoffee.py | 1,423 | 3.6875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
from itertools import combinations
#
# Complete the 'maxSubstring' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING s as parameter.
#
def findShoffee(coffeeBeanAndExpectation, prefere... |
92b8f79687ebc4dafcc3014653d95f13330b5852 | saulmont/programacion_python | /Bases/Practica/repaso_8.py | 660 | 3.578125 | 4 | def suma(abc, defg, hijk):
return abc + defg + hijk
def resta(abc, defg, hijk):
return abc - defg - hijk
def multiplicacion(abc, defg, hijk):
return abc * defg * hijk
def division(abc, defg):
return abc / defg
for i in range(0, 101, 2):
print("Cargando", i , "% completo")
resultado = resta... |
e82a2b73a4cdccef5721a26f75dd1a90d43137b6 | saulmont/programacion_python | /Bases/Practica/repaso_9.py | 614 | 3.796875 | 4 | var_numeral = 12 # esta variable es global y puede ser accedida desde cualquier lugar del codigo.
def crear_variable():
var_numeral = 98 # esta variable es local y solo puede ser accedida desde esta funcion.
print(var_numeral)
def modificar_variable():
global var_numeral # esta accediendo a la variable gl... |
8a948203bc68f0fefd919a34ecd810cfd60c11f9 | saulmont/programacion_python | /Algoritmos/Numeros.py | 166 | 4.09375 | 4 | numero = int(input("Ingrese un numero: "))
if numero %2 ==0:
print("El Numero que has ingresado es par")
else:
print("El Numero que has ingresado es Impar") |
3cc14a8cad1ca03776f4b406dd5b4d203ff1d47d | saulmont/programacion_python | /Algoritmos/elevar_exponente.py | 337 | 3.953125 | 4 | base = int(input("Ingrese la base: "))
exponente = int(input("Ingrese el exponente: "))
acumulador = 1
contador = 0
if exponente == 0:
print("El resultado es: ", exponente)
else:
while contador < exponente:
acumulador = acumulador * base
contador = contador + 1
print("El resultado es: ", ... |
0554177b38e7da60432866c00f5535e41f41bf29 | shah-farheen/data_wrangling | /xls_parser.py | 3,458 | 3.546875 | 4 | import csv
import xlrd
datafile = "2013_ERCOT_Hourly_Load_Data.xls"
example_file = "example.csv"
def parse(datafile):
workbook = xlrd.open_workbook(datafile)
sheet = workbook.sheet_by_index(0)
data = [[sheet.cell_value(r, col) for col in range(sheet.ncols)] for r in range(sheet.nrows)]
print "\nLis... |
b2735390b25903d298a497dfb616d306cc0540e9 | JoaquinFarfan/TSI_repo1 | /Factorial.py | 182 | 3.90625 | 4 | import math
def factorial(x):
factorial = math.factorial(x)
return factorial
x = int(input('Ingrese un numero entero: '))
print('El factorial de ',x,' es',factorial(x)) |
56490d658082b16ec7ec9140147f0e3e0544c630 | subhendu17620/RUAS-sem-04 | /PP/Java/lab03/a.py | 1,391 | 4.1875 | 4 | # Python3 program to print all Duplicates in array
# A class to represent array of bits using
# array of integers
class BitArray:
# Constructor
def __init__(self, n):
# Divide by 32. To store n bits, we need
# n/32 + 1 integers (Assuming int is stored
# using 32 bits)
self.arr = [0] * ((n >> 5) + ... |
bda7c73b238715ee9b7fb75b3e6de0fed8f1aca5 | jrperlic/data-structure-tutorial | /code/1-problem-solution.py | 312 | 3.953125 | 4 | shelf = input()
stack = []
for item in shelf:
if item == "[":
stack.append(item)
elif item == "]":
if len(stack) == 0 or stack.pop() != "[":
print("False")
exit()
elif item == "|":
continue
else:
print("False")
exit()
print("True") |
e0b2b7001dede40fc01f2f06d8bbb6d62c1d6f2b | Guthixx23/IBS_Assignment_Wanderer_app | /wanderer/character.py | 5,422 | 3.5 | 4 | import random
# Parent class for Skeleton, Boss, and Hero
class Character():
def __init__(self):
self.hp = 0
self.dp = 0
self.sp = 0
self.current_hp = 0
self.level = 0
self.position_row = 0
self.position_col = 0
# 6 side dice roll
def roll_d6(self)... |
167c5c40a3cca81e5bcff9a86f8c75373703a30f | mohit242/SPOJ-Solutions | /FCTRL2.py | 202 | 3.53125 | 4 |
# coding: utf-8
# In[6]:
def fact(i):
if i==0 or i==1:
return 1
return fact(i-1)*i
num_cases=int(raw_input())
for i in range(num_cases):
inp=int(raw_input())
print fact(inp)
|
e775843d534f446bb0b4b2539be15b3c0f0d4f21 | TheUnknownCurry/psesudocode-and-python-code- | /assignment.py | 3,630 | 4.03125 | 4 | import random
attempts_list=[]
def start_game():
random_number=int(random.randint(1,50))
print("Hello, Gamer ")
print("Welcome To The Number Guessing Game ")
print("Let's Play An Interesting Game Were You Have To Guess A Number ")
print("A Number Which I Am Thinking Right Now ")
pr... |
f600b3970b3c556a9aa03af8d6ef7b1f1dd124f7 | MirjaLagerwaard/MountRUSHmore | /main.py | 1,500 | 4.28125 | 4 | import sys
from algorithm import *
if __name__ == "__main__":
# Error when the user did not give the right amount of arguments
if len(sys.argv) <= 1 or len(sys.argv) > 3:
print "Usage: python main.py <6_1/6_2/6_3/9_1/9_2/9_3/12> <breadth/depth/random>"
exit()
# update fp to the CSV file t... |
cefed8ceb330309a398607fbd2feffe9c87fcd49 | fabienf/SDP2015 | /planning/utilities.py | 2,642 | 3.5 | 4 | from math import tan, pi
def is_shot_blocked(world, angle_to_turn=0):
"""
Checks if our robot could shoot past their robot
"""
predicted_y = predict_y_intersection(
world, world.their_attacker.x, world.our_defender, full_width=False, bounce=True, angle_to_turn=angle_to_turn)
if predicted_... |
6e637521ca94000db1c04e3f798984d183244d0d | Test01DezWebSite/KattisDemos | /helpaphd/helpaphd.py | 601 | 3.609375 | 4 | #! /usr/bin/env python3
import sys
def answer(equation):
result = 'skipped'
try:
result = eval(equation)
except:
pass
return result
def solve():
data = sys.stdin.readlines()
ans = []
for line in data[1:]:
ans.append(str(answer(line)))
print('\n'.join(ans))
... |
351e04dbcd8cd47a887a4b8bf388c14b88672b5d | danieloved1/anigma | /main.py | 7,807 | 3.65625 | 4 | import json
day = input("Enter day:\n")
while int(day) < 1 or int(day) > 7:
day = input("Enter day:\n")
# ----------------- Enigma Settings -----------------
reflector = "UKW-B"
file = open("code-book.json")
data = file.read()
data = json.loads(data)
dailyConfig = data[day]
rotors = dailyConfi... |
5ba04f2a2ab1f498f565e9aa2c9f2d14a7e46771 | maxjackson705/Python-Practice | /collections.py | 285 | 3.71875 | 4 | my_list = ['p', 'r', 'o', 'b', 'e']
my_list2 = [10, 20, 30, 40]
print(my_list2)
print(my_list[0])
print(my_list[2])
print(my_list[4])
n_list = ["Happy", [2, 0, 1, 5]]
print(n_list[0][1])
print(n_list[1][3])
print(my_list[2:5])
for item in my_list2:
print(item)
|
0a1ba8bcf84ab53fa0d2d5fc8b1702142d945ed5 | AscendentFive/Python | /FuncionMAP.py | 150 | 3.609375 | 4 | def operador(n,m):
if n==None or m==None:
return 0
return n+m
l1 = [1,2,3,4]
t1 = (9,8,7,6)
lr = map(operador,l1,t1)
print l1
print t1
print lr |
02cfb2e06082639aeed0be7813753611b2101560 | AscendentFive/Python | /diccionarios.py | 155 | 3.796875 | 4 | d = {'Clave1':[1,2,3],
'Clave2':True,
4:True
}
print d['Clave1']
print d['Clave2']
print d[4]
#Cambiar una clave
d[4] = "Hola He cambiado"
print d[4] |
a6bf630f2b172e307da8e72f982a58b750f15fa7 | AscendentFive/Python | /FuncionOrdenSuperior.py | 243 | 3.546875 | 4 | def seleccion(operacion):
def suma(n,m):
return n+m
def multiplicacion(n,m):
return n*m
if operacion == "suma":
return suma
elif operacion == "multi":
return multiplicacion
fGuardada = seleccion("multi")
print fGuardada(12,12)
|
f19270953319dd13b4647d50ab6d48efec6c2abd | mannurulz/Machine_Learning | /slop_intercept_n_predict.py | 759 | 3.78125 | 4 |
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
xs = np.array([1,2,3,4,5], dtype=np.float64)
ys = np.array([5,4,6,5,6], dtype=np.float64)
def best_fit_slope_and_intercept(xs,ys):
m = (((mean(xs)*mean(ys)) - mean(xs*ys)) /
((... |
5a40f176f18234f361b4b362ed05148e79d964c8 | aomline1/python_algorithm | /sort.py | 1,941 | 3.890625 | 4 | #插入排序
lista=[1,40,12,25,78,8,9,18]
def insert_sort(list):
for i in range(1,len(list)):
key=list[i]
j=i-1
while( j>0 and list[j]>key):
list[j+1]=list[j]
j-=1
list[j+1]=key
return list
#归并排序
def merge_sort(list):
if len(list)<=1:
r... |
9165d23f16e7ba35acf8b8f08ed5f28ea74f12da | nadiabey/rosalind | /dnastructures.py | 323 | 3.703125 | 4 | nucleotides = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}
def reverse(st):
temp = st[::-1]
ret = ""
for x in temp:
if x in nucleotides.keys():
ret += nucleotides[x]
print(ret)
return ret
if __name__ == '__main__':
f = open('rosalind_revc.txt', 'r').readlines()[0]
reverse... |
17c26d98f7b010a6dd18fba21d6f7dc6a113df50 | hyunkyeng/TIL | /algorithm/day12/피자굽기.py | 802 | 3.609375 | 4 | def pizza():
global cheeze
pan = []
for i in range(N):
pan.append(cheeze.pop(0))
return bake(pan)
def bake(pan):
while True:
if len(pan) == 1:
return pan[0][0]
pan[0][1] = pan[0][1] // 2
if pan[0][1] != 0:
pan.append(pan.pop(0))
elif ... |
3198cbddd9a4ed9ab9aa5c19b54b3d8824415b6f | ouzarf/tuto-py | /classY.py | 442 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 4 08:59:44 2018
@author: ouzarf
"""
class Y:
def __init__(self, v0):
self.v0 = v0
self.g = 9.81
def value(self, t):
return self.v0*t - 0.5*self.g*t**2
def formula(self):
return ("v0*t - 0.5*g*t**2; v0=%g" % s... |
4569c713cbb38259afd412666bbe92c6af35547a | anteater333/Anteater_lab | /Algo/5086/__init__.py | 323 | 3.546875 | 4 | outputs = []
done = False
while not done:
a, b = map(int, input().split())
if a == 0 and b == 0:
done = True
elif a % b == 0:
outputs.append("multiple")
elif b % a == 0:
outputs.append("factor")
else:
outputs.append("neither")
for output in outputs:
print(outp... |
e38b6169034ffa41f946851485367923aba2a652 | yuyan1991/Python-ProjectEuler | /PE0001.py | 116 | 3.984375 | 4 | # -*- coding:utf-8 -*-
ans = 0;
for x in range(1000):
if x%3==0 or x%5==0:
ans += x
print("ans=", ans)
|
3723ca900a2c07388f8e1ea7ea961c74c83be178 | prince-singh98/python-codes | /Loops/GuessingGame2.py | 550 | 3.90625 | 4 | num = 7
list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for trial in range(3):
ans = int(input("enter a num : "))
if ans in list:
if trial == 0 or trial == 1:
if ans == num:
print("success")
break
else:
print("try again")
elif trial ... |
589c19c0041b1a176e8b3a896b6eb17d9dee9ccb | prince-singh98/python-codes | /Relation/WarshallAlgorithm.py | 406 | 3.6875 | 4 | import numpy as np
M = np.array([[1, 0, 1], [0, 1, 0], [1, 1, 0]])
x = len(M)
def warshall(M):
assert(len(row) == len(M) for row in M)
n = len(M)
for k in range(n):
for i in range(n):
for j in range(n):
M[i][j] = M[i][j] or (M[i][k] and M[k][j])
return M
print("T... |
90bda58a280724875f5ba10d8171e81e093338ac | prince-singh98/python-codes | /ConditionalStatements/DigitAlphabateOrSpecialCharecter.py | 229 | 4.28125 | 4 | char = input("enter a alphabet")
if((char>='a' and char<='z') or (char>='A' and char<='Z')):
print(char,"is alphabet")
elif(char>='0' and char<='9'):
print(char, "is digit")
else:
print(char, "is special character")
|
eb97ccd4bed66773ffa8de7a12b6ec48dc7feeb3 | prince-singh98/python-codes | /Loops/Fibonacci.py | 219 | 4.09375 | 4 |
# fibonacci series wrt term
term = int(input("enter up to which term you want: "))
t1 = 0
t2 = 1
print(t1)
print(t2)
for x in range(2,term,1):
nextTerm = t1 + t2
print(nextTerm)
t1 = t2
t2 = nextTerm
|
4c19578d82cdd55affaef69cd74f214a1664b1ff | prince-singh98/python-codes | /Relation/RelationList.py | 1,049 | 4.1875 | 4 | A = {"A", "B", "C"}
def is_symmetric(relation):
for a, b in relation:
if (a,b) in relation and (b,a) in relation and a != b:
return "Symmetric"
return "Asymmetric"
print(is_symmetric([("A","A"), ("A","C"), ("C","A"), ("C","C")])) # True
print(is_symmetric([("A","A"), ("A","C"), ("A","B"),... |
10ed809445886786b67ae5806fcb58afcf3382f8 | prince-singh98/python-codes | /Relation/RelationAssignment.py | 2,056 | 3.734375 | 4 | A = {1, 2, 3}
R = {(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)}
def is_reflex_notReflex_Irreflex(R):
count = 0
for a, b in R:
if (a, b) and a == b:
count += 1
if count == 0:
# Ir-reflexive relation
return count
if count == len(A):
... |
94cdc04e927c6085167dbd774cc0660e641fb1bf | prince-singh98/python-codes | /ClassAndObjects/Calculator.py | 491 | 3.71875 | 4 |
class Calculator:
def userInput(self,no1,no2):
self.no1 = no1
self.no2 = no2
def add(self):
return self.no1+self.no2
def sub(self):
return self.no1-self.no2
def mul(self):
return self.no1*self.no2
def div(self):
return self.no1//self.no2
cal =... |
b9cfdb68bb172692e0ac36a882bd10be58e9dc72 | prince-singh98/python-codes | /ConditionalStatements/Average.py | 281 | 3.96875 | 4 | # average of 5 nos
a = int(input("enter first number"))
b = int(input("enter second number"))
c = int(input("enter third number"))
d = int(input("enter fourth number"))
e = int(input("enter fifth number"))
sum = a + b + c + d + e
result = sum / 5
print("average is : ", result)
|
cfd82a0d2e541e6e0058a6fe3206a21bbc2a457a | MustansirMR/Python-Projects | /number_guessing/main.py | 2,334 | 3.984375 | 4 | import random
class NumberGuessingGame:
def __init__(self):
self.score = 10
def guess_number(self):
self.num_to_guess = random.randint(2, 99)
print(self.num_to_guess)
print(f'I have a number in mind between 2 and 100. Can you guess it in {self.score} turns?')
while Tru... |
68e536bf4e5f3b3a7f8a853223e83f6f03511a98 | Chrisgo-75/intro_python | /conditionals/switch_or_case.py | 696 | 4.15625 | 4 | #!/usr/bin/env python3
# Index
# Python does not have a "switch" or "case" control structure which
# allows you to select from multiple choices of a single variable.
# But there are strategies that can simulate it.
#
# 1.
def main():
# 1.
choices = dict(
one = 'first',
two = 'second',
... |
85145d7b919824030bb2ce9a1f2132cfadcac9df | Chrisgo-75/intro_python | /general_syntax/strings.py | 1,433 | 4.9375 | 5 | #!/usr/bin/env python3
# Index
# 1. Strings can be created with single or double quotes.
# 2. Can introduce new line into a string.
# 3. Display escape characters (literally). Use "r" per example below.
# - r == "raw string" which is primarily used in regular expressions.
# 4. Format or replace characte... |
70a6549f5d354ecf63fc1cd8899c9c9a67cb7799 | thiagoeh/exercism | /python/largest-series-product/largest_series_product.py | 540 | 3.890625 | 4 | def serie_product(serie):
product = 1
for char in serie:
product *= int(char)
return product
def largest_product(series, size):
if size < 0:
raise ValueError('size must be a non-negative integer')
# Generate all combinations based on the size
combinations = (series[i:size+i] f... |
55d5bb10659365468580c9f842ee5a06ee6b5c27 | thiagoeh/exercism | /python/run-length-encoding/run_length_encoding.py | 1,020 | 3.8125 | 4 |
def decode_char(c, multiplier):
if multiplier == '':
multiplier = 1
return c * int(multiplier)
def decode(string):
multiplier = ''
decoded_str = ''
for c in string:
if c.isdigit():
multiplier = multiplier + c
else:
decoded_str = decoded_str + decod... |
d18d24ce0234c050bf14090cd8f04078c1a788ac | thiagoeh/exercism | /python/isbn-verifier/isbn_verifier.py | 1,119 | 3.734375 | 4 | def verify(isbn):
# Initialize sum
isbn_sum = 0
# Removing dashes
isbn_stripped = isbn.replace('-','')
# Test if we have the right length
if len(isbn_stripped) != 10:
return False
# X at the end is equivalent to 10 at the position
if(isbn_stripped[-1] == 'X'):
# R... |
ea0ba9d5b27e60510c4c8787b999b33048b15c57 | joaovitordmoraes/curso_CeV_python3 | /mundo 01/exercicio27.py | 192 | 3.921875 | 4 | nomecompleto = str(input('Digite seu nome completo: ')).strip()
nome = nomecompleto.split()
print('Seu primeiro nome é: {}'.format(nome[0]))
print('Seu último nome é: {}'.format(nome[-1]))
|
408e448d3c3d62263f1ac47ec626a5cfefd24b25 | joaovitordmoraes/curso_CeV_python3 | /mundo 01/exercicio28.py | 340 | 3.8125 | 4 | from random import randint
from time import sleep
computador = randint(0, 5) # SORTEIA UM NÚMERO ENTRE 0 E 5
print('Escolhendo um número.......')
voce = int(input('Tente adivinhar em que número o computador pensou: '))
print('Processando...')
sleep(2)
if voce == computador:
print('Você acertou!')
else:
print('V... |
b223daabfdef0d456262ed54430a85c199eb2bdc | joaovitordmoraes/curso_CeV_python3 | /mundo 02/exercicio44.py | 1,277 | 3.703125 | 4 | preco = float(input('Qual o preço do produto? R$'))
forma = str(input('Qual a forma de pagamento (à vista ou parcelado)? ')).strip()
red = '\033[31m'
fecha = '\033[m'
if forma == 'à vista' or forma == 'a vista':
print('À vista selecionado.')
avista = str(input('Será pago em dinheiro, cheque ou cartão? ')).str... |
1abeac658c51abed58627a94bcfa750fbdafeb83 | joaovitordmoraes/curso_CeV_python3 | /mundo 01/exercicio09.py | 124 | 3.796875 | 4 | tabuada = int(input('Digite a tabuada: '))
for x in range(1, 11):
print('{} x {} = {}'.format(tabuada, x, tabuada * x))
|
695540ac11869112344c218342df05c686e0cf83 | joaovitordmoraes/curso_CeV_python3 | /mundo 01/exercicio10.py | 122 | 3.796875 | 4 | valor = float(input('Digite o valor: '))
converter = valor / 3.27
print('Você possui {:.2f} dólares'.format(converter))
|
5f97f81c6f4a6b6f601859606f88709d09d404d7 | joaovitordmoraes/curso_CeV_python3 | /mundo 02/exercicio36.py | 579 | 3.90625 | 4 | '''
EMPRESTIMO BANCÁRIO PARA A COMPRA DE UMA CASA
'''
valor = float(input('Qual o valor da casa? R$'))
salario = float(input('Qual o valor do seu salário? R$'))
anos = float(input('Em quantos anos pretende pagar? '))
prestacao = (valor / anos) / 12
parcelas = anos * 12
abre = '\033[31m'
fecha = '\033[m'
if pres... |
bca8a5ec4316bb544908cdf93411b1dfc1c10a1f | xpenalosa/Text-To-Image-Encryption | /src/algorithms/streams/stream_seed.py | 1,929 | 3.5625 | 4 | from src.algorithms.streams.base_stream import BaseStreamAlgorithm
from typing import Generator, Optional
import random
class StreamSeedAlgorithm(BaseStreamAlgorithm):
"""Implementation of BaseStreamAlgorithm that streams the algorithm list.
The class provides the option to apply an XOR operation to the inpu... |
1959626da5a5f9d5f4cb9853b54ac2d9d30f16f0 | xpenalosa/Text-To-Image-Encryption | /src/algorithms/bit_cycle.py | 4,668 | 3.90625 | 4 | from src.algorithms.base import BaseAlgorithm
from src.utilities import bytes_conversions, algorithm_list_parser
class BitCycleAlgorithm(BaseAlgorithm):
"""Implementation of BaseAlgorithm that encodes through left-cycling bits.
The class provides the option to cycle the bits forming the text string an
ar... |
3e7afa5abee0267909f56bae2ade9759b4dde67a | Salmon420/01_Temperature | /08_valid_filename.py | 1,031 | 4.0625 | 4 | #checks in something is valid
import re
# Data to be outputted
data = ['first','second','third','fourth','fifth','sixth','seventh']
has_error = "yes"
while has_error == "yes":
print()
filename = input("Enter a filename: ")
has_error = "no"
problem = ""
valid_char = "[A-Za-z0-9_]"
for letter ... |
b36448a0e41f3ac2f94fb807d9beb21f6825674e | Ren-Jingsen/day04 | /sshop.py | 2,664 | 3.59375 | 4 | '''
任务:
优化购物小条
10机械革命优惠券,0.5
20张卫龙辣条优惠券 0.3
15张HUA WEI WATCH 0.8
随机抽取一张优惠券。
商城:
1.准备一些商品
2.有空的购物车
3.钱包
4.结算
流程:
看你输入的产品存不存在,
若存在
若钱够了:
将商品添加到购物车
钱包余额减去商品的钱
... |
b71e808a3cad44634d68acc663c543289b3feb74 | arvinjason/py4e | /Dict_Exercise1_Aquino.py | 232 | 3.546875 | 4 | file = input('Enter file name: ')
fh = open(file)
date = dict()
for line in fh:
if line.startswith("From "):
lst = line.split()
if lst[2] not in date:
date[lst[2]] = 1
else:
date[lst[2]] = date[lst[2]] + 1
print(date)
|
cde54473101afb081a05589e10754aafd4be65d6 | arvinjason/py4e | /Exercise3-Aquino.py | 282 | 3.921875 | 4 | score = input('Enter score: ')
try:
s = float(score)
except:
s = -1
if s>0 and s<0.6:
print('F')
elif s >= 0.6 and s < 0.7:
print('D')
elif s >= 0.7 and s < 0.8:
print('C')
elif s >= 0.8 and s < 0.9:
print('B')
elif s >= 0.9 and s < 1.0:
print('A')
else:
print('Bad score') |
e1fa1ee994a79d85ce82e5578c9e03623ceeb4a2 | DaishanHuang/python | /youtube/Tutorial-21_Function-and-return/main.py | 407 | 4 | 4 | # 1
def allowed_dating_age(my_age) :
girls_age = my_age / 2 + 7
return girls_age
# 1.1 example
mincongs_limit = allowed_dating_age()
print("i can date firls", mincongs_limit, "or older")
# 2
def get_gender(sex='unknown') :
if sex is 'm' :
sex = "Male"
elif sex is 'f' :
sex = "Female"
print(sex)
# 2.... |
b9fb8ee35b3cf5d73c30ca9874ca0daf20d5e3fc | DaishanHuang/python | /youtube/Tutorial-09_Sequences-and-Lists/main.py | 194 | 3.6875 | 4 | coloc = ['mincong','pape','charline']
print(coloc[0]) # mincong
print(coloc[1]) # pape
print(coloc[2]) # charline
# Pay attention !
print(coloc[-1]) # charline
coloc[0][2] # 'mincong'[2] # 'n'
|
a70b235ca5ecb8b7392d680f008b004d8da6cbcf | yui330/- | /tiktoktest3.py | 1,160 | 3.546875 | 4 | import re
class money():
def inputdata(self):
N = input()
N = int(N)
if N < 1 or N > 1000:
print("N is error")
return
line = input()
line = re.split(r'\s', line)
line = [int(e) for e in line]
if len(line) != N:
... |
096ad52ee4f95913932548d78ce15d314e9a0268 | thenerdygeek/Python-Help | /help.py | 2,484 | 3.75 | 4 | string='string'
integer=10
floating=10.2
list1=[]
while True:
x=int(input("Help For:-\n\t1)Integer\n\t2)Float\n\t3)String\nEnter your choice: "))
count=1
z=(input("Would you like to 'print' or save on a 'notepad'.:"))
if z=='print':
if(x==1):
list1=dir(integer)
for i in l... |
04a944d6c356c78d0ff31c8f3406ac40f6921bd5 | datarocksAmy/APL_Python | /ICE/ICE04/ICE04 Wikipage.py | 1,929 | 3.59375 | 4 | # ------------------------------------------------------------------------------------------------------------
# * Python Programming for Data Scientists and Engineers
# * ICE #4 Parse wikipage and extract the headers of the page.
# * BeautifulSoup + Requests Library
# * #11 Chia-Hui Amy Lin
# ---------------------... |
7a16498f5039f500dbb9b916d5f6a87ba3215c4b | datarocksAmy/APL_Python | /ICE/ICE02/ICE2.py | 2,515 | 4.125 | 4 | '''
* Python Programming for Data Scientists and Engineers
* ICE #2
* Q1 : Frequencies of characters in the string.
* Q2 : Max word length in the string.
* Q3 : Count numbers of digits and characters in the string.
* #11 Chia-Hui Amy Lin
'''
# Prompt user for a sentence
user_input_sentence = input("Please ... |
9094b07c5ef5da96a89870a898db9b9c010dbc45 | datarocksAmy/APL_Python | /Lab Assignment/Lab04/Lab04_b_MashDictionaries.py | 1,293 | 4.125 | 4 | # ------------------------------------------------------------
# * Python Programming for Data Scientists and Engineers
# * LAB #4-b Mash Dictionaries
# * #11 Chia-Hui Amy Lin
# ------------------------------------------------------------
# Dictionary
from statistics import mean
# Function
def mash(input_dict):
... |
5db43d9103f910dfeb21e7196142c38fc112af38 | datarocksAmy/APL_Python | /ICE/ICE03/ICE3-2 New List.py | 1,845 | 4.1875 | 4 | '''
* Python Programming for Data Scientists and Engineers
* ICE #3-2 Make new list
* Take in a list of numbers.
* Make a new list for only the first and last elements.
* #11 Chia-Hui Amy Lin
'''
# Function for prompting user for numbers, append and return the list
def user_enter_num(count_prompt, user_num_... |
008311dfd41940a63087d41c7579f3b72eb6743b | datarocksAmy/APL_Python | /ICE/ICE06/ICE06 - Linear Regression.py | 1,424 | 3.890625 | 4 | # ------------------------------------------------------------------------------------------------------------
# * Python Programming for Data Scientists and Engineers
# * ICE #6 Linear Regression with numpy + matplotlib
# * #11 Chia-Hui Amy Lin
# ---------------------------------------------------------------------... |
1e0a31556ab37f2c1c6ac3799c06899a0531aa87 | mmax5/project-euler | /Problem 32.py | 1,437 | 3.984375 | 4 | # -*- coding: iso-8859-15 -*-
"""
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example,
the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 186 = 7254, containing multiplicand, multiplier, and product is... |
b58b88e52af5404e379189e3744b42ee535838fd | mmax5/project-euler | /Problem52.py | 586 | 3.734375 | 4 | __author__ = 'mikemax'
"""It can be seen that the number, 125874, and its double, 251748, contain
exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain
the same digits."""
def test_number(x):
for i in [2, 3, 4, 5, 6]:
for dig ... |
1fa6d1b0e7de65b9f52999887cfb1a4827d615a1 | mmax5/project-euler | /Problem 28.py | 466 | 4 | 4 | '''
Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals in a... |
0016c5ca8a1ef3d15ac7e3351e9434464aeec6f7 | mmax5/project-euler | /Problem 24.py | 540 | 3.859375 | 4 | """
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3
and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The
lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
... |
2474eb0b564ed43645ec3e5914bcad6ff2496453 | dunaevai135/algos_ITMO_2019 | /oe/5w/priorityqueue.py | 2,330 | 3.953125 | 4 | from edx_io import edx_io
def heappush(heap, item):
heap.append(item)
siftdown(heap, 0, len(heap)-1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = h... |
b35fdead2749686c0f517ec5891726b95dd2dd5d | xuezhaoit/learn_python | /python_5_AdvancedFun.py | 1,310 | 3.640625 | 4 | # # -*- coding: utf-8 -*-
# import sys
# import io
# sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')
'''
高阶函数:map/reduce、filter、sorted
返回函数
匿名函数
装饰器
偏函数
'''
# ---------高阶函数-------------
# -----------map--------------
# def fun1(args):
# return args * args
# r = map(fun1, range(... |
d266471c8be63888f5e60dad137784395dafb9b4 | ghyhoiu/learn-python | /6.Functional programming/05.py | 215 | 3.75 | 4 | # 对于一个列表,偶数组成新的列表
# 定义过滤函数
# 过滤函数要求有输入,有布尔值
def isEven(a):
return a % 2 == 0
l = [1,23,2,45,3,4,5]
l1=filter(isEven,l)
for i in l1:
print(i) |
d53c4e77b2b0d89e654e491674045eade6a694cf | ghyhoiu/learn-python | /6.Functional programming/01.py | 322 | 3.828125 | 4 | # lambda表达式
# 以lambda开头
# 紧跟参数(如果有的话)
# 参数后面用逗号和表达式分开
# 只是一个表达式,没有return
# 计算一个数的123倍(单个参数)
stm = lambda x:x * 123
print(stm(12))
# 计算三个数字的加法(多个参数)
stm2 = lambda a,b,c: a + b + c
print (stm2(12,3,5)) |
a6a266b9b8e8b8663221534179f7caa18c62c3e9 | ghyhoiu/learn-python | /3.Exception handling/02.py | 1,011 | 3.953125 | 4 | # 简单异常案例
# 给出提示
try:
num = int(input("请输入你要输入的数字(整数):"))
rst = 100/num
print("计算结果是{0}".format(rst))
# 捕获一个异常,把异常实例化,出错信息会在实例里
# 注意以下写法:
# 以下语句是捕获 ZeroDivisionError异常并并实例化
# 如果出现了多种错误,要把越具体的情况,越往前放
except ZeroDivisionError as e:
print("你为什么要输入{0},你还能干点啥???????".format(num))
print(e)
exit()
excep... |
f28c8b94e19ffab49c2b76712243df6d2697c759 | ghyhoiu/learn-python | /3.Exception handling/01.py | 266 | 3.6875 | 4 | # 简单异常案例
try:
num = int(input("请输入你要输入的数字(整数):"))
rst = 100/num
print("计算结果是{0}".format(rst))
except:
print("你为什么要输入{0},你还能干点啥".format(num))
# exit是退出程序
exit() |
5fdbe6879dbd660e9e729eee18913d5f0d3e00b6 | ghyhoiu/learn-python | /2.oop/07.py | 468 | 3.78125 | 4 | # __call__举例
class A():
def __init__(self, name=0):
print("已经被调用")
def __call__(self):
print("再一次被调用")
def __str__(self):
return"小明是个好学生"
# 这时将对象变为字符串使用
a = A()
a()
print(a)
class B():
name = "Noname"
age = 18
def __getattr__(self,item):
print("没有找到哦")
b = ... |
edc6d34d72440134779c7a6cd3ceaecd42c903b9 | RevathiJambunathan/amrex | /Tools/Postprocessing/python/column_depth.py | 2,843 | 3.703125 | 4 | #!/usr/bin/env python
import sys
import numpy
def countValidLines(iterableObject):
""" Here we count the number of lines in the iteratableObject that don't
start with a comment (#) character. The iterableObject can be a file,
in which case we rewind the file to the beginning."""
import types
numG... |
41936305a845745c6d57198b17a967ffb7e85e2b | motakuw/x-o-game | /FINALEEEE - Copy.py | 2,716 | 3.9375 | 4 | def showboard():
print(board[0],'|',board[1],'|',board[2])
print(board[3],'|',board[4],'|',board[5])
print(board[6],'|',board[7],'|',board[8])
board=[0,1,2,3,4,5,6,7,8]
print("LET'S START!!")
a=input(str("Player 1, what's your name?? "))
b=input(str("Player 2, what's your name?? "))
print(... |
5c6ce8379d2c4dc702b20cb252db1d584af6f997 | 215836017/PythonDemos | /DemoReptile/01_urllib/001_urllib_urlopen.py | 1,821 | 3.515625 | 4 | import urllib.request as request
import urllib.parse as parse
'''
最基础的HTTP库有:urllib, httplib2, requests, treq等
'''
response = request.urlopen('https://www.python.org/')
print('test 111 : ', response)
# print('test 222 : ', response.read().decode('utf-8')) # 结果跟网页源代码是一样的
print('test 333 : ', type(response))
# test... |
d3d19fd1c3c69a151114b1e73aaab7df663665b9 | ronicst/advpyDec2020 | /my_modules/my_reduce.py | 305 | 3.890625 | 4 | from functools import reduce # reduce is part of the functional programmnig tools
# using reducers
def add_r(x, y):
return x+y
if __name__ == '__main__':
print(reduce(add_r, range(1, 99, 3))) # start at 1, stop at 98, every third member
print( reduce( lambda x, y: x * y, range(1,6) ) )
|
92881d6a747c8f9b0e3096a6c88d8dcabb0eb4e5 | ronicst/advpyDec2020 | /my_performance/thread_semaphore.py | 882 | 3.796875 | 4 | from threading import Thread, Event, Lock, BoundedSemaphore
import time
class DemoSem:
def __call__(self, name):
self.name = name
global sem
sem.acquire()
time.sleep(2)
sem.release()
print(f'{self.name} done')
if __name__ == "__main__":
# we need a global semaph... |
0e57e58c829c23f85e3a4a325fa73f0bd0ec9ab0 | ronicst/advpyDec2020 | /my_performance/threaded_class.py | 1,310 | 3.96875 | 4 | import sys
import time
import random
from threading import Thread
# Each thread has it's own stack
# each thread SHARES the Heap, any Statics and any resources e.g. files
# the Python kernel (single process) schedules the threads
# declare a runnable class
class MyRunnable(Thread): # if we extend the Thread class, we... |
0eb67f97c69a15f4a28b57bc32aef315ca01f6ed | ronicst/advpyDec2020 | /my_performance/thread_callback.py | 1,052 | 3.828125 | 4 | from threading import Thread
import time
import sys
import random
# declare a callable class
class MyCallable: # nb this is not a runnable, so we treat it like functional
def __call__(self, name):
for i in range(1,50):
sys.stdout.write(name) # same as print()
time.sleep( random.rand... |
a35bdb250aa59a9b8c3ae66a582c34d313382a31 | ronicst/advpyDec2020 | /my_static/my_point_test.py | 904 | 3.765625 | 4 | import unittest
from my_point import Point
class testPoint(unittest.TestCase): # we need the TestCase class from unittest
# set up the tests (this is run BEFORE each test)
def setUp(self):
self.point = Point(3, 5)
self.pointDefault = Point() # default to 0, 0
# declare our suite of tests
... |
017558f532bb7f977b12fd5687f7587f4e4bbaaf | ronicst/advpyDec2020 | /using_db/my_insertmany_db.py | 692 | 3.8125 | 4 | import sqlite3
# we need a connection to the db
conn = sqlite3.connect('books_db') # creates if not exist
# now we can try to insert into the db
cur = conn.cursor()
# declare some data members
b1 = [2, 'Climate', 'Greta', 'warm@chilly.se', 'bit of a hero']
b2 = [3, 'GGG', 'Timnit', 'ex@google.com', 'general good bod'... |
f68c12017bd5d91b26671303872782ace9f70197 | drafski89/interview-examples | /1_General/pairs_add_ten.py | 501 | 3.71875 | 4 | # Find pairs in an integer array whose sum is equal to 10 (bonus: do it in linear time)
input_values = [5,2,3,5,6,2,8]
if __name__ == "__main__":
for first_value in range(0,len(input_values),1):
for second_value in range(first_value,len(input_values),1):
if input_values[first_value] + input_va... |
29464287ca699df010e2a76086229b48eb7caa6b | drafski89/interview-examples | /1_General/rotated_array.py | 765 | 3.953125 | 4 | # Given 2 integer arrays, determine of the 2nd array is a rotated version of the 1st array.
# Ex. Original Array A={1,2,3,5,6,7,8} Rotated Array B={5,6,7,8,1,2,3}
a = [1,2,3,4,5,6,7,8]
b = [5,6,7,8,1,2,3,4]
def check_rotated_arrays(a, b):
# check that the lengths are the same
if len(a) != len(b):
ret... |
dbc3dfae249a74877e71007e05cd933c92d13459 | lelong03/python_algorithm | /array/median_sorted_arrays.py | 2,041 | 4.125 | 4 | # Find median of two sorted arrays of same size
# Objective: Given two sorted arrays of size n.
# Write an algorithm to find the median of combined array (merger of both the given arrays, size = 2n).
# What is Median?
# If n is odd then Median (M) = value of ((n + 1)/2)th item term.
# If n is even then Median (M) = ... |
b2a16d0cf8c6db546496e8a3f16da54a1af67ece | lelong03/python_algorithm | /array/quick_sort.py | 1,785 | 3.796875 | 4 | def quicksort(alist):
quicksort_helper(alist, 0, len(alist)-1)
def quicksort_helper(alist, first, last):
if last < first:
return
pivot = alist[first]
split_point = partion(alist, first, last, pivot)
quicksort_helper(alist, first, split_point-1)
quicksort_helper(alist, split_point+1, l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.