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
6558d052e684878a271533df745aa0aaf398d710
apollo-chiu/password-retry
/pssw-try3.py
267
3.84375
4
key = 'a123456' x = 3 while x > 0: x = x - 1 psw = input('請輸入密碼: ') if psw == key: print('登入成功!') break else: print('密碼錯誤!') if x > 0: print('還有', x, '次機會') else: print('沒機會嘗試了! 要鎖帳號了啦!')
a9540bff47bfe8f9939f81c00fefa3348e91675c
tianshuaifei/kaggle
/feature.py
1,222
3.890625
4
import numpy as np #类别变量处理 treat categorical features as numerical ones #1 labelencode #2 frequency encoding #3 mean-target encoding #https://www.kaggle.com/c/petfinder-adoption-prediction/discussion/79981 # Mean-target encoding is a popular technique to treat categorical features as numerical ones. # The mean-target...
69b848ed2eeae8f3090a9c35b2cdf12bc4dd29e5
Rita626/HK
/Leetcode/237_刪除鏈表中的節點_05170229.py
1,671
4.21875
4
#題目:请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, ...
4e485050a23b744142df8dc609002818dd9044c9
Eduardo-Chavez/Unidad2Evaluacio-n
/Iniciales_login.py
194
3.9375
4
usuario = input ("Ingresa tu usuario: ") contra = input ("Ingesa tu contraseña: ") if usuario == "utng" and contra == "mexico": print ("Bienvenido") else: print ("Datos incorrectos")
2991c345efe646cedda8aeaeeebe06b2a4cc6842
drmason13/euler-dream-team
/euler1.py
778
4.34375
4
def main(): """ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ test() print(do_the_thing(1000)) def do_the_thing(target): numbers = range(1, target) answer =...
0c9c7fbf5ea0ed3591fd4aee2c9ac9de4b2392a6
paulbradshaw/scrapers
/festivaltweetsjson.py
1,713
3.65625
4
#!/usr/bin/env python import json import csv import requests import urllib import scraperwiki jsonurlgh = 'https://raw.githubusercontent.com/paulbradshaw/scraping-for-everyone/gh-pages/webpages/cheltenhamjazz-export.json' jsonurl = 'https://paulbradshaw.github.io/scraping-for-everyone/webpages/cheltenhamjazz-export.j...
1ce80703b6e762b4913a7c906fc23143363e2bae
paulbradshaw/scrapers
/westminstercouncilevents.py
1,660
3.578125
4
#!/usr/bin/env python import scraperwiki import urlparse import lxml.html import urllib2 import datetime #more on datetime here: https://www.saltycrane.com/blog/2008/06/how-to-get-current-date-and-time-in/ now = datetime.datetime.now() currentmonth = now.month currentyear = now.year currentday = now.day print str(n...
01c12a1ab03ab87a404dbd42b9a755be0ed03173
maymashd/BFDjango
/week 1/Informatics mcc/Cycle While/D.py
151
3.5625
4
import math n=int(input()) i=1 ok=False while i<=n: if i==n: ok=True i=i*2 if (ok==True): print("YES") else: print ("NO")
e2e7128884e11dbc5dba935b8986c987663633db
maymashd/BFDjango
/week 1/Informatics mcc/Array/B.py
140
3.609375
4
import array n=int(input()) a=input() arr=a.split(" ") for i in range(0,len(arr)): if (int(arr[i])%2==0): print(arr[i],end=' ')
5ff1f253950b663e79b8d4450e458aa43937d802
maymashd/BFDjango
/week 1/Informatics mcc/Cycle For/K.py
105
3.5
4
import math cnt=0 n=int(input()) for i in range(1,n+1): a=int(input()) cnt=cnt+a print(cnt)
27662057212e19516566758c0cdde3eb883a90a2
valeriuursache/scratchpad
/module 3/cat_strings.py
637
3.71875
4
if __name__ == "__main__": #Concatenation #You can concatenate two strings together using + leia = "I love you." han = "I know." print(leia + ' ' + han) ship = "Millinium Falcon" # Python starts at 0, slices TO the end index (not included) print("'" + ship[10:] + "'") bold_state...
6f1aa43d0614cd211b0c92a48b182cf662e230fa
nmaswood/Random-Walk-Through-Computer-Science
/lessons/day4/exercises.py
720
4.25
4
def fib_recursion(n): """ return the nth element in the fibonacci sequence using recursion """ return 0 def fib_not_recursion(n): """ return the nth element in the fibonacci sequence using not recursion """ return 0 def sequence_1(n): """ return the nth element in the sequ...
5f31e4cdf81801c19d737535ca94fb49ceab59fb
dangriffin13/Project_Euler
/euler21_amicable_numbers.py
662
3.578125
4
import math t = int(input()) def sum_of_divisors(number): s = 0 stop = int(math.floor(math.sqrt(number))) for i in range(2,stop): if number%i == 0: s += i + number/i return int(s+1) amicable_numbers = [] for i in range(100001): y = sum_of_divisors(i) if sum_of_diviso...
cd4d8070eeaa1eff50473cb6d89f3cedbf973b66
LawlessJ/Object_Oriented_Programming_Project
/Script.py
2,987
3.703125
4
from datetime import datetime class Menu: def __init__(self, name, items, start_time, end_time): self.name = name self.items = items self.start_time = datetime.strptime(start_time, "%I %p") self.end_time = datetime.strptime(end_time, "%I %p") self.times = [self.start_time, self.end_time] def...
51ed6228cc6ff33b400a250782b2b0d9b16daf09
RohilH/Convolutional-Neural-Network-using-TensorFlow
/cnnTensorFlow.py
2,468
3.515625
4
from keras.models import Sequential from keras.layers import Dense, Conv2D, Flatten import matplotlib.pyplot as plt from keras.datasets import mnist from keras.utils import to_categorical import numpy as np # (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = np.load("data/x_train.npy") X_trai...
bed140408d860cdaa01ba616ac984a3beb4029ae
benoitantelme/python_ds_ml_bootcamp
/05-Data-Visualization-with-Matplotlib/02-Matplotlib Exercises.py
3,412
3.75
4
#!/usr/bin/env python # coding: utf-8 # ___ # # <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> # ___ # # Matplotlib Exercises # # Welcome to the exercises for reviewing matplotlib! Take your time with these, Matplotlib can be tricky to understand at first. These are relatively simp...
d460b9928fa6276cd94ab510d3c24b7aa8932a34
shanefay/MachineLearning
/assignment2/estimate_scorer.py
2,528
3.515625
4
from sklearn.metrics import make_scorer from sklearn.model_selection import train_test_split, cross_validate def split_estimate(estimator, X, y, metrics, test_size=0.3): """Score an estimated model using a simple data split. A 70/30 split of training to testing data is used by default. Args: esti...
4d0f3b2e8eb544407de5ed9cd04ef2347628ff19
Inlinesoft/POC.ECS.Python.App
/utilities/email.py
2,975
3.59375
4
import smtplib import definitions class Email: """ Send out emails (with or without attachments) using this class. Usage: With attachment email = Email(server_name) email.send_mail(send_from, send_to, subject, text, files) Without attachment email = Email() email.send_mail(send_fr...
2512b1f39ae0d570fae3dda36f2950254a085549
jfernand196/Ejercicios-Python
/funcion_all.py
146
3.71875
4
# verificarf que todos los items iteravles cumplan una condicion lista = [2, 4, 6, 7] print(all(x > 4 for x in lista)) h = "juan" print(type(h))
60dab56c8c06bc13f3c182ec1dbb11832298c6d2
jfernand196/Ejercicios-Python
/farmeteos de string y float.py
190
3.734375
4
palabra = "!aprendiendo python!" print("%.6s" % palabra) print("%.12s" % palabra) real = 2.6578 print("valor es: %f" % real) print("valor es: %.2f" % real) print("valor es: %.13f" % real)
1bb1c0e327300b98526b91d88217cd75360260bf
jfernand196/Ejercicios-Python
/concatenar_lista.py
319
3.53125
4
# simular la funcion join numeros = [2,4,5,77] #opcion 1 #print('juan'.join([str(n) for n in numeros])) #print('juan'.join(numeros)) #opcion 2 def concatenar_listas(lista): resultado= '' for i in lista: resultado +=str(i) return resultado numeros = [2,4,5,77] print(concatenar_listas(numeros))
30163909aeaaa4efaa8d27365f4631b18390aab4
jfernand196/Ejercicios-Python
/operador_not.py
382
3.53125
4
#Operador logico de negacion de verdad: NOT print('Operador logico de negacion de verdad : NOT') llueve = True print('contenido de la variable llueve:', llueve) llueve = not llueve print('contenido de la variable llueve:', llueve) print() edad = 17 resultado = not edad < 18 print('Resultado', resultado) edad ...
7b884b25dd4b1f427e61c8259d7673e9f49706cb
jfernand196/Ejercicios-Python
/makeitreal03.py
390
3.953125
4
# Duplica cada elemento # Escribe una función llamada duplicar que reciba un arreglo de números como parámetro y retorne un # nuevo arreglo con cada elemento duplicado (multiplicado por dos). # duplicar([3, 12, 45, 7]) # retorna [6, 24, 90, 14] # duplicar([8, 5]) # retorna [16, 10] def duplicar(x): return [i*2 f...
42d3e9a30261a005a547a0957c4e53d2a19d5911
jfernand196/Ejercicios-Python
/examen_makeitreal.py
610
4.21875
4
# Temperaturas # Escribe una función llamada `temperaturas` que reciba un arreglo (que representan temperaturas) y # retorne `true` si todas las temperaturas están en el rango normal (entre 18 y 30 grados) o `false` de # lo contrario. # temperaturas([30, 19, 21, 18]) -> true # temperaturas([28, 45, 17, 21,...
661cafb9861064d8006a56dceaf4177a0131bf31
jfernand196/Ejercicios-Python
/gen_num_primos.py
652
3.578125
4
## Generar n cantidad de numeros primos consecutivos # 2, 3, 5, 7, 11 ... def generar_primo(): numero = 2 yield numero while True: temp = numero while True: temp += 1 contador = 1 contador_divisores = 0 while contador <= temp: ...
38b85a7e4050e345f3b1eedadb288fcec5dad51a
jfernand196/Ejercicios-Python
/letcode_1678.py
855
4.09375
4
# You own a Goal Parser that can interpret a string command. The command consists of an alphabet # of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", # "()" as the string "o", and "(al)" as the string "al". The interpreted strings are # then concatenated in the original...
342bd4524146685a04fb5bbc20fe03f51d4baedd
jfernand196/Ejercicios-Python
/try_except_else_finally.py
435
3.921875
4
# Programa que le pide al usuario la edad (edad entero) y comprueba #si ese usuario es mayor de edad (18 años) try: numero = int(input('introduce tu edad: ')) except ValueError: print('no has introduciod un nuemero entero') else: if numero >= 18: print('eres mayo de edad') else: ...
d13db4be9d30a72dbe1edb5af5178d3b897fbf4d
jfernand196/Ejercicios-Python
/area_triangulo.py
466
3.859375
4
## Calcular el area de un triangulo base = None altura = None while True: try: base = float(input('escriba la base del triangulo: ')) break except: print('Debe de escribir un numero.') while True: try: altura = float(input('escriba la altura del triangulo: ')) brea...
2b8f6de2b9ac1a87bbc8a2e27df982fb72bef80f
ChetanVDhawan/PythonDataStructures
/LinkedList.py
2,290
4.03125
4
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.start = None def add(self, data): node = Node(data) if self.start is None: self.start = node return temp = self.start ...
59b2ff13da21c4d38f95749450ba726579c69209
piranna/asi-iesenlaces
/0708/listas/ej234.py
568
3.96875
4
# -*- coding: cp1252 -*- #$Id$ """ Disea un programa que elimine de una lista todos los elementos de valor par y muestre por pantalla el resultado. (Ejemplo: si trabaja con la lista [1, -2, 1, -5, 0, 3] sta pasar a ser [1, 1, -5, 3].) """ # mtodo 1: con while lista = [1, -2, 1, -5, 0, 3] i = 0 while ...
bae04ed2f85dc7b04153764d391fedf3f3148106
piranna/asi-iesenlaces
/0708/examenes/27feb/1234.py
3,292
3.765625
4
# -*- coding: utf-8 -*- def listadoAlumnos(listaAlumnos, curso, grupo=0): """ Entrada: una lista de alumnos como la indicada anteriormente, el nombre de un curso y opcionalmente el número de un grupo. Devuelve una lista con los datos de los alumnos del curso y grupo indicados. Si no se indica grupo, devolv...
4733fe243f4582efe2705f4181188a2920f3f846
piranna/asi-iesenlaces
/0708/repeticiones/ej118.py
989
3.84375
4
# -*- coding: utf-8 -*- """ $Id$ Realiza un programa que proporcione el desglose en billetes y monedas de una cantidad entera de euros. Recuerda que hay billetes de 500, 200, 100, 50, 20, 10 y 5 € y monedas de 2 y 1 €. Debes recorrer los valores de billete y moneda disponibles con uno o más bucles for-in. """ # Prese...
42bb3d5df47e7eb91425f7a92e19872ed16e3483
piranna/asi-iesenlaces
/0708/repeticiones/ej109.py
861
4.21875
4
# -*- coding: utf-8 -*- """ $Id$ Calcula el factorial de un número entero positivo que pedimos por teclado Si tienes dudas de lo que es el factorial, consulta http://es.wikipedia.org/wiki/Factorial """ # Presentación print "*" * 50 print "Programa que calcula el factorial de un número" print "*" * 50 # Petición del n...
ba9b41a053ff6e6ea6df38fae9807cb3ecd49220
piranna/asi-iesenlaces
/0708/examenes/23nov/exa10.py
1,744
4.09375
4
# -*- encoding: utf-8 -*- # $Id$ """ Escribe una función que reciba una lista de nombres y que imprima la lista ordenada. La lista tendrá la siguiente estructura: [ “Ana, Martínez, Blasco”, “Nombre,Apellido1, Apellido2”, ...]. La ordenación se hará según el siguiente criterio: Apellido1 – apellido2 – Nombre. Es de...
597e97399626f74acfdadf7a75811a102fa19ff4
piranna/asi-iesenlaces
/0708/repeticiones/ej129.py
930
3.734375
4
# -*- coding: utf-8 -*- """ $Id$ Haz un programa que calcule el máximo comun divisor (mcd) de dos enteros positivos. El mcd es el número más grande que divide exactamente a ambos numeros. Documentación: http://es.wikipedia.org/wiki/M%C3%A1ximo_com%C3%BAn_divisor """ # Presentación print "*" * 50 print "Programa máxi...
4c4716e3d4b6710d9452f20af531be6c2cd5a9f5
piranna/asi-iesenlaces
/0708/repeticiones/mayormenor.py
756
3.84375
4
# -*- coding: cp1252 -*- """ $Id$ Trabajos con series de nmeros Mayor, menor, media ... Cuidado con los valores no vlidos al procesar una serie """ num = int(raw_input("Introduce un num positivo: ")) mayor = num # candidato el primero menor = num total = 0 veces = 0 while num >=0: if num > ma...
54582356e4fb4257a8066bdcca0f4612837deca9
piranna/asi-iesenlaces
/0708/repeticiones/esprimo.py
564
3.890625
4
# -*- coding: utf-8 -*- """ $Id$ Calcula si un número es primo. Ej. pág 118. Hay que mejorar el algoritmo. """ num = int(raw_input("Introduzca un número: ")) creo_que_es_primo = True for divisor in range (2, num ): if num % divisor == 0: creo_que_es_primo = False # Esta parte necesita una mejora...
3c55d755d5a00cab0e2ef1847d1c90672d6ac23a
zllu2/iMSA_577
/lessons/Module2/notebooks/helper_code/mlplots.py
1,071
3.734375
4
import pandas as pd import numpy as np import seaborn as sns # Convenience function to plot confusion matrix # This method produces a colored heatmap that displays the relationship # between predicted and actual types from a machine learning method. def confusion(test, predict, labels, title='Confusion Matrix'): ...
44a036e4b3d596c701892a3905bb27e369f93018
seanx92/hotel_retrieval
/hotels/search.py
6,175
3.53125
4
import shelve import time import heapq from tokenization import tokenize def search(name, address, onlyOverall=True, tags=["cleanliness", "service", "value", "location", "sleep_quality", "rooms"]): ''' This function is used for finding the conjunctive result by searching by "address" and "name". ''' addre...
c10d96e43b1b728b1f42250686fcae0d9aae2b69
jcguy/AdventOfCode2017
/problem4.py
827
3.703125
4
#!/usr/bin/env python3 # Advent of Code, Problem 4 # James Corder Guy def main(): # Part 1 num_valid = 0 with open("problem4.txt") as f: for line in f: phrase = line.replace("\n", "").split(" ") if sorted(phrase) == sorted(list(set(phrase))): num_valid += 1 ...
795f82845050e500086eea28a79bdfc9654ed8b7
anwenliucityu/atomman
/mep/integrator/rungekutta.py
820
3.5
4
# coding: utf-8 def rungekutta(ratefxn, coord, timestep, **kwargs): """ Performs Runge-Kutta ODE integration for a timestep. Parameters ---------- ratefxn : function The rate function to use. coord : array-like object The coordinate(s) of the last timestep. timestep : f...
f9e60194c6a8df0e7755f45703ca36915db08388
maisha815/Solitaire_Cypher
/cipher.py
2,513
4.03125
4
import c_functions import os.path def validate_file_name(message): """ (str) -> str Prompt user the message to type the name of a file. Keep re-prompting until a valid filename that exists in the same directory as the current code file is supplied. Return the name of the file. """ ...
a7248417ac7f1924cd5db4323c8b3903bdda1047
grimsley217/608-mod1
/range.py
175
4.25
4
#range.py """This prints the range of values from the integers provided.""" x=min(47, 95, 88, 73, 88, 84) y=max(47, 95, 88, 73, 88, 84) print('The range is', x, '-', y, '.')
da79c29a1fa65206d5446bf374974aaef57b09e2
luiz-vinicius/IP-UFRPE-EXERCICIOS
/lista4_ex_8.py
265
3.640625
4
from random import randint s1 = str(input("Digite o 1º texto: ").replace("","")) s2 = str(input("Digite o 2º texto: ").replace("","")) len_s1 = len(s1) len_s2 = len(s2) print(len_s1) menor = len_s1 if(len_s2<menor): menor = len_s2 r = randint(0,menor) print(r)
9a28fbd169078b2133058156d9f7c3c8f86d38ae
luiz-vinicius/IP-UFRPE-EXERCICIOS
/aula_lista_ex_2.py
157
4.09375
4
lista = [] for x in range(10): v = float(input("Digite um valor: ")) lista.append(v) lista.reverse() for i,p in enumerate(lista): print(i+1,"º = ",p)
3323f4d0504f59a298ff413e4e79de25f23f79b0
luiz-vinicius/IP-UFRPE-EXERCICIOS
/lista3_ex_8.py
291
3.75
4
nome = str(input("Digite o nome do funcionário: ")) sal = float(input("Digite o salário bruto do funcionário: ")) des = sal *5/100 sal_liq = sal - des print("Nome do funcionário: {} \nSalário Bruto {:.2f} \nDesconto: {:.2f} \nSalário Líquido: {:.2f}".format(nome, sal, des, sal_liq))
03fc80b0a61c1c6a16672f55488287f969f0a0e3
luiz-vinicius/IP-UFRPE-EXERCICIOS
/if_ex_9.py
471
3.953125
4
peso = float(input("Digite seu peso: ")) altura = float(input("Digite sua altura: ")) imc = peso/(altura*2) if(imc<20): print("Abaixo do peso") elif(imc>20 and imc<=25): print("Peso ideal") elif(imc>25 and imc<=30): print("Sobrepeso") elif(imc>30 and imc<=35): print("Obesidade Moderada") el...
91e92a5aaf939ad7a970b43c0e9ac2984d8c3c80
luiz-vinicius/IP-UFRPE-EXERCICIOS
/lista4_ex_3.py
109
3.796875
4
nome = str(input("Digite o seu nome completo:")) espaço = nome.split(" ") print(espaço[-1],",",espaço[0])
e7c8dc1d1cf897ec181b2ddf648f0cda2b25af14
luiz-vinicius/IP-UFRPE-EXERCICIOS
/while_ex_1.py
523
3.796875
4
qnt_alunos = 0 qnt_altura = 0 while True: idade = int(input("Digite a idade: ")) if(idade<=100 and idade>0): altura = float(input("Digite a altura: ")) if(altura==0): break if(idade>=13): qnt_alunos +=1 if(altura>=1.5): ...
1cab19115488ffde362ca1a725cf79bce4d17030
luiz-vinicius/IP-UFRPE-EXERCICIOS
/if_ex_7.py
247
4.0625
4
v = input("Digite \nM-Matutino \nV-Vespertino \nN-Noturno \n: ") if(v=='M'or v=='m'): print("Bom dia!") elif(v=='V' or v=='v'): print("Boa Tarde!") elif(v=='N' or v=='n'): print("Boa Noite!") else: print("Valor Inválido!")
56aa08c0b985d4c08aba410e2c6f82ce2908be0a
luiz-vinicius/IP-UFRPE-EXERCICIOS
/for_ex_1.py
596
3.59375
4
c = 0 for i in range(10): qnt = int(input("Digite a quantidade itens vendidos pelo vendedor: ")) if(qnt>0 and qnt<=19): c = qnt*0.10 print("A comissão do {}º vendedor será de: {}%".format(i+1,c)) elif(qnt>=20 and qnt<50): c = qnt*0.15 print("A comissão do {}º vendedor...
de9ed90bb6c7ea52a2e457dfcddbe8014ff15f23
JoelsonSartoriJr/study-astronomy
/Nbody/main.py
2,983
3.578125
4
import numpy as np import matplotlib.pyplot as plt from acceleration import acceleration from energy import energy def main(): """ Init simulation N-body parameters""" N = 100 # Number of particles t = 0 # Time of the simulation tEnd = 10.0 # time at which simula...
efc673e72bf226503ca35988255ae723ce7b9071
keerthanachinna/first
/vowel1.py
176
4.125
4
c=input("enter the character") if(c=='a' or c=='A' or c=='e' or c=='E' or c=='i' or c=='I' or c=='o' or c=='O' or c=='u'or=='U'): print (c+,"vowel") else: print(c+,"consoant")
a7e7e5f0d0d6ea259a65432cfb51d99778ec1aa4
kaviyakaviyarasan98/practice
/factorial.py
86
3.671875
4
num=int(input()) i=1 fact=1 while(i<=5): fact=fact*i i=i+1 print(fact)
c4f579fb11e9282776556fe875783bdc04344f59
kanwar101/Python_Review
/src/Chapter07/parrot.py
265
3.921875
4
prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " message = "" active = True while active: message = input ("Do you want to Quit? ") if message != 'quit': print (message) else: active=False
7a932affcbd170fa57dcb114ac972460b47e3b54
kanwar101/Python_Review
/src/Chapter08/pizza.py
242
4.09375
4
def make_pizza(size, *toppings): """Print dynamic list of toppings""" print (f"You ordered {size} pizza with following toppings:") for topping in toppings: print (topping) #make_pizza( size='thin crust','olives', 'peppers','onion')
daacca98ea87613f501c1db9e060948ff3e7d018
kanwar101/Python_Review
/src/Chapter06/aliens.py
436
3.953125
4
aliens_0 = {'color':'green', 'point':5} alient_1 = {'color':'blue', 'point':7} alient_2 = {'color':'white', 'point':10} aliens =[aliens_0,alient_1, alient_2] for alien in aliens: print(alien) print("next item in the list") empty_aliens = [] for value in range(0,10): new_alien = {'color':'Orange', 'points':valu...
d2ab2cc50739a52b7a3fcfac1af26f54a621bb07
kanwar101/Python_Review
/src/Chapter11/test_name_function.py
351
3.5
4
import unittest from name_function import get_formatted_name class NameTestCase (unittest.TestCase): """Test for the name funtion""" def test_first_last_name (self): """testing formatted names""" formatted_name = get_formatted_name('Bob', 'Crow') self.assertEqual ('Bob Crow', formatted_name) if __name__ ...
98379659dbbd937bfc5db774006c392ce352f08d
kanwar101/Python_Review
/src/Chapter06/alien.py
739
3.5625
4
alien_0={'key1':'value1', 'key2':'value2','key3':'value3'} print (alien_0['key1']) alien_0['key4'] = 'value4' print (alien_0) empty_dict={} empty_dict['system'] = 'HP' empty_dict['OS'] = 'Chrome' empty_dict['processor']='intel' print (empty_dict) empty_dict['system']='Dell' print (empty_dict) # if loop with dicti...
ded6b6fb5db245ede155d1ceb4f9a67a4c68e0b9
kanwar101/Python_Review
/src/Chapter11/name_function.py
164
3.84375
4
def get_formatted_name (first, last, middle =''): """Print formatted name""" if middle: return f"{first} {middle} {last}" else: return f"{first} {last}"
2790f8ae5a5e897fa6d95dfafd5008c8169f0b53
kanwar101/Python_Review
/src/Chapter04/slice_list.py
151
3.5
4
players = ['bob','dan','steve','reddy'] print (players[1:3]) print (players[-1:]) print (players[-2:]) for player in players[2:4]: print (player)
b976f86e302748c97bcd5033499a0f2a928bcbdc
taddes/python-blockchain
/data_structures_assignment.py
1,053
4.40625
4
# 1) Create a list of “person” dictionaries with a name, age and list of hobbies for each person. Fill in any data you want. person = [{'name': 'Taddes', 'age': 30, 'hobbies': ['bass', 'coding', 'reading', 'exercise']}, {'name': 'Sarah', 'age': 30, 'hobbies': ['exercise', 'writing', 'crafting']}, ...
8820ec93b9d0c2cffea06dca6d832ac02b53996b
marboh1126/homework
/hw-3.py
326
3.71875
4
class Dog: def __init__(self, name, age): self.name = name self.age = age def bow(self): print('bowbowbow') def sayName(self): print('Name: ' + self.name) def sayAge(self): print('Age: ' + str(self.age)) dog = Dog('Masato', 24) dog.bow() dog.sayName() dog.say...
866b64d7ad1da8e45faed0f702565fa0544e12c1
changfenxia/gb-python
/lesson_1/ex_4.py
558
3.9375
4
''' 4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции. ''' number = input("Введите целое положительное число: ") max = int(number[0]) x = 0 while x < len(number): if (int(number[x]) > max): max = int(number[x]...
0eea84be3a43149c15164ee857b647d8fc7fd08b
changfenxia/gb-python
/lesson_5/ex_6.py
1,395
3.5
4
''' 6. Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный предмет и наличие лекционных, практических и лабораторных занятий по этому предмету и их количество. Важно, чтобы для каждого предмета не обязательно были все типы занятий. Сформировать словарь, содержащий название предмета и ...
e1ddd1d2897462bc6d6831993acdd9b9257554b2
changfenxia/gb-python
/lesson_1/ex_2.py
503
4.3125
4
''' 2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк. ''' time_seconds = int(input("Enter time in seconds: ")) hours = time_seconds // 3600 minutes = (time_seconds % 3600) // 60 seconds = time_seconds - (hours * 3600) - (...
672968de994d9c62f0edb21db7e9339c8bb2a2dd
felipedelta0/URIOnlineJudge
/1010 - URI Online Judge - Solved.py
1,202
3.953125
4
# -*- coding: utf-8 -*- ''' Neste problema, deve-se ler o código de uma peça 1, o número de peças 1, o valor unitário de cada peça 1, o código de uma peça 2, o número de peças 2 e o valor unitário de cada peça 2. Após, calcule e mostre o valor a ser pago. Entrada O arquivo de entrada contém duas linhas de dados. Em c...
edd4db95c5ca029c1378e16677318becafac984f
Artamamo/hwsys
/hw.py
1,778
3.75
4
import sys str = sys.argv n=0 uppercase = False EnglishCheck = False NumberCheck = False fail = False Check = False try: n=len(str[1]) except: print("請輸入字串") if n<8: print("長度小於8") sys.exit(0) elif n>16: print("長度大於16") sys.exit(0) list1 =list(str[1]) for i in range...
95cbcc07243fb919699df576b9bb1458637ddd49
sroy8091/daily_coding_problem
/find_missing_positive.py
1,039
3.859375
4
""" This problem was asked by Stripe. Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -...
4d22bc86b5997a8b622aebd80dc81a956863a926
RDH06/Python
/28-07-2018classprogram/Some_Process.py
598
3.546875
4
import os def File_to_Listwrds(fname): if not os.path.isfile(fname): return[] wordlst = [] with open(fname,'r') as fob: wordlst = [] for walk in fob: flst = walk.strip("\n").split() wordlst.extend(flst) return wordl...
f4b1f6480bbe645be84bbfc89b23b224bc87435c
kishannerella/CSE537
/P3/submit.py
4,025
3.625
4
#do not modify the function names #You are given L and M as input #Each of your functions should return the minimum possible L value #Or return -1 if no solution exists for the given L #Your backtracking function implementation import time def isSafe(assignments,marker): assignments[marker] = 1 keys = assign...
920f126b9081a52fd2882375de6a026e29470590
teamroke/tessas_first_program
/Tessa.py
378
3.609375
4
import random def get_name(weather): nickname = input('What is your nickname? ') print(f'That is funny, hello {nickname}') print(f'It is {weather} outside!') return nickname for i in range(1,5): print(f'You rolled a: {random.randint(1,20)}') print('argh!') name = input('What is your name? ') print...
255f6298f6215d04542086661c9fb3c8121d7f76
lhotse-speech/lhotse
/lhotse/parallel.py
2,663
3.71875
4
import queue import threading from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor from typing import Callable, Generator, Iterable def parallel_map( fn: Callable, *iterables: Iterable, num_jobs: int = 1, queue_size: int = 5000, threads: bool = False, ) -> Generator: """ ...
56aeca5ce7c3654160344be4329f5a8b821c16f8
shadowleaves/deep_learning
/cnn/tflayer_text_cnn.py
5,843
3.5625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Simple example using convolutional neural network to classify IMDB sentiment dataset. References: - Andrew L. Maas, Raymond E. Daly, Peter T. Pham, Dan Huang, Andrew Y. Ng, and Christopher Potts. (2011). Learning Word Vectors for Sentiment Analysis. The 49th...
edf5c327f33d0adac1a3638e4f67ab810ad40c7d
shadowleaves/deep_learning
/mxnet/mxnet_binary.py
8,507
3.515625
4
#!/usr/bin/env python import mxnet as mx import numpy as np from rnn import rnn_unroll, DataIter # from minpy_binary import create_dataset, printSample def create_dataset(nb_samples, sequence_len): """Create a dataset for binary addition and return as input, targets.""" max_int = 2**(sequence_len - 1) # Ma...
3bc0d6c4c609c1b412a9f4cc8d0855519079178a
guispecian/FATEC-MECATRONICA-1600792021024-Guilherme
/LTP1-2020-2/Pratica06/programa09.py
216
3.796875
4
#Repetição Infinita (Cuidado, pois se a variavel somatorio for = 1; o programa nunca acaba) somatoria = 0 while True: print(somatoria) somatoria = somatoria + 10 if somatoria == 100: break print("Fim")
67878144c8ee495452dbd731515c0858a040c586
guispecian/FATEC-MECATRONICA-1600792021024-Guilherme
/LTP1-2020-2/Pratica11/programa01.py
478
4.0625
4
#Calculo da area do triangulo #Função para calculo do semiperimetro def semiperimetro(a,b,c): return (a+b+c)/2 #Função para calculo da area def area(a,b,c): s = semiperimetro(a,b,c) return (s*(s-a)*(s-b)*(s-c)) ** 0.5 #Programação Principal #Informe os lados A, B e c a = int(input('Informe o valor do lado A:')...
70c81e53b62d9adcedb92dbec0e4d7a2eb4b46e0
anhtu96/algorithms
/sorting/counting_sort.py
586
3.5
4
def counting_sort_1(arr): maxval = max(arr) sorted_arr = [] L = [None] * (maxval + 1) for i in arr: if L[i]: L[i].append(i) else: L[i] = [i] for i in L: sorted_arr.extend(i) return sorted_arr def counting_sort_2(arr): maxval = max(arr) so...
b699ab088ff08f3c0c5c9f6cbb4d2a1564acd528
anhtu96/algorithms
/graph_algorithms/bfs.py
652
3.9375
4
from collections import deque class BFSResult(object): def __init__(self): self.level = {} self.parent = {} def bfs(g, s): """ Queue-based implementation of BFS. Args: - g: a graph with adjacency list adj s.t g.adj[u] is a list of u's neighbors. - s: source vertex. """ r =...
b5ea314bac79c17cc8ff66f43b999cc6a02ac2fb
EliasKassapis/Deep-Learning
/assignment_1/code/mlp_numpy.py
3,136
4.125
4
""" This module implements a multi-layer perceptron (MLP) in NumPy. You should fill in code into indicated sections. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from modules import * class MLP(object): """ This class implements a Multi-layer Pe...
b0a0ec721c9f7571a4f294c1b05aa07b3b82c2eb
marcozpina/DevNet
/AgendaTelefonica.py
1,362
4.09375
4
agenda_telefonica = {} while True: print () print ("-------- .: Menu :. --------\n") print ("1.- Ingresar nuevo contacto\n") print ("2.- Eliminar contacto\n") print ("3.- Consultar contactos\n") print ("4.- Salir del programa\n") select = int (input("Selecciona una opcion: ")) print ()...
0ef332e089b580d4c64f222ea88a6c8c0fb6d52e
arinanda/huffman-code-implementation-webapps
/storage/compressor/huffman/adaptive_huffman/adaptive_huffman.py
1,600
3.625
4
from common.util import Node def insert_node(null, char): char_node = Node(char, 1) empty_node = Node(parent=null.parent, left=null, right=char_node) char_node.parent = empty_node if null.parent: if null is null.parent.left: null.parent.left = empty_node else: n...
30da36f468a59b34608639ecf55725b37457a0a1
daniel-paul/Farm-Simulation
/Agent.py
8,522
3.65625
4
import math import copy import random import time from Simulator import Simulator # Main Agent class class Agent: def __init__(self, size, timeLimit): self.simulator = Simulator(size) # Simulator instance of the farm self.monteCarlo = MonteCarloTreeSearch(size) # Instance of the MonteCarloTreeSe...
a098d9405d28447a47f63db41a3500732cd21cb0
roshna1924/Python
/ICP4/sourcecode/naivebayes.py
962
3.75
4
#----------- Importing dataset -----------# import pandas as pd glass=pd.read_csv("glass.csv") #Preprocessing data X = glass.drop('Type',axis=1) Y = glass['Type'] #----------Splitting Data-----------# # Import train_test_split function from sklearn import model_selection # Split dataset into training set and test se...
7cdaebe77cfb044dfc16e01576311244caae283f
roshna1924/Python
/ICP1/Source Code/operations.py
590
4.125
4
num1 = int(input("Enter first number: ")) num2 = int(input("Enter Second number: ")) operation = int(input("Enter 1 for addition\n" "Enter 2 for Subtraction\n" "Enter 3 for multiplication\n" "Enter 4 for division\n")) def arithmeticOperations(op): switcher = { 1: "Result of addition : " + str(num1 + num2),...
bf98bd690471b14034136df54ebe676bb2e5b920
ryanpjbyrne/coffeecode2
/hello.py
90
3.71875
4
print("hello world") fruits= ["apple", "pear", "oranges"] for i in fruits: print(i)
0909e53fa788ef88debd3a3bceb5226b7e371332
vincentGuerlais/matCutPy
/matCutPy.py
2,116
3.546875
4
#! /usr/bin/env python import os import sys #################### ### Get Help #################### # print the help and exit the programm def getHelp() : print """matCutPy help Usage : python matCutPy.py input_file cutoff matCutPy generate a list of IDs with a total of estimated RNA-Seq ...
8d7937fd6aa3583e7c7937587f550f7809ac5f7a
aghyadalbalkhi-ASAC/Game_of_Greed
/game_of_greed/game_logic.py
2,593
3.5625
4
from abc import abstractmethod, ABC from collections import Counter import random class GameLogic(ABC): def __init__(self): pass @staticmethod def calculate_score(tupleInt): rules={ 1:{1:100,2:200,3:1000,4:2000,5:3000,6:4000}, 2:{1:0,2:0,3:200,4:400,5:600,6...
b314f7dbe6ddf2741b5f782b4abecdb9c6fbc5e9
ColinPLambe/MediumWebScraper
/mediumScraper.py
2,567
3.53125
4
from bs4 import BeautifulSoup import requests import sys import os.path """ Colin Lambe A Webscraper to get the number of words, number of claps, and article text from articles on Medium.com Uses BeatifulSoup4 and Requests """ class MediumScraper: def scrape(self, url, minWords, minClaps): #gets the artic...
b749422d017a275cf98d99062a852942d7bd6178
Mara-d/Prototype-sorting-algorithms-with-numbers
/Prototype-Sorting Algorithms/Sorting Algorithms Proto.py
7,294
3.96875
4
import time import random import tkinter as tk from tkinter import * import threading # This is a prototype, seeing numbers getting sorted in real time helps me visualize the algorithms better, # This program is by far finished, this is just a concept # I plan to have an OOP approach in the future window = tk.Tk(clas...
416b79accfdae13f2df358b5b9636403e75b6f62
CxrlosKenobi/cs50
/pset6/Sentimental/readability.py
694
4.0625
4
from cs50 import get_string letters = 0 words = 1 sentences = 0 text = get_string("Text: ") # Here we count the letters in the string for i in range(len(text)): if (text[i] >= 'a' and text[i] <= 'z') or (text[i] >= 'A' and text[i] <= 'Z'): letters += 1 # Here we count the words in the string if text[i] == ' ': ...
3c839f5ce1fc572fc78255520368ea3ef6952a48
vimleshtech/python_sep2
/oops2.py
389
3.53125
4
class emp: #first argument will take add of object #at least one argument need to recieve def newEmp(self): print(self) self.sid =input('etner data :') self.name =input('enter name :') def show(a): print(a) print(a.sid) ...
4626384e435e06e14c4c69eecd3f760a7c03278f
ivapanic/natprog-2019-2020
/Prijemni/KFC.py
1,280
3.640625
4
import sys def main(): m_meat, s_soy, h_bread = map(float, input().split()) pm_kn, ps_kn = map(float, input().split()) if h_bread == 0: max_earnings = 0 print(max_earnings) elif m_meat == 0 and s_soy == 0: max_earnings = 0 print(max_earnings) else: is_there_...
7aa71ae51a60ec0437058f1dbe26e9c8d070764f
BorisBelovA/Python-Labs
/7.1.py
711
3.796875
4
def makeSurnameDict(): my_file = open("students.csv", encoding='utf8') i = 0 dict = {} while True: line = my_file.readline() if(len(line) != 0): #print(line.split(';')) dict[i] = line.split(';') i+=1 else: break dict.pop(0) ...
bfed59521e007e81c2d062b67feed94de0807a3c
BorisBelovA/Python-Labs
/5.2.py
442
3.8125
4
def makeSurnameArray(): my_file = open("students.csv", encoding='utf8') arr = [] for line in my_file: arr.append(line.split(';')) arr = arr[1::1] for elem in arr: elem[3] = elem[3].replace('\n','') return arr def sortSurname(arr): surnamArr = [] i = 0 while(i<len(ar...
800b7e087ff43e689a00fc75a9bf4a0eb76a490c
BorisBelovA/Python-Labs
/4.2.py
162
3.609375
4
import random i = 0 list = [] while (i<10): list.append(random.randint(0,20)) i+=1 print(list) list = list[2::1] list.append(1) list.append(2) print(list)
cf7b22bbb77b7a208a8573982d2f78e05a01f3a8
arpancodes/100DaysOfCode__Python
/day-9/blind-auction.py
899
3.734375
4
from os import system, name from art import logo # define our clear function def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') print(logo) print("Welcome to the silent auction for 'The best painting'"...
1a50d400abbf33d7692ee73d847c7b90b317ab5d
Mahesh-5/Python
/Tic_Tac_Toe.py
3,959
3.90625
4
import random from itertools import combinations class Board(object): def __init__(self): self.board = {x:None for x in (7,8,9,4,5,6,1,2,3)} def display(self): """ Displays tic tac toe board """ d_board = '\nTIC TAC TOE:\n' for pos, obj in self.board.items(): ...
6cae3ccc0e4287a1ff3225051c788e8a8733ebc0
MaryLivingston21/IndividualProject
/Animal.py
598
3.71875
4
class ANIMAL: def __init__(self, name, breed, age): self.name = name self.breed = breed self.age = age def to_string(self): return self.name + ": a " + str(self.age) + " year old " + self.breed + '\n' def get_name(self): return self.name def get_breed(self): ...
6fe0f6441a3135f71e16c2b276a12c957858ccb5
RyanPeking/tkinter
/贪吃蛇.py
5,763
3.5625
4
import queue import random import threading import time from tkinter import Tk, Button, Canvas class Food(): def __init__(self, queue): self.queue = queue self.new_food() def new_food(self): ''' 功能:产生一个食物 产生一个食物的过程就是随机产生一个食物坐标的过程 :return: ''' #...