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
cafa19ec507d2c4336453156e48745d0741bfa53
PacktPublishing/The-Complete-Python-Course
/2_intro_to_python/lectures/11_comprehensions_with_conditionals/code.py
691
3.734375
4
ages = [22, 35, 27, 21, 20] odds = [n for n in ages if n % 2 == 1] # -- with strings -- friends = ["Rolf", "ruth", "charlie", "Jen"] guests = ["jose", "Bob", "Rolf", "Charlie", "michael"] friends_lower = [f.lower() for f in friends] present_friends = [ name.capitalize() for name in guests if name.lower() in fri...
f8fad97a0ca47a3f5e609db18f89a04eed5eaa96
RubenH101/Calculator
/CalculatorProject.py
6,626
3.65625
4
from tkinter import* import math cal= Tk() cal.geometry('442x610') cal.configure(bg='mediumblue') cal.title("Calculator") callabel = Label(cal,text="Calculator",font=('arial',100,'bold')) def clickbut(numbers): current = caltext.get() caltext.delete(0, END) caltext.insert(0, str(current) + str(nu...
90aa93be4b574939d568c13f67129c50c4f34d19
ItzMeRonan/PythonBasics
/TextBasedGame.py
423
4.125
4
#--- My Text-Based Adventure Game --- print("Welcome to my text-based adventure game") playerName = input("Please enter your name : ") print("Hello " + playerName) print("Pick any of the following characters: ", "1. Tony ", "2. Thor ", "3. Hulk", sep='\n') characterList = ["Tony", "Thor", "Hulk"] characterNumber = ...
045eb4fa6050cf6db361622253215869793a030d
wsr0727/pythonLessionTest
/strtesr.py
132
3.609375
4
def rvs(s): if s == "": return s else: return rvs(s[1:])+s[0] def main(): print(rvs(s=input())) main()
4c60fb574cb306ecb5565c04c570570a945dd718
Semihozel/Workspace
/Kullanıcı Girişi.py
565
3.84375
4
print("********\n KULLANICI GİRİŞİ\n********") kayıtlıad = "Semih" kayıtlıparola = "12345" kullanıcı_adı = input("Kullanıcı adını giriniz ") parola = input("Parolayı giriniz ") if (kullanıcı_adı == kayıtlıad and kayıtlıparola != parola): print("Parola yanlış") elif (kullanıcı_adı != kayıtlıad and...
46a0b3b6c4d950a602b0085788309b4c7cfe775c
Semihozel/Workspace
/Mükemmel Sayı Bulma.py
364
3.875
4
print("MÜKEMMEL SAYI BULMA") a = int(input("sayı : ")) toplam = 0 for i in range(1, a): if (a % i == 0): print("{} nın bölenleri".format(i)) toplam += i print("bölenlerin toplamı", toplam) if (toplam == a): print("{} mükemmel bir sayıdır".format(a)) else: print...
44743a6d92fd09751136f4ae34699e9947d8a17d
xuyanbo03/study
/python/test/sushu.py
341
3.84375
4
def _odd_iter(): n=1 while True: n = n + 2 yield n def _not_divisible(n): return lambda x:x%n>0 def primes(): yield 2 it = _odd_iter() while True: n=next(it) yield n it = filter(_not_divisible(n),it) for n in primes(): if n<1000: print(n) ...
6a62ad6dadd132628c486c46bccee578d8fa6d88
jameygronewald/python_challenges
/list_overlap.py
397
3.515625
4
import random # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] a = [] b = [] length_of_a = random.randint(20, 50) length_of_b = random.randint(20, 50) for x in range (length_of_a): a.append(random.randint(1, 100)) for x in range (length_of_b): b.append(random.r...
c88bc8dba47119b9fb09fb36ef2782ee8fb04c90
jameygronewald/python_challenges
/guess_word_by_letter.py
731
4.03125
4
word = "EVAPORATE" list = ['_' for char in word] guessed = [] def init(): print() print(*list) while '_' in list: print('\nTry to guess the word!') user_guess = input('Enter a letter to guess: ').upper().strip() if len(user_guess) > 1: print('\nPlease enter only o...
88764af2f7ea16f7c927cf3c3ffaee41639ea625
jameygronewald/python_challenges
/reverse_word_order.py
193
4.34375
4
def reverse_word_order(): string = input(f"Type a message with multiple words and I will reverse the word order for you. ") print(" ".join(string.split()[::-1])) reverse_word_order()
f5a76219a79e832625c64dd0e16352ecc4f96ac9
SoeZeng/FishC
/P48_1.py
1,379
3.859375
4
# -*- coding: utf-8 -*- """ Created on Tue May 25 13:58:26 2021 @author: DELL """ class LeapYear: def __init__(self): self.year = 2021 def __iter__(self): return self def __next__(self): while not ((self.year % 4 == 0 and self.year % 100 != 0) or (self....
a3c5cddfc199013915eb4152ba615e90ced60586
SoeZeng/FishC
/P41_2.py
1,039
3.515625
4
# -*- coding: utf-8 -*- """ Created on Tue May 18 16:47:38 2021 @author: DELL """ class Nint(int): def __new__(cls,pref): if isinstance(pref,str): result = 0 for c in pref[:]: result += ord(c) pref = result return int._...
2feb9efd1c4596c1b6fedff272b3b91cefb24927
SoeZeng/FishC
/P42_2.py
1,626
3.796875
4
# -*- coding: utf-8 -*- """ Created on Wed May 19 12:14:07 2021 @author: DELL """ class Nstr(str): def __init__(self,s): self.asc = 0 for c in s: self.asc += ord(c) def __add__(self,other): return int(self.asc) + int(other.asc) de...
3c221d5ddb50cd037b771d2b33c1f809c550249d
SoeZeng/FishC
/P39_1.py
1,325
3.9375
4
# -*- coding: utf-8 -*- """ Created on Tue May 18 11:12:14 2021 @author: DELL """ class Stack: def __init__(self): self.stack = [] def isEmpty(self): print(True) if len(self.stack) == 0 else print(False) def push(self,data): self.stack.append(data) ...
91640393b2028db76feab7459f1bb2706d945403
Spencer-Ross/spencer_ross_proj2
/wsu-pub-crypt.py
6,638
3.765625
4
# imports and globals import sys, argparse, random from random import getrandbits from fastExp import fast_exp from Miller_Rabin import is_prime rands: int = 10 # number of checks for isPrime wordSize: int = 4 # number of bytes/word # Key Related Functions ----------------------------------------------------------...
34cf5dbfbf40c3d7f1a3965383ee549a21c74fb2
Zerobitss/Python-101-ejercicios-proyectos
/practica88.py
4,169
3.9375
4
def plato(): menu_principal = ['Pizzas','Pasta','Ensaladas'] menu_eleccion = [menu_pizzas(), menu_pasta(), menu_ensalada()] opcion_menu = int(input("1.-Pizzas\n2.-Pasta\n3.-Ensaladas\nQue deseas comer hoy: ")) if (opcion_menu <= len(menu_principal)): print(f"Tu eleccion fue: {menu_principal[opci...
5d9f81915ee5b355e49e86ed96da385f40c81280
Zerobitss/Python-101-ejercicios-proyectos
/practica47.py
782
4.1875
4
""" Escribir un programa que almacene el diccionario con los créditos de las asignaturas de un curso {'Matemáticas': 6, 'Física': 4, 'Química': 5} y después muestre por pantalla los créditos de cada asignatura en el formato <asignatura> tiene <créditos> créditos, donde <asignatura> es cada una de las asignaturas del cu...
31536f9c78af3c4974ffd1fe1239547faf27a07b
Zerobitss/Python-101-ejercicios-proyectos
/practica65.py
358
3.921875
4
""" 3: Con operadores logicos, determina si una cadena de texto ingresada por el usuario tiene una longitud mayor o igual a 3 y a su vez es menor a 10. (true o false) """ def run(): texto = str(input("Ingresa un texto: ")) if len(texto) >= 3 and len(texto) < 10: print(True) else: print(False...
f6c650389a5589fd1889af109d49878ea4f31f6e
Zerobitss/Python-101-ejercicios-proyectos
/practica97.py
987
3.859375
4
class Persona(): def __init__(self, apellidoPat, apellidoMat, nom): self.apellidoPaterno = apellidoPat self.apellidoMaterno = apellidoMat self.nombres = nom def mostrarNombre(self): txt = "{0}, {1}, {2}" return txt.format(self.apellidoPaterno, self.apellidoMaterno, self...
1c07f5f093217d0818bda345ebc9f1dec853394a
Zerobitss/Python-101-ejercicios-proyectos
/practica6.py
722
3.828125
4
""" Escribir un programa que almacene la cadena de caracteres contraseña en una variable, pregunte al usuario por la contraseña e imprima por pantalla si la contraseña introducida por el usuario coincide con la guardada en la variable sin tener en cuenta mayúsculas y minúsculas. """ def run(): login = str(input("In...
34aa36caf907e6334d2dcb3e7b1594fd736007f3
Zerobitss/Python-101-ejercicios-proyectos
/practica42.py
427
4.0625
4
""" Escribir un programa que almacene en una lista los siguientes precios, 50, 75, 46, 22, 80, 65, 8, y muestre por pantalla el menor y el mayor de los precios. """ def run(): precios = [50, 75, 46, 22, 80, 65, 8] precios.sort() minimo = min(precios) maximo = max(precios) print(f"El menor de los pre...
669612375d9e39154bbfc4273767fe19fe313dbc
Zerobitss/Python-101-ejercicios-proyectos
/practica62.py
256
3.8125
4
""" 5)Aqui hay un texto que esta alreves, es un alumno, que tiene una nota del examen.¿Como podemos darlo vuelta y verlo normalmente? texto = "zaid luar, 10" """ def run(): texto = "zaid luar, 10" print(texto[::-1]) if __name__ == "__main__": run()
c58beab76a386453584e334a14ca93b9979c8bd5
Zerobitss/Python-101-ejercicios-proyectos
/practica4.py
383
4.03125
4
""" Escribir un programa que pregunte al usuario su edad y muestre por pantalla si es mayor de edad o no. """ def run(): print("🤗Bienvenido al programa para saber si eres mayor o no 😁") edad = int(input("Ingresa tu edad: ")) if edad >= 18: print("Si eres mayor de edad") else: print("No...
975c2263afb1696d97671eba3731aa05349ee3f4
Zerobitss/Python-101-ejercicios-proyectos
/practica1.py
1,668
4.125
4
""" Una juguetería tiene mucho éxito en dos de sus productos: payaso y muñeca. Suele hacer venta por correo y la empresa de logística les cobra por peso de cada paquete así que deben calcular el peso de los payasos y muñecas que saldrán en cada paquete a demanda. Cada payaso pesa 112 g y la muñeca 75 g. Escribir un pro...
96cffff7188de858043be7752354bdf527b6042c
Zerobitss/Python-101-ejercicios-proyectos
/practica85.py
1,985
4.46875
4
""" Escribir una función que simule una calculadora científica que permita calcular el seno, coseno, tangente, exponencial y logaritmo neperiano. La función preguntará al usuario el valor y la función a aplicar, y mostrará por pantalla una tabla con los enteros de 1 al valor introducido y el resultado de aplicar la fun...
c61148bd558bcf40610b0bdaed53f3d2bb3876a3
Zerobitss/Python-101-ejercicios-proyectos
/practica67.py
702
3.875
4
""" (1)Escribir un programa que almacene la cadena de caracteres contraseña en una variable, pregunte al usuario por la contraseña hasta que introduzca la contraseña correcta. """ def run(): while True: password = str(input("Ingresa tu contraseña: ")) re_password = str(input("Repite tu contraseña: "...
645d14de2df189107ae1b0d6562e4e83e984d0ec
DiogoNeves/PyAlgo
/algos/stack.py
862
3.6875
4
# !/usr/bin/env python # -*- coding: utf-8 -*- from algos import CollectionException, Collection, UNLIMITED class StackException(CollectionException): pass class Stack(Collection): def __init__(self, capacity=-1): if capacity == 0 or capacity < UNLIMITED: raise StackException( ...
23c8d095e97226e3c7558de15a692abda0bd0e01
kunal-singh786/basic-python
/ascii value.py
219
4.15625
4
#Write a program to perform the Difference between two ASCII. x = 'c' print("The ASCII value of "+x+" is",ord(x)) y = 'a' print("The ASCII value of "+y+" is",ord(y)) z = abs(ord(x) - ord(y)) print("The value of z is",z)
3fe0e5c3fd08074abc2d7b60f5b799b5b0acb538
kunal-singh786/basic-python
/loop hackerrank.py
176
4.09375
4
'''Task Read an integer . For all non-negative integers , print . See the sample for details''' if __name__ == '__main__': n = int(input()) for i in range(n): print(i**2)
4afe44be49a57421c502423cc9f0226df2e07a8c
kunal-singh786/basic-python
/5a1.py
280
3.8125
4
mobile = ['nokia','samsung','vivo','oppo','redmi'] x = type(mobile) print(x) string = ' '.join(mobile) print(string) def check_vow(string,vowels): final = [each for each in string if each in vowels] print(len(final)) print(final) vowels = "AaEeIiOoUu" check_vow(string,vowels);
cd87777649d836dbd3f48b638f645f6060041ca1
kunal-singh786/basic-python
/bus ticket generate.py
1,036
3.9375
4
print(" Jotti Travelers") bus_no =int(input("Enter the bus number(Gurugram to Other= 35, Other to Gurugram= 36)=")) name = str(input("Name:-")) age = int(input("Age:-")) gender = str(input ("Gender:-")) source = str(input("Source:-")) des = str(input("Destination:-")) rate = int(input("Enter the d...
43aaeac595fb07f69b90c5e481e3197582b0f65e
rafaelacarnaval/uri-online-judge
/Revisão.py
434
4
4
print("Hello World!") first_name = "Rafaela" last_name = "Carnaval" age = 25 height = 1.60 print("Olá, %s %s. Eu tenho %d anos e %.2f de altura" %(first_name, last_name, age, height)) first_name = input("Nome:\n") last_name = input("Sobrenome:\n") age = int(input("Idade:\n")) height = float(input("Altura:\n")) pr...
8ca4c0008691ecaac718f1f2610c62816f75523c
rafaelacarnaval/uri-online-judge
/uri_1021.py
376
3.859375
4
n = float(input()) notas = [100,50,20,10,5,2] moedas = [1,0.50,0.25,0.10,0.05,0.01] print("NOTAS:") for nota in notas: quantidade = n / nota print("%d nota(s) de R$ %d.00" %(quantidade, nota)) n = n % nota print("MOEDAS:") for moeda in moedas: quantidade = n / moeda print("%d moeda(s) de R$ %....
40889d762e49b20ff541207f16649b5cadcebbcb
e998/CS550
/13dog_class.py
2,210
4.09375
4
# 10/25/2018 """ Properties - breed - size - color - name * - home - food/diet - owner - tricks - energy * - hunger * - thirst - happiness """ """ Methods - walk - eat * - sleep * - play fetch - roll over - bark - bite - follow owner - sit """ # name with capital letter and with singular class Seal: ### CONSTRUCT...
f34edf98143ba9e7eea0ec02bd93db3465943fe6
e998/CS550
/card.py
681
3.859375
4
# 11/1/2018 class Card: def __init__(self, suit, rank): self.suit = suit self.rank = rank def __str__(self): # create local variable rank, don't want to permanently change the number of the rank rank = self.rank suit = self.suit if rank == 1: rank = "Ace" elif rank == 11: rank = "Jack" elif...
9b18e28d9b8defa2507779a95d69d7d59e4c0576
e998/CS550
/w3montecarlowalk.py
3,006
4.40625
4
# 1/10/2019 # CS550 Class/HW Winter # Monte Carlo Walk & Dart Simulation # Answer: 22 blocks (Longest walk where you'll be within walking distance at least 50% of the time) """ Solution Explantion: In the Monte Carlo simulation, for different lengths between the values of 0 and 30, the user goes on random walks for ...
8173f27556c3d20308fed59059819a509afaf083
marianraven/estructuraPython
/ejercicio7.py
287
4.15625
4
#Escribir un programa que pregunte el nombre del usuario por consola y luego imprima #por pantalla la cadena “Hola <nombre_usuario>”. Donde <nombre_usuario> es el #nombre que el usuario introdujo. nombreIngresado= str(input('Ingrese su nombre:')) print('Hola......', nombreIngresado)
9452b77f4adca6f96525f9a2a3623e5a019111a6
marianraven/estructuraPython
/ejercicio17.py
518
3.984375
4
#Escribir un programa que pida un número natural n al usuario e imprima por pantalla #la suma de los números naturales de 1 hasta n. Por ejemplo para n = 5, la salida debe #ser: #1 + 2 + 3 + 4 + 5 = 15 #Nota: Hacerlo de dos formas, usando y sin usar la ecuación: #F ( n ) = ∑ i= #i= 1 #n ( n+1 ) #2 entrada= int(input('I...
e26dd47bed2da8fd37db2411b242636426f50d12
ShrutiBalla9/ShrutiBalla7
/fileoperation.py
595
3.859375
4
#writing in file with open("text.txt","w",encoding='utf-8')as f: f.write("hello") f.close() f = open("text.txt","r") print(f.read()) #reading file f = open('text.txt','r',encoding='utf-8') print(f.read()) #closing opened file f = open("text.txt","r",encoding='utf-8') print(f.read()) f.close...
d62fb1c8e99fc0208f21f782bb8b1ea04ff0899b
ShrutiBalla9/ShrutiBalla7
/operators.py
389
4.0625
4
# Arithmetic operator x=20 y=10 print("\n 20+10=",x+y) print("\n 20-10=",x-y) print("\n 20*10=",x*y) print("\n 20%10=",x%y) print("\n 20/10=",x/y) print("\n 20**10=",pow(x,y)) #comparison operators print("x>y",x>y) print("x<y",x<y) print("x==y",x==y) print("x!=y",x!=y) #logical operator print("x and ...
729fe090ac9756c25199f1f2ab6dd3e98a65ff51
jbascunan/Python
/1.Introduccion/16.metodos_estaticos.py
557
3.6875
4
class Circulo: # variable de clase pi = 3.1416 # METODO ESTATICO @staticmethod def pi2(): return 3.14 # CONSTRUCTOR def __init__(self, radio): self.radio = radio self.perimetro = 4 # METODO DE INSTACIA def suma(self): return "suma" circulo1 = Circ...
de2c66cc004eae8ba588f8e775fc8266e9867df5
jbascunan/Python
/1.Introduccion/2.diccionarios.py
966
4.3125
4
# las llaves puede ser string o enteros diccionario = { 'a': 1, 'b': 2, 'c': 3 } # diccionario de llave enteros diccionario1 = { 1: "nada", 2: "nada2" } print(diccionario1) # agregar clave/valor diccionario['d'] = 4 # modifica valor diccionario['e'] = 5 # si la llave existe se actualiza sino la c...
cf1b2e8a4454c28033a86f08ffda2544c4018078
jbascunan/Python
/1.Introduccion/18.herencia.py
730
3.609375
4
class Animal: # clase abuelo @property def terrestre(self): return "animal" class Felino(Animal): # clase padre hereda de Animal @property def garras_retractiles(self): return True def cazar(self): print("cazando") class Gato(Felino): # hereda de Felino def gato_c...
1026cedd32de74a4318e5fd7dea6e77a5a39ad8a
tbchamp/UWCSE403-Recipe-Reader
/web/cgi/allrecipes_scraper.py
8,155
3.53125
4
#!/usr/bin/python #print page header print "Content-type: text/html" print "" import cgi import cgitb; import htmllib import httplib import re import sys import unicodedata import urllib import urllib2 from urlparse import urlparse from BeautifulSoup import BeautifulSoup #function for unescaping string for printing...
6439616147683c7d01b8ce2814276118ae362c89
ulises1229/NURBS-Python_Examples
/ex_curve04.py
1,143
3.671875
4
# -*- coding: utf-8 -*- """ Examples for the NURBS-Python Package Released under MIT License Developed by Onur Rauf Bingol (c) 2017 """ from nurbs import Curve as ns from nurbs import utilities as utils from matplotlib import pyplot as plt # Create a NURBS curve instance curve = ns.Curve() # The full ci...
f1533c7e247c3dfae9a3b416cadc90e8e471eb5b
bobyaaa/Competitive-Programming
/CCC/CCC '05 S5 Pinball Ranking.py
1,484
3.703125
4
#Run in pypy2 or TLE ;-; #Basically what we're doing here is mergesorting the list, and then counting the inversions of the mergesort. #Solution by Andrew Xing import sys n = int(sys.stdin.readline()) alist = [] for x in range(n): alist.append(int(sys.stdin.readline())) swapCount = 0 def mergeSort(alist): glo...
b1b664af153b13d978314cb61c5e656901daf1be
bobyaaa/Competitive-Programming
/CCC/CCC '03 S1 - Snakes and Ladders.py
646
3.6875
4
win = False counter = 1 while win == False: roll = input() if roll == 0: break counter = counter + roll if counter == 9: counter = 34 elif counter == 40: counter = 64 elif counter == 54: counter = 19 elif counter == 67: counter = 86 elif counter == 90: counter = 48 elif ...
b766cd78c2fe2e777e563ebca005b1fa180e890d
bobyaaa/Competitive-Programming
/CCC/CCC '04 J3 Smile with Similes.py
283
3.84375
4
adj = input() noun = input() adjliszt = [] nounliszt = [] for x in range(adj): adjliszt.append(raw_input()) for x in range(noun): nounliszt.append(raw_input()) for x in range(len(adjliszt)): for y in range(len(nounliszt)): print adjliszt[x] + " as " + nounliszt[y]
3b1d0f4f464f06987564946eb720995f5f7e9b28
bobyaaa/Competitive-Programming
/Bruce/Bruno and Pumpkins.py
1,363
3.65625
4
#Solution by Andrew Xing import sys n = input() t = input() dp_but_not_really = [input() for x in range(n)] dp_but_not_really.sort() #We sort our dp. This is because we just want to find the optimal solutions. Say we have -4 -3 -2 1 8. Why would you try #to compute the distance (if you want three pumpkins) for -4, -3,...
61ee175839674d678f7ad5e54dbc68e9698d80fe
bobyaaa/Competitive-Programming
/Other/Rabbit Girls.py
297
3.71875
4
rabbit_girls = input() group = input() if group > rabbit_girls: print group - rabbit_girls elif group == rabbit_girls: print 0 else: remainder = rabbit_girls % group if remainder == 0: print 0 elif remainder > float(group/2): print group - remainder else: print remainder
87a6d5e514a8d472b5fe429ddf28190fb3e38547
EddieMichael1983/PDX_Code_Guild_Labs
/RPS.py
1,514
4.3125
4
import random rps = ['rock', 'paper', 'scissors'] #defining random values for the computer to choose from user_choice2 = 'y' #this sets the program up to run again later when the user is asked if they want to play again while user_choice2 == 'y': #while user_choice2 == y is TRUE the program keeps going user...
e1bd7675cbe0ca378fcc5799262bdb1796e53716
EddieMichael1983/PDX_Code_Guild_Labs
/functions.py
536
3.859375
4
#functions.py #illustrates the difference between print and return def noisy_add(num1, num2): print(f"ADDING {num1} AND {num2}!!! :D") return num1 + num2 #return leaves behind what it points at def bad_add(num1, num2): print(num1 + num2) #print just shows what it prints and leaves none behind ...
698c8d06b87bda39846c76dff4ddb1feb682cf4f
ManchuChris/MongoPython
/PrimePalindrome/PrimePalindrome.py
1,739
4.1875
4
# Find the smallest prime palindrome greater than or equal to N. # Recall that a number is prime if it's only divisors are 1 and itself, and it is greater than 1. # For example, 2,3,5,7,11 and 13 are primes. # Recall that a number is a palindrome if it reads the same from left to right as it does from right to left. # ...
56ed66d12f06498a53c9be533a829efdd00d2bd6
ManchuChris/MongoPython
/AddLinkedList/AddLinkedList.py
1,918
3.890625
4
# Given two numbers represented by two linked lists, write a function that returns the sum list. # The sum list is linked list representation of the addition of two input numbers. It is not allowed to modify the lists. # Also, not allowed to use explicit extra space (Hint: Use Recursion) class node: def __init__(s...
11f5d71093cf9d5c00d06f88875d9ec00ed0ee5c
aduqu3/calculadora_metodos
/PyQt5/funciones.py
6,974
3.5625
4
import sys from math import * import numpy as np from numpy import log as ln # ============================ REPLACE CHARACTERS ON STRING INI =================== # reemplazar simbolos en la cadena de caracteres para poderse utilizar en el metodo simpson 1/3 def string_replace(string): replacements = { ...
3f40aa3e28b189fabc48fad78347448ddb2ad706
l8g/graph
/Graph/Dfs/Path.py
1,198
3.546875
4
import sys sys.path.insert(0, "..") from Expression.Graph import Graph class Path(): def __init__(self, g : Graph, s, t): self._g = g self._s = s; self._t = t; self._visited = [False] * g.v() self._pre = [-1] * g.v() self._pre[s] = s ...
ebe3d0b8c5d85eb504e9c68c962c1fa8343eab3b
aartis83/Project-Math-Painting
/App3.py
2,137
4.1875
4
from canvas import Canvas from shapes import Rectangle, Square # Get canvas width and height from user canvas_width = int(input("Enter the canvas width: ")) canvas_height= int(input("Enter the canvas height: ")) # Make a dictionary of color codes and prompt for color colors = {"white": (255, 255, 255), "blac...
370e818c299774fd85ed8e467cacd8acfdff4b7d
anotherLostKitten/william_lu
/util/db_utils.py
498
3.625
4
import sqlite3 import urllib.request import json def getType(weather): '''uses weather info to get corresponding list of pokemon types''' print(weather) DB_FILE = "app.db" db = sqlite3.connect(DB_FILE) c = db.cursor() db.text_factory = str command = "SELECT data.type FROM data WHERE data.we...
35f51add924f454421a261899ee75e900fe1d1b7
rashed091/Algorithm-and-Data-structures
/DynamicProgramming/coin-change.py
305
3.890625
4
def change_count(S, n): m = len(S) table = [0 for _ in range(n+1)] table[0] = 1 for i in range(m): for j in range(S[i], n + 1): table[j] += table[j - S[i]] return table[n] if __name__ == "__main__": arr = [1, 2, 3] n = 5 print(change_count(arr, n))
876bc23bafaa9526d7cc54bf71cccaeb7992e57b
rashed091/Algorithm-and-Data-structures
/Queue/queue.py
431
3.796875
4
class Queue: def __init__(self): self._items = [] def is_empty(self): return self._items == [] def enqueue(self, item): self._items.insert(0, item) def dequeue(self): self._items.pop() def size(self): return len(self._items) if __name__ == "__main__"...
4c34a47b1b291d3d267cf0ebd9b18f0c3501d508
rashed091/Algorithm-and-Data-structures
/Queue/palindrome.py
285
3.734375
4
from collections import deque def is_palindrome(chars): char_deque = deque(chars) while len(char_deque) > 1: first = char_deque.popleft() last = char_deque.pop() if first != last: return False return True print(is_palindrome('radar'))
27d1c5e77ebc24edd8f50c96f7c1aba313eb3ae4
fraserjamieson/static_-dynamic_testing
/part_2_code/tests/card_game_tests.py
1,219
3.984375
4
import unittest from src.card import Card from src.card_game import CardGame class TestCardGame(unittest.TestCase): def setUp(self): self.cards= [] # define card1 and card2 objects based on the Card class and respective instance variables self.card_4 = Card("Spades", 4) self.cards.appen...
660655e0af55d67073a42fb1170164f1554fa54d
IBRAR21/IntroToProg-Python
/Assigment05_IBRAR.py
3,886
3.84375
4
# ------------------------------------------------------------------------ # # Title: Assignment 05 # Description: Working with Dictionaries and Files # When the program starts, load each "row" of data # in "ToDoList.txt" into a python Dictionary. # Add the each dictionary "r...
5b12da7ef3dd2f4eb9c36183897d14cf7cadf0bc
fangrin08/python-primer
/second.py
345
3.953125
4
import math some_text = "1a2b3c4d" def is_letter(texts): if texts in "abcdefg": return True else: return False def extract_letters(text): s = "" for c in text: if is_letter(c): s = s + c print("partial = " + s) else: print(c + " is a number!") return s letters = extract_letters(some_text) pri...
7f021755ec5991c20b69e6eae0dd0967d3c55904
malcolmgreaves/pyprocut
/{{cookiecutter.repo_name}}/{{cookiecutter.package_name}}/utils.py
3,136
3.640625
4
import logging import os import shutil from pathlib import Path from typing import Sequence, Optional, Tuple, Any def make_logger(name: str, log_level: int = logging.INFO) -> logging.Logger: """Create a logger using the given :param:`name` and logging level. """ if name is None or not isinstance(name, str...
c7a71766c0e273939c944342abd04ad7c6043f51
MrLawes/quality_python
/12_不推荐使用type来进行类型检查.py
2,031
4.4375
4
""" 作为动态性的强类型脚本语言,Python中的变量在定义的时候并不会指明具体类型,Python解释器会在运行时自动进行类型检查并根据需要进行隐式类型转换。按照Python的理念,为了充分利用其动态性的特征是不推荐进行类型检查的。如下面的函数add(),在无需对参数进行任何约束的情况下便可以轻松地实现字符串的连接、数字的加法、列表的合并等多种功能,甚至处理复数都非常灵活。解释器能够根据变量类型的不同调用合适的内部方法进行处理,而当a、b类型不同而两者之间又不能进行隐式类型转换时便抛出TypeError异常。 """ def add(a, b): return a + b """ 不刻意进行类型检查,而是在出错的情...
0f4da657552e172025f3b4ede87a233ffdafab51
MrLawes/quality_python
/19_有节制地使用from...import语句.py
4,555
3.78125
4
""" Python提供了3种方式来引入外部模块:import语句、from...import...及__import__函数。 其中较为常见的为前面两种,而__import__函数与import语句类似, 不同点在于前者显式地将模块的名称作为字符串传递并赋值给命名空间的变量。在使用import的时候注意以下几点: ·一般情况下尽量优先使用import a[插图]形式,如访问B时需要使用a.B的形式。· 有节制地使用from a import B形式,可以直接访问B。·尽量避免使用from a import *, 因为这会污染命名空间,并且无法清晰地表示导入了哪些对象。 """ """ 为什么在使用import的时候要注意以...
c047864044d2270efeef97adf40483da5cdbeced
MrLawes/quality_python
/10_充分利用Lazy evaluation的特性.py
1,057
4.25
4
""" Lazy evaluation常被译为“延迟计算”或“惰性计算”,指的是仅仅在真正需要执行的时候才计算表达式的值。 充分利用Lazy evaluation的特性带来的好处主要体现在以下两个方面: 1)避免不必要的计算,带来性能上的提升。对于Python中的条件表达式if x and y, 在x为false的情况下y表达式的值将不再计算。而对于if x or y, 当x的值为true的时候将直接返回,不再计算y的值。因此编程中应该充分利用该特性。 """ """ 2)节省空间,使得无限循环的数据结构成为可能。Python中最典型的使用延迟计算的例子就是生成器表达式了,它仅在每次需要计算的时候才通过yield产生所需要的元素...
7ef3708e603ae031572167066e5044e6f24ee068
jkHaam/django
/regular_expression_test.py
305
3.5625
4
import re def validate_phone_number(number): #핸드폰 체크 if not re.match(r'^01[016789][0-9]\d{6,7}$', number): return False return True print(validate_phone_number('01012341234')) print(validate_phone_number('0101112222')) print(validate_phone_number('010111112222'))
e65f822dc56d694c6dc62b0b26fbbdb744dcc823
fahmyabida/python-basic_learning
/soal1.py
234
3.703125
4
cars = ["Toyota", "Honda", "Mitsubishi"] for car in cars: print "this is brand from", car if car == "Toyota": print " - Camry" elif car == "Honda": print " - CR-V" elif car == "Mitsubishi": print " - Pajero"
f3738fd5bf9df2a2ca93adb4c706dc28870bc8a5
amxsa/python_demo
/pythonAPI/04.set.py
281
3.84375
4
#coding:utf-8 #set无序,不重复 #set里面不能放入list set1=set([1,2,3]) #输出为{1,2,3} print(set1) set2=set([2,2,3,4]) set1.add(4) set1.remove(4) #set的交集 print(set1&set2) #set的并集 print(set1|set2) # list去重 list1 = [2, 4, 3, 4, 5] print(list(set(list1)))
431ef06eaedab40960f81efab3aaae1276f4c490
amxsa/python_demo
/pythonAPI/20.实例属性和类属性.py
811
3.6875
4
#coding:utf-8 class Student(object): name="Stu" def __init__(self,name): self.name=name s=Student("Bob") s.score=90 #实例属性 print(s.name) #类属性 print(Student.name) print("\n===================\n") #给实例绑定属性和方法 class Person(object): pass p=Person() #动态给实例绑定一个属性 p.name="Xiaohua" print(p.name) #定义一个函数作为实例方法 def set_a...
d5b5a1455f0c502525b8a04df9738906d5ed9c2d
AmnesiaWu/NN
/sources/Practice1.py
494
3.703125
4
# encoding:utf-8 # class Solution: def bin_rev(self, int_input): """ :param int_input: int :return:int """ bin_input = bin(int_input) result_bin = bin_input[::-1][:-2] # 把输入的整数的二进制数翻转 result_int = int(result_bin, 2) return result_int if __name__ == '_...
6f3810e4b3dae9d48fabef845b56465f3a0b7324
rebeling/monday-morning-mite
/results.py
1,072
3.671875
4
def overview(users, notes=False): for i, u in enumerate(users): print '{}. {}\n{}'.format(i, u, '-'*79) stats = users[u]['statistics'] for k in ['total entries', 'tasks', 'billable', 'references', 'time total', 'mean per entry', 'shortest entry', 'long...
a9851d6286afaa894a86b3674849cd72ccc05d40
kesch9/Alg_Data_Structur_Python_Homework
/lesson_3/task1.py
375
3.75
4
# В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне от 2 до 9. x = list(range(2,100)) y = list(range(2,9)) print() rez =[] for i in x: ind = 0 for j in y: if i%j == 0: ind += 1 rez.append(ind) print(rez)
2d64b3b0f14096ea0070e04a6769ccf7abe0e8d4
kesch9/Alg_Data_Structur_Python_Homework
/lesson_1/task5.py
480
4.0625
4
# Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят и сколько между ними находится букв. a = ord(input("Введите первую букву ")) b = ord(input("Введите первую букву ")) a = a - ord('a') + 1 b = b - ord('a') + 1 print(f'Место первой буквы = {a}, второй = {b}') print(f'Разница = {abs(a-b)-1}')
baf96cd8bbc8142fcffb7b89a125241a62a7ee5d
kesch9/Alg_Data_Structur_Python_Homework
/lesson_3/task5.py
237
3.890625
4
# В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию в массиве. x = [1, 2, -3, -25, 0] print(x.index(min(x)))
e7ba2b9d5dd01c9e8483b9296dc26f0bd1177f9e
a26703248/Arduino4Py_2021
/case02/LambdaLab.py
1,144
3.625
4
''' 作業 (利用 lambda) id = 'A123456789' 第二碼 sex = id[1] -> 1 (1: 男生, 2: 女生) 第三碼 area = id[2] -> 2 (0~5: 台灣, 6: 外國, 7: 無戶籍, 8: 港澳, 9: 大陸) 印出: 台灣男 ''' def Belonging(x): sex = "" if x == 1: sex = "男" else: sex = "女" def nation(y): country = " " if y <= 5 and y > 0: ...
7e01564c4fdc1409e931404afdb51735016c81cf
a26703248/Arduino4Py_2021
/Project_Demo/OpenWeather.py
1,144
3.640625
4
# 絕對溫度 273.15 import requests import json import urllib.request import ssl # ssl不用驗證 def openWeather(): city = 'taoyuan' count = 'tw' apikey = '9843047d16e20413cf8f4203c24e5d29' url = 'https://api.openweathermap.org/data/2.5/weather?q={},{}&appid={}' \ .format(city, count, apikey) resp =re...
3fcd04a7dc8d8306cf4d1d9fd09a785fcc4e8b6e
MultiparameterTDAHistology/SpatialPatterningOfImmuneCells
/one_parameter_classes.py
8,896
3.515625
4
import numpy as np import matplotlib.pyplot as plt import copy import numbers class Bar(object): """A single bar, which should be contained in a Barcode""" def __init__(self, start, end, multiplicity): """Constructor. Takes start/birth, end/death, and multiplicity.""" self.start = start ...
3b9b8ccc58875db61691c0e4dfbd5222967c70ab
Hitthesurf/PythonFun
/Hangman_Game/test_hangman.py
2,330
3.828125
4
from unittest import TestCase import Hangman_Game.Hangman as Hangman class TestHangman(TestCase): def test_update_word_updates_display_word_correctly_for_given_letter(self): word = Hangman.Hangman() word.true_word = "Apple" word.display_word = "_ _ _ _ _" word.update_wor...
15890b3c25d8da97b18943518357cba494cb0845
sabergjy/Leetcode_Programing
/23.合并K个升序链表.py
3,843
3.921875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: #法一:顺序合并 o(k**2*n) k是链表个数,n为链表长度 python会超时 def mergeTwoListNode(node1, n...
029c5a48acfb93b3b509e58c53459aebc1e3b483
sabergjy/Leetcode_Programing
/25.K 个一组翻转链表.py
1,480
3.78125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: #1.每k个一组组,一循环(执行反转函数) #反转好后头尾接入链表 def reverseKListNode(head,ta...
4fba1f30386a3cd8e90ec4c9082b5133402e7169
poudyalanil/hpc-coursework
/password_cracking/mr.py
1,218
3.90625
4
#!/usr/bin/python3.6 ########################################################################## # # This program is used to run other programs a number of times. The name # of the program to run is the argumnet to this program. Assuming that # this file is named mr.py you need to make sure that it is executable # wi...
3a4283d222014ac24604cbf34811920b4e9b7834
ElizabethBeck/Class-Labs
/BeckLab02P3.py
412
3.78125
4
T = 1.08 # tax for each day F = 5.00 # one time fee R = 100 # room rate d = int(input("Enter the number of days stayed at the hotel ")) c = 0 # initialize cost variable if (d > 0): # days > 0 # calculations here to compute the solution c = T*(R*d) + F print(" the cost for ", d, " days is ", ...
2b5033eb83c77c3a40579e70701a7059826e0706
amresh1495/Udemy-course-follow-up-code
/UDEMY_COURSE.PY
4,103
4.59375
5
# Python code follow up on udemy course - The four pillars of object oriented programming in python # check if an employee has achieved his weekly target - class Employee: """attributes like name, designation etc are included below to help understand more about the class""" name = 'Amresh' design...
5ddd963bc1354a0593e0797ef80d1078690484cf
Lay-RosaLauren/Coursera-Python-2
/Week02/maisculas.py
671
3.875
4
# Recebe uma string e retorna todas as letras maiúsculas em ordem de ocorrência def maiusculas(frase): maiusculas = [] for i in range(len(frase)): caracter = frase[i] decASCII = ord(caracter) if decASCII > 64 and decASCII < 91: maiusculas.append(caracter) ...
eb21641a0bc733a13df560c458d10749d4b72fa4
Lay-RosaLauren/Coursera-Python-2
/Week01/matriz_mult.py
323
3.546875
4
def dimensoes(matriz): return (len(matriz), len(matriz[0])) # Verifica se as matrizes recebidas são multiplicavéis def sao_multiplicaveis(m1, m2): dimensao_m1 = dimensoes(m1) dimensao_m2 = dimensoes(m2) if dimensao_m1[1] == dimensao_m2[0]: return True else: return False ...
1cc6852def3f885aa8a276a33991329e27cc8db3
Lay-RosaLauren/Coursera-Python-2
/Week06/elefantes1.py
448
3.96875
4
def incomodam(n): if type(n) != int or n <= 0: return '' else: str1 = 'incomodam ' return str1 + incomodam(n - 1) def elefantes(n): if type(n) != int or n <= 0: return '' if n == 1: return "Um elefante incomoda muita gente" else: ...
a949ddd50bbad777b1b1d054e743330ffa8a5921
TILhub/Data-Cleaning
/NLTK basic cleaning/Keywords.py
2,379
3.625
4
#author Sahil Malik #Time 12:34 AM #Location New Delhi import nltk #for removing conjunctions pronouns and prepositions from nltk.tokenize import word_tokenize from nltk.corpus import stopwords import string from nltk.stem.porter import PorterStemmer #reading input file file1=open('text.txt','r') text=file1...
56b3c204f607e7fb1c4ff4062df9c733b24ccbc2
ZhiweiPan/week5-6
/prac3-4.py
7,458
3.78125
4
import tkinter import math import tkinter.messagebox class Calculator: def __init__(self): self.root = tkinter.Tk() self.root.minsize(280,450) self.root.maxsize(280,480) self.root.title("Simplified Calculator") self.result = tkinter.StringVar() self.result.set(0) ...
9d2e0456cc294c606ac2c33bdafa79de7ad19e26
Likitha-dotcom/Python_Lab
/modules/operator_overloading.py
870
3.796875
4
#overload operators and function using modules class Oper: def __init__(self): self.alist=[] def get(self): n=int(input("Enter the list size:")) for i in range(0,n): ele=int(input("Enter the elements:")) self.alist.append(ele) #print(self.alist) def __add__(self,other): new_list=[] for i in range(...
d25230bedac976f12660889de3f7f67481c73472
ShirkeJR/PythonLearn
/Zajecia25.10.2017/zad1.py
1,116
3.5625
4
import math class LiczbaZespolona: def __init__(self, a, b): self.a = a self.b = b self.modul = self.__funModul() def __str__(self): return "%i + %ii" % (self.a, self.b) def __add__(self, other): return LiczbaZespolona(self.a + other.a, self.b + other.b) def __su...
d3bf0386cc51e9709cc35a2225eba8057487eefe
ShirkeJR/PythonLearn
/Zajecia22.11.2017/zad1.py
458
3.53125
4
import math def pobierzLiczbe(liczba): try: pierw = math.sqrt(liczba) except (TypeError, ValueError) as ex: print "Zle dane: " + str(ex) else: return pierw finally: print "Koniec" print pobierzLiczbe(2) print pobierzLiczbe(-2) print pobierzLiczbe("Tak") try: licz...
4a495068d36aa5efa2386abec4581c5f791d57d1
ShirkeJR/PythonLearn
/DiceGame/Rule.py
1,671
3.609375
4
from collections import Counter class Rule(object): @staticmethod def calculate_points(rule, dices): most_common_result = Counter(dices).most_common() if rule == "a": return sum(dice.result == 1 for dice in dices) elif rule == "b": return sum(dice.result == 2 fo...
cb229252f297caac2a1dcdb71e42c1fec72bbd2b
liamdebell/liamdebell.github.io
/py/task3_c.py
179
3.921875
4
force = [] numberlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] num = int(5) for i in numberlist: if i < num: force.append(i) sumf = sum(force) print(force, "or the sum: ", sumf)
4f1671979fb8a51eefc77dbad2241fc96d6c01f8
haohaowasky/Sliding-Window-Average
/Version1.py
587
3.6875
4
class MovingAverage(object): def __init__(self, size): # Initialize your data structure here. self.size = size self.sum = 0.0 self.array = [] self.counter = 0 # @param {int} val an teger def next(self, val): # Write your code here sel...
72ff2bdee4d6faa9f8e7327632f427c1d932cb05
Behzadkha/Python
/src/ReadAllocationData.py
2,806
3.671875
4
## @file ReadAllocationData.py # @author Behzad Khamneli # @brief This code reads student information and returns the necessary files for allocation of students. # @date 1/18/2019 ## @brief This function returns a list of dictionaries of student information. # @details ReadStdnts accepts a string corresponding to...
171326d5db817cc063ba21f5c68d78b15da34b42
ItaiHenn/BIU-Engineering-2021
/Ex_4_Q_4_by_Dudu_Gvili.py
1,291
3.953125
4
#A restaurant networks want to open branches along a highway #there are 'n' available places given in list m[] #at each location you can open 1 restaurant and the profit will be according to list p[] in same index of m[] #the distance between 2 branches has to be atleast 'k' #write an algorithm that find the maximum pr...
2522084a92aab51849700787b5014b1da2f5aa09
NorahJC/RegressionAnalyses
/SimpLinReg.py
3,417
3.9375
4
##Norah Jean-Charles ##2/4/2019 ##Simple Linear Regression ##Dr.Aledhari ##CS4267-Machine Learning ##Section 1 ##Spring 2019 import numpy as np import pandas as pd import matplotlib.pyplot as plt # Import dataset dataset = pd.read_csv('Salaries-Simple_Linear.csv') print(dataset) # Gives (# of rows, # of col) ##print...