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
ff9f7ec04facfd5b436431e18a1c4c6d46a3976c
as-iF-30/My-Python
/floodfill.py
684
3.578125
4
#leetcode def floodFill(image, sr, sc, newColor): color = image[sr][sc] def fun(image,sr,sc,newColor,color): if(image[sr][sc]==color and image[sr][sc]!=newColor): image[sr][sc] = newColor if(sr>=1): fun(image,sr-1,sc,newColor,color) if(sr+1<len(image))...
50a88c887869ec5162d483e6b05727da552aa1d3
as-iF-30/My-Python
/stack.py
781
3.984375
4
class Stack: def __init__(self,size): self.size = size self.stack = [] def push(self,element): if self.size == 0: print('stack full') else: self.stack.append(element) self.size -= 1 def pop(self): if(self.stack == [] ): ...
c944fa7fc1c05795d46f39ef4956636ba44f977a
as-iF-30/My-Python
/basic2.py
632
3.5
4
#max count element test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4] print(max(set(test), key = test.count)) def x( ): return 1, 2, 3, 4 a, b, c, d = x() print(a, b, c, d) class MyName: Skill, Santa, Upskill = range(3) print(MyName.Skill) print(MyName.Upskill) print(MyName.Santa) #store n = 10 result = 1 < n < 20 print(res...
6d487cac6f5e42a683913e8c18899d5ff08f15f5
as-iF-30/My-Python
/basicfun.py
145
3.5
4
import itertools l = [1,3,2,6,1,2] c = 0 t = list(itertools.combinations(l,2)) print(t) l = [1,2,3] t = list(itertools.permutations(l)) print(t)
200aab6d017d69934a5698201cfdf12e48a78884
NecroReindeer/comp110-coding-task-1
/Client-Server Database/updatename.py
1,521
3.515625
4
#!/usr/bin/python """Update the name of a given player. The code in this file updates the name of a given player stored in the table of players in the highscores database. """ import cgi import cgitb import json import pymysql import processing def change_player_name(username, player_id): """Change the name ...
ef91a958487b036791414114005c6f37c2b5db04
karim-hb/practice-python-2
/convertToSecond.py
234
4.0625
4
def convert(time): hour = int(time[0:2]) minutes = int(time[3:5]) seconds = int(time[6:8]) print(hour*3600 + minutes*60 + seconds) time = input("please enter a full hour like 01:00:20 : ") convert(time)
4a96ee6aa058b1e4a82d47dfbc7ac154d37ad726
gourav071295/PythonCodes
/game.py
317
3.515625
4
print "\t\t\tWelcome to the game of numbers" name = raw_input("\tEnter your name :") print "\nYou entered " + name print "\nGreat ! Now Enter your password :" password = raw_input("\t Type your password here :") if password == "secret" : print "Access Granted" raw_input("\n Press Enter to exit")
54e250c7c93908773fd293b84468594d9706eb5d
incesubaris/Numerical
/secant.py
1,330
4.1875
4
import matplotlib.pyplot as plt import numpy as np ## Defining Function def f(x): return x**3 - 5*x - 8 ##Secant Method Algorithm def secant(x0, x1, error, xson, yson): x2 = x0 - (x0-x1) * f(x0) / (f(x0)-f(x1)) print('\n--- SECANT METHOD ---\n') iteration = 1 while abs(f(x2)) > error: if ...
2287864288827205f98be7e301deb75c78c8fa1f
bwbeckwi/Python
/dirtest.py
443
4
4
def replace_single_slash(slash): return slash.replace("\\","\\\\") current_dir = input("Enter current directory to copy from: ") target_dir = input("Enter target directory to copy to: ") if "\\\\" not in current_dir: current_dir = replace_single_slash(current_dir) if "\\\\" not in target_dir: target_d...
dfec1eedaca2e273de067d33b0331359e4c1c3da
bbearce/coding_tests
/Amazon/lot_problem.py
825
3.65625
4
lot = [[1,1,1,1,1,1,1], [1,1,0,1,1,1,1], [0,1,1,0,0,0,1], [0,0,1,1,1,1,9],] def bfs(grid, start): # queue=[start] width = len(lot[0]) height = len(lot) queue = [[start]] seen = set([start]) loop_limit = 3000 count=0 while queue and count < loop_limit: path =...
c35064703f7ed412ac6d8536c5356eaea1a66046
bbearce/coding_tests
/hacker_rank/python/easy/decorator_tutorial.py
4,309
3.96875
4
# [1] functions def foo(): return 1; # [2] scope a_string = 'this is a string' def foo(): print(locals()) foo() # {} print(globals()) # {..., 'a_string': 'this is a string'} # [3] varible resolution rules ### blah...it just says that local variables with the same name as global ones don't modify the global on...
b874620b4a29bd65d3577370525adada91391cfa
ppicavez/PythonMLBootcampD00
/ex07/cost.py
1,210
4.03125
4
import numpy as np def cost_elem_(y, y_hat): """ Description: Calculates all the elements (1/2*M)*(y_pred - y)^2 of the cost function. Args: y: has to be an numpy.ndarray, a vector. y_hat: has to be an numpy.ndarray, a vector. Returns: J_elem: numpy.ndarray, a vector of dimension (numb...
4cfefb42c88250aa58e56356cd9489a9eca915f6
ppicavez/PythonMLBootcampD00
/ex09/plot.py
1,399
4.15625
4
import matplotlib.pyplot as plt import numpy as np def cost_(y, y_hat): """Computes the mean squared error of two non-empty numpy.ndarray, without any for loop. The two arrays must have the same dimensions. Args: y: has to be an numpy.ndarray, a vector. y_hat: has to be an numpy.ndarray, a vec...
7a278079bd6b7ebd4dbb79011fc0f3bb1a77dfe5
vinagrace-sadia/python-mini-projects
/Hangman/hangman.py
1,330
4.125
4
import time import random def main(): player = input('What\'s your name? ') print('Hello,', player + '.', 'Time to play Hangman!') time.sleep(1) print('Start guessing . . .') time.sleep(0.5) # Lists of possible words to guess words = [ 'bacon', 'grass', 'flowers...
9f994b26f9b4bbb2eb91b2f705bcb132438e0257
fredkeemhaus/zero_base_algorithm
/python_basic/section10.py
4,355
3.609375
4
# Section10 # 파이썬 예외처리의 이해 # 예외 종류 # 문법적으로 에러가 없지만, 코드 실행(런타임) 프로세스에서 발생하는 예외 처리도 중요하다 # linter : 코드 스타일, 문법 체크 # ① SyntaxError (문법 에러) : 잘못된 문법 # print('Test) # SyntaxError: unterminated string literal (detected at line 10) # if True >>> SyntaxError: expected ':' # pass # x => y # ② NameError : 참조 변수가 없을 때 생기는 에...
790dd69517a00a4b80ec18d32211d78403e79c02
fredkeemhaus/zero_base_algorithm
/data_structure/14-7.py
4,517
3.546875
4
# 추가 예제 코드 # search_from_head # search_from_tail # insert_before class Node: def __init__(self, data, prev=None, next=None): self.prev = prev self.data = data self.next = next class NodeManageMent: def __init__(self, data): # 인스턴스 초기화시에는 아직 연결된 노드들이 없으므로, head 와 tail 모두 인스턴스 본...
03f4a8ffa7da986f30e69cd0f737a306eaf53e9a
fredkeemhaus/zero_base_algorithm
/python_basic/section12-3.py
1,594
3.53125
4
# Section12-3 # 파이썬 데이터베이스 연동(SQLite) # 테이블 데이터 수정 및 삭제 # DB 사용을 위한 패키지 import import sqlite3 # DB 생성(파일) conn = sqlite3.connect( '/Users/leejunhee/FastCampus/python_basic/resource/database.db') # 해당 경로애 있는 db 파일 DB Brwoser for SQLite로 열기 # Cursor 연결 c = conn.cursor() # 데이터 수정 1 (기본적인 형태로 수정하기 SQL 문법) # c.exe...
6d7bdda5d1552860a15bc5a252c395c6ed017bc9
fredkeemhaus/zero_base_algorithm
/python_basic/quiz2_2.py
1,169
3.859375
4
class Median: def __init__(self): self.item = [] def get_item(self, item): self.item.append(item) def clear(self): self.item = [] def show_result(self): self.item.sort() if len(self.item) % 2 == 1: idx = 0 idx = int(len(self.item)/2) ...
bcc1ad6c291450e157344c7ef26558eb9a7fb5bd
fredkeemhaus/zero_base_algorithm
/algo/bubble_sort.py
583
4.03125
4
data = [5, 1, 3, 10, 9, -1] # 1,3,5,9,-1,10 # 1,3,5,-1,9,10 # 1,3,-1,5,9,10 # 1,-1,3,5,9,10 # -1,1,3,5,9,10 # swap이라는 true false를 반환하는 boolean 값을 어디에 놓을지 아는 것이 중요 def bubble_sort(data): for index in range(len(data) - 1): swap = False for index2 in range(len(data) - index - 1): if dat...
922e9b6ffdd514134b75b935e7b0a0e7564ed982
fredkeemhaus/zero_base_algorithm
/algo/HappyNumber.py
549
3.515625
4
# def solution(n): # if n == 1: # return True # if n >= 10: # pass # return n // 10, n % 10, n # Test code # print(solution(1)) # True # print(solution(19)) # True # print(solution(61)) # False # print(solution(201)) # False def solution(n): r = s = 0 while(n > 0): r...
2d81cff070d030949787d422246f96bfb826e76a
jhnguyen521/SpeedCrafter
/scripts/parse_recipes.py
4,365
3.625
4
import os import json from collections import namedtuple class RecipeParser: """ Parse individual recipe JSON files into a single JSON file so they can be easily retrieved by other scripts. For simplicity, only the first choice gets added for recipes that accept different items (e.g. substitu...
e5eb3ba3404d6f56fead0ab54db6ddf3da04f154
ethanbar11/python_advanced_course1
/lecture_3/examples_2.py
314
3.6875
4
import sys print('woho') sys.stdout.write('Woho #2\n') raise Exception() x = sys.stdin.readline() sys.stderr.write(x) # Printing the string, and then accepting input from the user # and returns it. def my_input(string_to_print): pass # same as print, with enter in the end. def my_print(to_print): pass
88608003a64a994b7d78d09c29cf1174c35b34bf
DavideMaspero/python-alfabetizzazione-docenti
/esercizi/binomiale.py
322
3.671875
4
def fattoriale(numero): i = numero prodotto = 1 while i > 1: prodotto = prodotto * i i = i - 1 return prodotto print "inserire i valori n e k" n = input("n ") k = input("k ") binomiale = fattoriale(n) / (fattoriale(k) * fattoriale(n-k)) print "il coefficiente binomiale è ", binomiale...
4eb7b896756ccdf0fa4b579606b8cb3834c868c8
DavideMaspero/python-alfabetizzazione-docenti
/esercizi/percorso2.py
689
3.703125
4
def radice(numero): radice = 1.0 while (radice * radice) <= numero: radice = radice + 1.0 for i in range(0, 10): radice = 0.5 * (radice + numero / radice) return radice haltFlag = 1 lunghezza = 0.0 print "inserire le coordinate delle citta':" print "un valore negativo termina l'inser...
1537aee9542dbdba07a414fda91e7962fe6c94b9
DavideMaspero/python-alfabetizzazione-docenti
/esercizi/maxSemplice.py
129
3.703125
4
a = input('inserire a ') b = input('inserire b ') if (a > b): print 'a maggiore di b' if (b > a): print 'b maggiore a'
4c09b471e8659d835613639abe1c786ca9d48564
DavideMaspero/python-alfabetizzazione-docenti
/esercizi/functionsArgsKind.py
1,853
3.953125
4
# default argument values # definition: it is possible to assaign a default value to some parameters # (AFTER THE POSITIONALS ONES) def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok i...
af90d3755b1021b142b67ad95e730b8f52ba38aa
DavideMaspero/python-alfabetizzazione-docenti
/esercizi/if.py
106
3.5625
4
a = input("Inserire un numero intero a:\n") if a < 0: a = -a print "Il valore assoluto di a e' ", a
ba7f1a767538ad2dfa7a758930a83c80c7085e85
DavideMaspero/python-alfabetizzazione-docenti
/esercizi/primalita.py
689
4.09375
4
numero = input("inserire un numero intero positivo: ") primo = False contatore = 1 divisore = contatore * 2 + 1 while divisore <= numero: print "contatore ", contatore print "divisore ", divisore print "resto ", numero%divisore print "divisione", numero/divisore print numero%divisore == 0 print...
2c602e7c8e6f9862eda00e14c9959c2cb9d59336
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 1/Ex006 - operacoes.py
216
4.125
4
num = int(input('Digite um número inteiro: ')) dobro = num*2 triplo = num*3 raiz = num**(1/2) print('O dobro do número é {}, o triplo do número é {} e a raiz do número é {:.2f};'.format(dobro, triplo, raiz))
b67a6cf01324b2aadb667274281476d1d8144d85
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 3/06 - Funções - p2/Ex102 - Fatorial.py
489
3.890625
4
def fatorial(n, show=False): """ Calcula o fatorial de um número. :param n: O número que será feito o fatorial. :param show: Apresenta o cálculo ou não :return:o valor do fatorial. """ c = 1 for l in range(n, 0, -1): c = c*l if show: if l == 1: ...
6ace00e157783862c0e9c60984da537efa86cb7b
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 1/Ex008.py
371
3.859375
4
### convertendo valores met = float(input('Quantos metros você quer converter?')) km = met*(1/1000) hec = met*(1/100) deca = met*(1/10) met = met dec = met*10 cent = met*100 mili = met*1000 print('Os {} metros são {} milímetros, {} centímetros,' '\n {} decímetros, {} decâmetros, {} hetômetros e {} kilometros '....
a11e59a765703bff36652a66a332071d0ba9df35
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 3/05 - Funções - p1/Ex098 - Contando.py
1,055
3.6875
4
from time import sleep def contador(i, f, r): if i < f: if r > 0: for k in range(i, f+1, r): sleep(0.25) print(k, end=' ') else: for k in range(i, f+1, -r): sleep(0.25) print(k, end=' ') if f < i: if...
1957807513aa138bec412a1545ff2d1f4b4ba4d8
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 1/Ex013 - new wage.py
289
3.5625
4
# novo salário salario = float(input('A empresa está aumentando o salário dos funcionários, \n' 'em 15%, dessa forma, precisamos saber seu salário atual.\n')) salario_novo = salario*1.15 print('O seu novo salário será de {:.2f} reais.'.format(salario_novo))
c7eefb1f08a05a85e320466bcf62fce07522f2e1
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 3/01 - Tuplas/Ex077 - Vogais.py
530
3.703125
4
#vogais em aplavras print('Digite palavras sem acento ou pontuação.') pala1 = str(input('Digite uma palavra aleatória:')).strip().lower() pala2 = str(input('Digite uma palavra aleatória:')).strip().lower() pala3 = str(input('Digite uma palavra aleatória:')).strip().lower() tupla = (pala1, pala2, pala3) vogais = ('a', '...
3199745c9d39422425a740007f83d6e891f80031
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 1/Ex018 - trigonometria.py
356
3.953125
4
#### lendo um angulo qualquer import math angu = float(input('Digite um angulo qualquer, em graus: \n')) ang = math.radians(angu) print('Os graus digitados correspondem a {:.2f} radianos'.format(ang)) sen = math.sin(ang) cos = math.cos(ang) tg = math.tan(ang) print('Os graus digitados são em seno {}, cosseno {} e t...
080cadb27e20a0ed9463581c0db1ef4724d3d454
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 2/Ex057 - Corretamente.py
186
4
4
### leitura correta sexo = str(input('Qual o seu sexo?[M/F]\n')).strip().lower() while sexo!='f' and sexo!='m': sexo = str(input('Qual o seu sexo?[M/F]\n')) print('Está correto!')
9e641d338cf72647db394ed29d950f99a4badaa1
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 3/04 - Dicionários/Ex094 - people.py
1,515
3.703125
4
q = 0 pessoa = dict() people = list() somaidade = 0 mulheres = list() pessoaacima = list() while True: pessoa.clear() q = q + 1 pessoa['name'] = str(input(f'Digite o nome da {q}ª pessoa:')).strip().lower().capitalize() while True: pessoa['years old'] = int(input(f'Digite a idade da {q}ª pessoa:'...
8a40c2f37e572042d27f6dff7b663306ab579885
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 2/Ex045 - JO KEN PO.py
1,718
3.734375
4
#### jo KEN PO import random from time import sleep aceite = int(input('Olá, eu sou seu computador. Gostaria de jogar jokenpô?\n1 - Sim\n2 - Não\n')) escolhapc = random.choice([1, 2, 3]) if aceite == 1: escolhahumano = int(input("""Escolha uma das opções: 1 - Pedra 2 - Papel 3 - Tesoura \n""")) if escol...
72279874ee3d72540d8b5be30d39ccc47e579227
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 3/01 - Tuplas/Ex073 - brasileirão.py
618
3.515625
4
# tabela do brasileirão - inventarei uma tabela obs:brasileiro nao começou tupla = ('grêmio', 'flamengo', 'vasco', 'internacional', 'chapecoense', 'fluminense', 'avai', 'athletico', 'atletico', 'palmeiras', 'são paulo', 'corinthians', 'santos', 'botafogo', 'bahia', 'ceara', 'ponte preta', 'juventude','guarani', 'cruzei...
46376015c5a7c9d3b2b2da4b686e809db1591a3a
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 1/Ex012 - new price.py
221
3.578125
4
# Calculadora de desconto preco = float(input('Qual o preço do produto?\n')) novo_preco = preco*0.95 print('Levando-se em consideração 5% de desconto\n' 'o novo preõ será de {:.2f} reais.'.format(novo_preco))
469ad8416a32b02a7cd806a95a2c2738bd0ba6be
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 3/02 - Listas - p1/Ex078 - v2.py
357
3.515625
4
c = 0 l = [] for c in range(0, 5): n = int(input(f'Digite o {c + 1}º valor, sem repetir:')) while n in l: n = int(input(f'Digite o {c+1}º valor, sem repetir:')) l.append(n) n = ' ' print(f'O maior valor foi o {max(l)} na {l.index(max(l))+1}ª posição.\n' f'O menor valor foi o {min(l)} na {l...
ec8aeb14483945f77dca0dd7b7133c2c16cff418
Karran8458/Values-Greater-Than-Second
/Values Greater Than Second.py
188
3.96875
4
def values_greater_than_second(arr): arr2 = [ ] if len(arr) < 3: return false for x in range(0,len(arr),1): if arr[x] > arr[1]: arr2.append(arr[x]) print(len(arr2)) return arr2
c00f2b8f1e2b7d5db631c18fe0005e35f5cb1b91
camera510PC7/codeiq_answer
/no_progress.py
338
3.578125
4
# -*- coding: utf-8 -*- value=input() if value%2==0: print"invalid" elif value==1: print "n" else: n='n' d='.' nf=0 for i in range(value): if i<1 or i>=value-1: nf=0 else: nf=1 print 'n'+d*(i-1)+n*nf+d*(value-i-2...
13a5ee46b9ea315b1aea6400754c17391a6561aa
CodecoolMSC2016/python-game-statistics-3rd-si-oONinaOo
/part2/reports.py
4,413
3.71875
4
# What is the title of the most played game? def get_most_played(file_name): games_list = [] with open(file_name, "r") as my_file: for lines in my_file: games_list.append(lines.strip().split("\t")) # list of all by title and popularity most_played = [] for i in range(len(games_li...
a76e9c4a69e9993ed9b5e290ca9aa1b6077448cf
crhmhealey/2018_ClassDemos
/c block demos/factorial.py
1,200
3.953125
4
def factorial(n): if n is 0 or n is 1: return 1 return factorial(n-1)*n print(factorial(5)) print(factorial(4)) print(factorial(3)) print(factorial(2)) print(factorial(1)) print(factorial(0)) # evil fib but interesting for recursion def fib(n): if n is 0 or n is 1: return n return fib(n-1)+fib(n-2) print(fib...
9cce81610a18cf89b0469db1cf756e3447977f7f
crhmhealey/2018_ClassDemos
/Deck of Cards/card.py
684
3.9375
4
# card class represents a single card in a deck class Card: # card class keeps track of rank and suit for a single card def __init__(self, rank, suit): self.rank = rank self.suit = suit # print out the rank and suit in a nice way for the card # rank is stored as a number, but will display as a word here def ...
80aee09b4007aeffde77cd8094eed571a2088ed7
crhmhealey/2018_ClassDemos
/g block demos/demo_game.py
1,103
4.03125
4
def lake(): choice = input('You are sitting on the lake, enjoying your picnic, when the water starts stirring and bubbling. Do you run [r] to the mountains for safety, or stand [s] your ground and prepare to fight? ') if check(choice,'r','s') == 'r': print('You decide to flee to the mountain for safety. ') mount...
ec951fa06ca117a254e2dc83eba1483801ab4958
crhmhealey/2018_ClassDemos
/c block demos/lists_revisited.py
263
3.875
4
apples = [] for orange in range(5): apples.append(orange) i = [x for x in range(5)] i = [[1,2,3],[4,5,6],[7,8,9]] i[1][0] i = [0 for x in range(12)] print(i) j = [0]*12 print(j) i = [[0]*10 for x in range(10)] print(i) for x in range(len(i)): print(*i[x])
de007536891581b70c55725f97b33bc8df2d1ce6
crhmhealey/2018_ClassDemos
/g block demos/Bank.py
973
3.546875
4
import random class Account: def __init__(self, amount, pin): self.balance = amount self.pin = pin self.account = random.randint(10000000,99999999) self.isOpen = True def close(self, pin): if self.pin == pin: isOpen = False money = self.balance self.balance = 0 return money else: return p...
5a699fabe189e8453a4ba1b7a3db892255042771
crhmhealey/2018_ClassDemos
/c block demos/dog_class_demo.py
1,084
3.9375
4
class Dog: # constructor def __init__(self, energy, name): self.energy = energy self.hunger = 5 self.weight = 30 self.happiness = 5 self.name = name #------------------------------ # methods - functions #------------------------------ # allows the dog to eat some food def eat(self): status = "" i...
bd1eee9df1c0a3dba011e36ed0c293e7a2225e1f
09Susinthan08/guvi
/digitcount.py
89
3.640625
4
num=int(input()) count=0 while num>0: num=int(num/10) count=count+1 print(count)
3fe5251b4cd5884f4adaba9a5cb954c92baeed0b
09Susinthan08/guvi
/extract_num.py
127
3.859375
4
s=input() li=[] for i in s: if(i.isnumeric()): li.append(i) else: continue for i in range(len(li)): print(li[i],end="")
675dec9cd96b305c2647a43b2143010340e7ec85
09Susinthan08/guvi
/sumarr.py
72
3.515625
4
num=int(raw_input()) su=0 for i in range(0,num+1): su = su+f print(su)
6cc5d5847c780a73f3b4e4c6534cd1036a3427b5
09Susinthan08/guvi
/word_split.py
248
3.546875
4
s=input() li=[] li1=[] for i in range(len(s)): if(i%2==0): li.append(s[i]) else: li1.append(s[i]) for i in range(len(li)): if(i==len(li)-1): print(li[i],end=" ") else: print(li[i],end="") for i in range(len(li1)): print(li1[i],end="")
57a9ed5a42dfc9c95e8abc9250bee77a20f7e274
protossw512/Deep-learning-projects
/MLP_Skeleton_d_minibatch.py
9,655
3.59375
4
""" Xinyao Wang """ from __future__ import division from __future__ import print_function import sys import cPickle import numpy as np # np.random.seed(321) # This is a class for a LinearTransform layer which takes an input class LinearTransform(object): def __init__(self, W): # DEFINE __init funct...
5d87a628b94927bab71349d685783154e819e912
praveengadiyaram369/LearningPython
/Basic_Python_Programming/Sequences_Tuples_Sets_Basics.py
686
4
4
####### Tuples ####### tuple_1 = ('A', 'AB', 'ABCD', 'EUIHVEAO') print(tuple_1) tuple_2 = tuple_1 print(tuple_2) ####### Empty Tuple ######### empty_tuple = tuple() empty_tuple = () #tuple_1[0] = 'WUI' #print(tuple_1) #tuple_2[0] = 'WUI' #print(tuple_2) ######### Set ###### subject_set = {'Maths', 'Physics', 'Ch...
83bcc918ad14403337b92d9a96fb5f9f846033f9
mdudapinho/Seguranca-de-Redes
/Trabalho 5/hash.py
640
3.53125
4
import hashlib hash_file = "hash_file.txt" this_file = "server.py" CREATENEWHASH = False USEHASH = False def md5Hash(text): result = hashlib.md5(text.encode("utf-8")).hexdigest() return result[:16] def checkApplicationIntegrity(): if(USEHASH): fh = open(hash_file).read() th = open(this_fil...
6bfce60110b0b09bf5ba10f77b491e1d194c15a9
harishpichukala/tesseract-based-text-to-braille
/convert_num.py
563
3.75
4
def convert(text): temp=text out=[] for i in temp: if '1'==i: j="@a" out.append(j) elif '2'==i: j="@b" out.append(j) elif '3'==i: j="@c" out.append(j) elif '4'==i: j="@d" out.append(j) elif '5'==i: j="@e" out.append(j) elif '6'==i: j="@f" out.append(j) elif '7'==i: ...
fa55764c1e7a96b334fde53f5ae89200a8160793
Planet-Nine/cs207project
/timeseries/timeseries.py
11,476
3.953125
4
import numpy as np from pytest import raises import pype import numbers def f(a): return a class LazyOperation(): """ An class that takes a function and an arbitrary number of positional arguments or keyword arguments as input Parameters ---------- function : an arbitrary function ...
6b550237b3a3516a689a79adf7b34825314dd2d6
mattthewong/cs_5_green
/lengthToATG.py
619
3.578125
4
import random def lengthToATG(): counter = 0 newcontainer = "" while counter <=3 or newcontainer[counter-4:counter-1] != "ATG": newcontainer += random.choice(['A','T','C','G']) counter = counter + 1 return counter def meanToATG(trials): newcounter = 0 newcontainer = "" while ...
7af649c957548e185780ad58824ea7ab16eb198b
mattthewong/cs_5_green
/count.py
171
3.890625
4
def count(letter, string): counter = 0 for symbol in string: if letter == symbol: counter = counter+1 return counter
fe74281880b4219344591d6f7e8b1dc974969565
mattthewong/cs_5_green
/hw10/Ant.py
2,671
4.6875
5
from Vector import * import random import turtle class Ant: def __init__(self, position): '''This is the "constructor" for the class. The user specifies a position of the ant which is a Vector. The ant keeps that vector as its position. In addition, the ant chooses a random color for its fo...
88a542ae63daee452e566099abf61e367326d0ea
mattthewong/cs_5_green
/hw1bonus.py
296
3.90625
4
def palindrome(input): if input == input[::-1]: return True else: return False def fancyPal(string): lowerstring = string.lower() for value in lowerstring: if value == ',' or value == ' ' or value == '.':
0f6ba572e53dc34067241b53aa7d65c72f4e1462
Mauricio1xtra/python
/basic_revisions2.py
2,903
4.125
4
""" Formatando valores com modificadores - AUlA 5 :s - Texto (strings) :d - Inteiro (int) :f - Números de ponto flutuante (float) :.(NÚMERO)f - Quantidade de casas decimais (float) :CARACTERE) (> ou < ou ^) (QUANTIDADE) (TIPO - s, d ou f) > - Esquerda < - Direita ^ - Centro """ """ num_1 = 1 print(f"{num_1:0>10}") ...
08f92f268f365273ba0eeecfa7ea637599cd126e
FigNewtons/hackerrank
/warmup/CountingValleys.py
447
3.875
4
def counting_valleys(s: str) -> int: valley_count = 0 level = 0 in_valley = False for ch in s: if ch == 'D': if level == 0: in_valley = True level -= 1 else: level += 1 if level == 0 and in_valley: in_valley = Fal...
f74423128c8fcacbf42426d5a6d8061ad747d706
lyubomirShoylev/pythonBook
/Chapter04/ex08_herosInventory2.py
1,292
4.1875
4
# Hero's Inventory 2.0 # Demonstrates tuples # create a tuple with some items and display with a for loop inventory = ("sword", "armor", "shield", "healing potion") print("\nYour items:") for item in inventory: print(item) input("\nPress the enter key to exit.") # get the l...
9eaf4fbd375f2f10554b93b64cddd7f6f0e8d334
lyubomirShoylev/pythonBook
/Chapter06/ch02_guessMyNumberModified.py
1,848
4.21875
4
# Guess My Number # **MODIFIED** # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money. In this version of the game # the player has limited amount of turns. # # MODIFICATION: # Reusing t...
cd8e55a1d45d6c3375e5747fb57f4d83ff92f103
lyubomirShoylev/pythonBook
/Chapter09/ch02_war/war.py
4,906
3.609375
4
# War Game # # A one-card version of the game war, based on modules 'cards' and 'games' as in # example code from the book. import games, cards class WarCard(cards.Card): """A War Card.""" ACE_VALUE = 14 @property def value(self): if self.isFaceUp: v = self.RANKS.index(self.r...
e550fd073b917dafc66ff71ee3455053617cd920
lyubomirShoylev/pythonBook
/Chapter04/ex05_noVowels.py
445
4.53125
5
# No Vowels # Demonstrates creating new strings with a for loop message = input("Enter a message: ") newMessage = "" VOWELS = "aeiou" print() for letter in message: # letter.lower() assures it could be from VOWELS if letter.lower() not in VOWELS: newMessage += letter print("A new string has be...
5f7c7c5018f3db3c93c1cb1dcc4fe731c06cee2d
ARM-software/ML-examples
/yeah-world/randomsound.py
1,727
3.5625
4
#!/usr/bin/python # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
85a40eed93bd27097008e98354632806036e426e
veteransgroup/leetcode
/leetcode/3Sum.py
1,849
3.9375
4
from collections import Counter def speedup(numbers): """ list 里任意三个数相加为0 Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Args: numbers (list): 一个全部元素为整数的list Returns: ...
98af62cdddb028c83bfbf05f2f53c56dd7a7171b
matheusdelimasilva/ChronicKidneyDisorderDiagnostic
/NN_KNN_functions.py
7,345
3.921875
4
# Machine Learning Project - Functions for Step 2 and 3 # ***************************************** # COLLABORATION STATEMENT: # https://www.w3schools.com/ # https://numpy.org/ # https://www.askpython.com/python/array/python-add-elements-to-an-array # ***************************************** #Import statements import...
300702830b8f8c6e092c6068a667fa61bd69d84c
iiibsceprana/pranavsai
/functions/funtest2.py
153
3.6875
4
def reassign(list): list = [0,1,9,8,7] print(list) def append(list): list.append(-5) print(list) list=[4] reassign(list) append(list)
14d3fd4767b746e8fe459695f66ec523201bd95a
iiibsceprana/pranavsai
/pranav/iterators.py
248
3.703125
4
#Geneartor def squares(start, stop): for i in range(start, stop): print(i*i,end=" ") Iterator = squares(1, 10) #print(Iterator) Iterator1=squares(11,20) i=range(10) print(i) for l in i: print(l) for l in i: print(l)
bcb1b9acfea3e0eb1714788eee2c42d9ddb9d694
LeeroyC710/pj
/Desktop/py/YuyoITGradingSystem2.py
2,203
4.1875
4
def grading(num): #Grades the grades if num >=99: return "U. No way you could have gotten that without cheating. (A****)" elif num >=94: return "S-Class Hero ranking. All might would be proud." elif num >= 87: return "A**. Either a prodigy or a cheater." elif num >= 79: r...
b3c8b2390a7d72e0976953785881c3b3471294ed
geosun61/CS50Projects
/geosun61-web50-projects-2020-x-1/sql/list.py
959
3.671875
4
import os from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker engine = create_engine(os.getenv("DATABASE_URL")) # database engine object from SQLAlchemy that manages connections to the database # DATABASE_URL is an environmen...
d7a3cb208bba848829312fec5f9542f4f8952ee8
geosun61/CS50Projects
/geosun61-web50-projects-2020-x-1/sql/import.py
1,266
3.609375
4
import os import csv from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker engine = create_engine(os.getenv("DATABASE_URL")) # database engine object from SQLAlchemy that manages connections to the database # DATABASE_URL is an...
deb4768dc86b14721ab971c668cd1108e10e68fc
dmoini/python
/tile_cover_cost.py
306
4.03125
4
def ask(): width = int(input("What is the width of each tile? ")) length = int(input("What is the length of each tile? ")) cost = int(input("What is the cost of each tile? ")) return width, length, cost def cost(): width, length, cost = ask() print(width * length * cost) cost()
f5d40426005cb11f4d9170a0d9ccd2ae0ecb1c16
PetrJanousek/Neurogenetic_algorithm
/mutation_funcs.py
1,343
3.890625
4
# Mutation helper functions: import random import numpy as np def swap_weights(array): """ Given the matrix of weights of the neural network, it mutates it. Chooses randomly how how many columns and which ones will be swapped. Then it swaps the positions of the weights columns. array : np.ndarray ...
dd61435d53cd3d5c36a69148d79a7efd06aa726f
meixingdg/course-prereq
/misc/datastoreBuilder/tsvBuilder.py
2,453
3.703125
4
import json import urllib # We keep global variables to store the YACS API's urls. yacs_url = "http://yacs.me/api/4/" yacs_deps_url = yacs_url + "departments/" yacs_courses_url = yacs_url + "courses/" def get_deps(): """Get a json of departments from YACS.""" response = urllib.urlopen(yacs_deps_url) ...
1c2e851481cd1b777079e28833c71e84dbe81368
Maor2871/DogsBeach
/Server/threads/Client communicator/User.py
1,692
3.625
4
# -*- coding: utf-8 -*- import threading import random class User(): """ The class represent a user that has connected to the program and use it right now. """ random_id_numbers = [] def __init__(self, general, socket): """Constructor. The function receives general, socket ...
6373c1db4bfd90b91593bc90c957c0d98feda180
haiyaoxliu/old
/stuyvesant intro class/brooks and pclassic/raw input.py
250
3.765625
4
def get(): while True: c = raw_input('input name? (Y/N)') if c == 'Y' or c == 'y': n = raw_input('name:') elif c == 'N' or c == 'n': break else: print('Error') break
2d3665446a721820d23752ce7ca92e6f44bed8fe
haiyaoxliu/old
/stuyvesant intro class/brooks and pclassic/test56.py
628
3.953125
4
# Problem 5: def replaceAll(astring,lookfor,replaceWith): rstring = "" while astring.find(lookfor) != -1: rstring = rstring + astring[:astring.find(lookfor)] + replaceWith astring = astring[astring.find(lookfor) + len(lookfor):] rstring = rstring + astring return rstring # Test results: ...
5e4a0022d4dbe3ce97ae4e8345f031106b7fdb1f
IvanCaballero1204/Actividad_3
/main.py
668
4.03125
4
#!/usr/bin/env python3 from math import pi import areas def main(): print("Hola mundo") nombre = input("¿Cual es tu nombre? ") print("Hola {}".format(nombre)) edad = int(input("¿Cuántos años tienes? ")) print("{} tienes {} años y en un año tendrás {} años".format(nombre, edad, edad + 1)) area_t...
d9dbb2999d18d9d3eed3a6d5391a99ea17554842
panipinaka/FML
/Linear_regression.py
1,247
3.8125
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 5 09:01:27 2019 @author: Pinaka Pani """ #import libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt #importing the dataset dataset = pd.read_csv("Salary_Data.csv") X = dataset.iloc[:,:-1].values y = dataset.iloc[:,1].values ##spliting th...
ad882f87d72023e54a7e3b8997a170d15032e48f
meghasn/study_grp_practice
/leaf_similar_tree.py
994
3.875
4
# // Time Complexity :O(n) # // Space Complexity :O(h) # // Did this code successfully run on Leetcode :yes # // Any problem you faced while coding this :no # // Your code here along with comments explaining your approach # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=N...
fb2b2ae876479abe029ef5db6f0e854442511b4c
windmill312/compilers
/python-compiler/src/main/java/com/windmill312/samples/listInversion.py
160
3.515625
4
list = [1,2,3,4,5] nnCnt = 2 for i in range(0, nnCnt): temp = list[len(list) - 1 - i] list[len(list) - 1 - i] = list[i] list[i] = temp print(list)
e74ab7f678eb535ee17cbe4cae7e22a835038407
imranasq/DataStructPy
/brickPyramid.py
336
3.96875
4
blocks = int(input("Enter the number of blocks: ")) height = 0 sum = 0 if blocks == 0: print("The height of the pyramid:", height) else: for i in range(1, blocks): sum = sum + i if sum <= blocks: height = height+1 else: break print("The height of the pyr...
96816dff40bd38767a7fb5ed41c40171bb84304e
imranasq/DataStructPy
/Array/matrix.py
338
3.890625
4
from numpy import * matrix1 = matrix('3, 24, 5; 24, 6, 2 ; 4, 5, 76') matrix2 = matrix('4, 3, 4 ; 24, 5, 1; 6, 67, 2') matrix3 = matrix1 + matrix2 matrix4 = matrix1 * matrix2 #for multiplication it should be 1st matrix row = 2nd matrix column. print("Sum of the matrices: ", matrix3) print("Multiplication of the matr...
70f8f903d61d69a2664cd978a1fad2abd2d0c94f
MeSrinathReddy/nltk-examples
/src/book/ch06.py
9,819
3.65625
4
#!/usr/bin/python # Text classification from __future__ import division import nltk from nltk.classify import apply_features import random import math def _gender_features(word): features = {} # started with 1 feature features["last_letter"] = word[-1].lower() # added some more features["first_letter"] = wo...
124cee9a7367047f0fed2037b3997df4cfaf9399
Kamil-Ru/Functions_and_Methods_Homework
/Homework_7.py
1,384
4.46875
4
# Hard: # Write a Python function to check whether a string is pangram or not. (Assume the string passed in does not have any punctuation) # Note : Pangrams are words or sentences containing every letter of the alphabet at least once. # For example : "The quick brown fox jumps over the lazy dog" # Hint: You may want t...
f4e2b611a1ee76f58dbe1a4bc56d96b9491d7a95
emg110/LearningGameStructure
/MCTS/snake_player.py
906
3.609375
4
import game from snake_action import * class SnakePlayer(game.HumanPlayer): """ Human player that plays Snake. """ def choose_action(self, board): next_dir = self.source() # returns 0,1,2,3,4, representing the direction the person wants to go color = board.turn curr_dir = boar...
00e9cd084d8b464fda0560b1e24e93290af4099c
ptkang/python-advanced
/chapter06/s04_set_frozenset.py
801
4.03125
4
# set集合, frozenset(不可变集合) 无需,不重复 # set实际顺序和我们添加的顺序不一样 # set接收一个iterable对象 # set性能很高,时间复杂度为O(1) s = set('abcdee') print(s) s = set(['a', 'b', 'c', 'd', 'e']) print(s) s = {'a', 'b', 'c', 'd', 'e'} print(s) s.add('f') print(s) # frozenset不可变集合使得其可以作为dict的key s = frozenset('abcdee') print(s) # update,将两个集合合并 s = set('ab...
fc05708df40a3f5a691e39484a629d50863e27d0
ptkang/python-advanced
/chapter04/class_var_4_4.py
573
4.0625
4
# 类变量和实例变量 class A: # 类变量 aa = 1 def __init__(self, x, y): # self是类的实例 # x, y 前面加self,即为实例变量 self.x = x self.y = y a = A(2, 3) # a.aa能访问是因为a先查找自身实例变量aa,若没找到,则向上在所在类里面查找类变量aa print(a.x, a.y, a.aa, A.aa) # 类变量必须通过类名.变量名来修改 A.aa = 11 # a.aa = 255 实质为动态的给实例a增加了实例变量aa a.aa = 255 ...
eec1b219bf01cb69e8d813cd2cc0ede7a1d43cb2
schana/random-hacking
/mod_pow.py
1,041
4.09375
4
''' This computes the result of (base ^ exponent) % modulus for large numbers with both an iterative and recursive solution. Time complexity is O(logN) where N is the exponent. ''' def power_mod(base, exponent, modulus): result = 1 base = base % modulus while exponent > 0: if exponent % 2 == 1: ...
a44b05ffd053712ead4334cfdcb03527bae47098
CKubinec/NHLAnalytics
/main.py
4,593
3.515625
4
import requests import json from Forward import Forward from Goalie import Goalie def write_to_file(player_array, name_of_role): """Writes all data to 3 separate files, 1 for Forwards (`forwards.txt`), 1 for Defencemen (`defenceman.txt`), and 1 for Goalies (`goalies.txt`)""" # Sorts the arrays by ...
3d6307db27e1682c31ed948cae246e6075a7c6da
dstanfield/adventcode2020
/day1/day1.py
565
3.8125
4
import csv valuesString = [] with open('input.csv', 'r') as fd: reader = csv.reader(fd) for row in reader: valuesString.append(row[0]) values = [int(numeric_string) for numeric_string in valuesString] print (values) for year in values: for secondyear in values: for thirdyear in values: ...
7242e72be2fc01a2d79bc2fbd565801072750e65
muhammed94munshid/codekatta-hunter-
/h03.py
190
3.515625
4
n=int(input()) l=[] for i in range (1,n+1): a=int(input()) l.append(a) print (l) m=[] for idx,val in enumerate(l): b=idx,val m.append(b) print(m) for x in m:
df1de6d59515d454f05524238460a4f76e77b99b
MatiwsxD/ayed-2019-1
/Labinfo_7/D -Left Rotation.py
317
3.625
4
from sys import stdin def rotation(lista,y): if y == 0: return lista else: x =lista[0] lista = lista[1:] z = lista+[x] return rotation(z,y-1) def main(): x = [int(x) for x in stdin.readline().strip(" ").split()] y = int(input()) print(rotation(x,y)) main()
6058618fbbf2007c45b019d103bb2ba2a34609d6
MatiwsxD/ayed-2019-1
/Labinfo_4/punto_2.py
468
3.546875
4
from sys import stdin def parejas(x): lista = [] for i in x: for j in range(len(x)): if i[0] == x[j][0] or i[0] == x[j][1] or x[1] == x[j][0] or x[1] == x[j][1] and i != x[j]: lista += x[j] return lista def main(): lista_1 = [] x = int(input()) ...