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
dfcfd8af291ddcc3cfc38f7725d35ba516318685
sagarkamthane/Code-with-harry
/OOP/practice1/pr3_complex.py
837
3.71875
4
#(a+bi)+(c+di) = (a+c) + (b+d)i #(a+bi)(c+di) = (ac-db) + (ad + bc)i class Complex: def __init__(self, r, i): self.real = r self.imaginary = i def __add__(c1, c2): real = c1.real + c2.real imaginary = c1.imaginary + c2.imaginary return Complex(real, imaginary) def...
f7ee3dee862cb613c56ae7506bb3d73618c3f55b
sagarkamthane/Code-with-harry
/OOP/employee.py
463
3.75
4
class Employee: company = "Google" salary = "10000" harry = Employee() sagar = Employee() print(harry.company) print(sagar.company) Employee.company = 'Vuclip' print(harry.company) print(sagar.company) print(sagar.salary) #before creating object instance sagar.salary = "15000" print(sagar.salary) #...
977560bdf5ffc1d477f0169e16924ae7f4871cd1
Argonnite/minimum_value_path
/minimum_value_path.py
1,660
3.9375
4
''' Return root-to-leaf path containing minimum. Ties broken by next minimum, and so on. Ex. 3 / \ 4 9 \ | \ 6 5 1 / / \ 1 8 4 / \ 2 3 Return: 3, 9, 5, 1, 2 ''' class BinaryTreeNode(object): def __init__(self, value): self.left = None self.right = None se...
2b972dac19caea9d0810ea8cc19df3927f29c119
alikayhan/udacity-pfwp
/check_profanity.py
706
3.65625
4
#!/usr/bin/env python3 __author__ = 'alikayhan' import urllib.request quotes_list = "" def read_text(): file = open(input("Enter the path of the text file to be checked for profanity: ")) quotes_list = file.read() return quotes_list file.close() def check_profanity(word_to_check): connection = ...
728c57a99d958e46071a42d3739aeb13a246fd8f
Boellis/PatRpi3
/IndividualStock.py
1,460
3.703125
4
from urllib.request import urlopen from bs4 import BeautifulSoup from googlesearch import search def findStock(StockName): #Ask what stock #StockName = input('Enter the name of the stock you want information for: ') #Specify this input is a stock that exists on the nasdaq and format the input StockPag...
9f9c4fc6073722f544c9fb78a86b66e67b3d374b
feoh/AdventOfCode2018
/day2.py
652
3.6875
4
from collections import Counter from pprint import pprint def check2(counts): return 2 in counts.values() def check3(counts): return 3 in counts.values() counts = [] hastwo = 0 hasthree = 0 with open("day2-input","r") as day2_input: lines = day2_input.readlines() lines = [x.strip() for x in lines] ...
b3db57f766c7f56cdad5c4d97f1fc8674de12102
sujoyroyskr/Introduction-To-Tkinter
/Tkinter13.py
1,039
4.03125
4
from tkinter import * from tkinter import ttk root = Tk() ## ------- Event Binding -----------## ## ------- This Function Mainly Creates an entry event --------- ## entry = ttk.Entry(root) entry.pack() entry.bind('<<Copy>>', lambda e: print('copy')) ## This function is for Copy Event. entry.bind('<<Past...
db2d589f40736c1c279e35cdd852471edf82ff7e
sarahheacock/thinkpython
/palindrome.py
352
3.9375
4
def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1:-1] def is_palindrome(word): temp = word while len(temp) > 0: if last(temp) != first(temp): return False temp = middle(temp) return True print(is_palindrome('racecar'...
20b46bb9dc738641b36c740428696ca652dbd835
sppapalkar/hungarian-globe-solver
/src/util.py
1,289
3.78125
4
#imports # Checks if state 1 and state 2 coordinates are equal def is_equals(state1,state2): for i in range(0,30): if state1[i] != state2[i]: return False return True #-----------------------------------------------------------------------------# #Convert final path notation to actual pat...
1d79865e5d1a2ce727eff4c55c8ddd8cd22dee65
liyaozr/project
/base/day6/02while的使用.py
1,598
4.21875
4
""" ============================ Author:柠檬班-木森 Time:2020/1/6 20:47 E-mail:3247119728@qq.com Company:湖南零檬信息技术有限公司 ============================ """ """ 需求:打印100白hello python """ # 定义一个变量来计数,记录打印了多少遍hello python i = 0 while i < 100: i = i + 1 print("这是第{}遍打印:hello python".format(i)) # ----------------------...
c4f454c105ce7d8116a2effff755c4ecfa025635
liyaozr/project
/base/day7/06函数的函数.py
1,170
3.59375
4
""" ============================ Author:柠檬班-木森 Time:2020/1/8 21:50 E-mail:3247119728@qq.com Company:湖南零檬信息技术有限公司 ============================ """ """ 函数的参数 形参:在定义函数的时候,定义的参数,叫形式(形式上的参数,并没确定值是多少) 形参是用来接收实参传递的值的。 1、必需参数(必备参数) 2、默认参数(缺省参数) 3、不定长参数(动态参数) 实参:在调用函数的时候,传入进行的参数,叫实参(实际的参数) 1、按位置顺序进行传递,这种传参...
0e28c1497632cd5e1879ae3d3ec72e14e877bd16
liyaozr/project
/base/day6/05for循环使用小案例.py
1,497
3.828125
4
""" ============================ Author:柠檬班-木森 Time:2020/1/6 21:30 E-mail:3247119728@qq.com Company:湖南零檬信息技术有限公司 ============================ """ """ 需求:1、计算1+2+3+4+。。。。100的结果 内置函数range: range(n):默认生成一个 0到n-1的整数序列,对于这个整数序列,我们可以通过list()函数转化为列表类型的数据。 range(n,m):默认生成一个n到m-1的整数序列,对于这个整数序列,我们可以通过list()函数转化为列表类型的数据。 r...
636361577018836296a8a8ba2b2a7c267ffffe96
optionalg/cracking_the_coding_interview
/chapter03_stacks_queues/04_queue_via_stack.py
378
3.671875
4
from ctci.chapter03_stacks_queues.Stack import Stack class MyQueue: def __init__(self): self.in_stack = Stack() self.out_stack = Stack() def push(self, value): self.in_stack.push(value) def pop(self): while self.in_stack.is_empty() is False: self.out_stack.push...
967f35fdb9d42f9e89255eb1b2fa4196e48cd0d2
optionalg/cracking_the_coding_interview
/chapter03_stacks_queues/02_stack_min.py
1,743
3.96875
4
class Node: def __init__(self, value): self.data = value self.next = None class Stack: def __init__(self): self.head = None self.min = [] def print(self): if self.head: tmp = self.head while tmp: print(tmp.data, " -> ", end=""...
3d11c1f4001a9d98b90a9b80baf9a71a5db5f615
optionalg/cracking_the_coding_interview
/chapter02_lists/LinkedList.py
2,237
3.6875
4
from random import randint class Node: def __init__(self, value, next=None): self.data = value self.next = next class LinkedList: def __init__(self): self.head = None def print_list(self): tmp = self.head while tmp is not None: print(tmp.data, " -> ", e...
ee1f838de3652e533b1600bce3fa33f59ad8d26d
Yasune/Python-Review
/Files.py
665
4.28125
4
#Opening and writing files with python #Files are objects form the class _io.TEXTIOWRAPPER #Opening and reading a file myfile=open('faketext.txt','r') #opening options : #'r' ouverture en lecture #'w' ouverture en ecriture #'a' ouverture en mode append #'b' ouverture en mode binaire print type(myfile) content=myfile...
54efa1c6c967cd07fb4d55f1555c023c845a4ad7
Yasune/Python-Review
/PandaSeries.py
868
3.625
4
#Serie Manipulation with Panda import numpy as np import pandas as pd print('====== Series======') s=pd.Series(([1, 2, 5, 7])) print s print type(s) s=pd.Series([1.3, 2, 5.3, 7]) print(s) print type(s) s = pd.Categorical(['a', 'b', 'a', 'b', 'b'], categories = ['a', 'b']) print type(s) print s #Exemple score of play...
64e8753317723d3317d3f206e1d7643794282dc5
maybexss/pythonstudy
/day003/list&tuple.py
1,096
3.765625
4
str = "python内置的一种数据类型是列表:list。它是一种有序的集合,可以随时添加和删除一种的元素。" print(str) classmates = ['maybexss', 'bluer', 'xuxi'] print(classmates) print('length of clasmates : ', len(classmates)) print('second element is : ', classmates[1]) print('倒数第一个元素是:',classmates[-1]) print('插入一个元素到第三元素中') classmates.insert(2, 'love you') print(c...
1faad174fe19897543c35fca8d04fa536539cdfc
castellanosr/CS280F2017-castellanosr
/CS280F2017-castellanosr/duplicates/tests/test_duplicates.py
456
3.71875
4
"""Test suite for the duplicates.py module""" import pytest import duplicates def test_duplicates_removed(): """Run the duplicate remove and see that the list gets smaller """ list_one = [1, 2, 3, 4] list_two = [1, 2, 5, 6] duplicates.remove_duplicates(list_one, list_two) assert list_one != list_...
8351570644f2d8d20ecda3f4b94f4eda0b41c576
kimeunyoung01/pythonTest
/day0420/ex09.py
1,798
3.796875
4
a = 10,20,30 print(a) i, j, k = a print(i) print(j) print(k) #연습) N을 매개변수로 전달받아 1~N까지합, N의 제곱, N*2를 차례로 반환하는 # 함수를 정의하고 호출해 봅니다. # def multi(n): # tot = 0 # for i in range(1, n+1,1): # tot = tot + i # return tot, n*n, n*2 # # r = multi(5) # # r = 15,25,10 # print(r)...
688c1740371fdc204941281724563f4c813b2ab7
Introduction-to-Programming-OSOWSKI/2-9-factorial-beccakosey22
/main.py
208
4.21875
4
#Create a function called factorial() that returns the factorial of a given variable x. def factorial(x): y = 1 for i in range (1, x + 1): y = y*i return y print(factorial(5))
97b4644edae1fadc8976a4881f786b53ec5337bc
Nanguage/seq_interval
/seq_interval/interval.py
8,471
4.40625
4
class Interval: """ The abstraction of interval with direction. example interval: |------------> direction: + start end <------------| direction: - end start >>> Interval(1, 10) Interval: 1 |-----> 10 >>> Interval...
1895f022d457aa3184c76c1f015fe0c8657951d8
manvelh/ImageCurator
/main.py
1,319
3.625
4
#THIS PROGRAMS TAKES AN IMAGE AND COMPUTES #AN IMAGE PROCESS BASED ON THE ARGUMENT TAG. #USE -B TO CHECK FOR BLUR #USE -S TO CHECK FOR SKEW #THE LAPLACIAN VARIANCE WHICH IS THE INDICATOR #OF A BLURRY IMAGE. IT ALSO COMPUTES THE HISTOGRAM #SKEWNESS WHICH IS AN INDICATOR OF HOW EXPOSED AN #IMAGE IS. # #author: Manvel B...
9b376cfa582abbeb92db6dc266e0cd7cfd9043cf
mt21667/Twowaits
/Twoc_1.py
1,633
4.03125
4
''' 1st question''' Name=input("Enter your name\n") Branch=input("Enter your branch\n") Gender=input("Enter your Gender\n") College=input("Enter your College\n") Age=input("Enter your Age\n") print("My name is",Name,"\n""My age is",Age,"\nI am a student of",College) '''2nd question''' import numpy as np def ...
15fa583f2d302348641cd76684292ccc1862641f
adinatkt/Sikli
/sikli2.py
858
4.0625
4
'''names = ('Максат','Лязат','Данияр','Айбек','Атай','Салават','Адинай','Жоомарт','Алымбек','Эрмек','Дастан','Бекмамат','Аслан',) i = 2 while i < 12: print(names) i+=2 ''' a = int(input("введите число") while a <= 100: if (a > 100) and (a < 1000): print("это число трёхзначное") else: ...
43495010506932c7369591602e35365d4b359b17
halovivek/100dayscoding1
/magicball.py
361
3.53125
4
import random message = ['it is certain', 'it is fine', 'this is correct', 'am i right to do', 'this is good to go', 'i am good at this', ' i am that i am ', 'what is your thought in your min', 'what is the use of this'] print(mess...
3b4cef3b0b4d49c0a0ad313ac8cddf17f0710340
emanoelmlsilva/ExePythonBR
/Exe.Lista/EL.02.py
280
3.78125
4
v=[] quant = int(input('Informe a quantidade de numeros: ')) for c in range(quant): num = int(input('Digite o {} valor: '.format(c+1))) v.append(num) #l1+=[num] #l1.extend([num]) cont = len(v) print('Ordem Inversa') while 0 < cont: print(v[cont-1]) cont -= 1
b1c0837a0210f95227e9ea969065743e05deaca4
emanoelmlsilva/ExePythonBR
/Exe.Lista/EL.12.py
475
3.9375
4
lista = list(range(3)) idade = list(range(3)) altura = list(range(3)) soma = 0 for i in range(len(lista)): idade[i] = int(input('Digite a idade do {} aluno: '.format(i+1))) altura[i] = float(input('Digite a altura do {} aluno: '.format(i+1))) soma += altura[i] med = soma / len(lista) cont = 0 for c in range(len(l...
c1402208921b4f5ac60a8a761181b3e25b863115
emanoelmlsilva/ExePythonBR
/Exe.Lista/EL.07.py
260
3.78125
4
lista = list(range(5)) v = [] soma = 0 mult = 1 for i in range(len(lista)): num = int(input('Digite um valor: ')) v.append(num) soma += num mult *= num print('números {}'.format(v)) print('soma: {}'.format(soma)) print('Multiplicação: {}'.format(mult))
2631027e3fa6486334282c4dd1f1784852dcc8fb
emanoelmlsilva/ExePythonBR
/Exe.Funçao/Fun.14.py
513
3.71875
4
def quadroMagico(vetor): i=0 while i < 9: print(vetor[i:i+3]) i+=3 if vetor[0] + vetor[1] + vetor[2] == vetor[3] + vetor[4] + vetor[5] == vetor[6] + vetor[7] + vetor[8] == vetor[0]+vetor[3]+vetor[6] == vetor[1] + vetor[4] + vetor[7] == vetor[2]+vetor[5]+vetor[8]==vetor[0]+vetor[4]+vetor[8]==vetor[2]+vetor[4]+vet...
0a386e52a550ee86dd053d3650fc57f722cc776f
emanoelmlsilva/ExePythonBR
/Exe.Lista/EL.06.py
390
3.65625
4
lista = range(10) v = [] m = [] soma = 0 cont = 0 for i in range(len(lista)): soma = 0 print('Notas do {} aluno'.format(i+1)) for c in range(4): num = int(input('Digite a {} nota: '.format(c+1))) soma += num med = soma / (c+1) m.append(med) if med >= 7: cont += 1 print('Quantidade de alunos com media maior...
f8338f794ac414ab549200bb19d8d35aa7aa0c28
emanoelmlsilva/ExePythonBR
/Exe.String/Str.10.py
439
3.78125
4
extenço = ["Um","Dois","Tres","Quatro","Cinco","Seis","Sete","Oito","Nove","Dez","Onze","Doze","Treze","Catorze","Quinze","Dezesseis","Dezessete","Dezoito","Dezenove"] extenço2 = ["Vinte","Trinta","Quarenta","Cinquenta","Sessenta","Setenta","Oitenta","Noventa"] num = input("Digite um numero entre 1 e 99: ") if int(num)...
4c8fd597108eb4fc5bc0cabfe54485d07d6664d0
emanoelmlsilva/ExePythonBR
/Exe.Funçao/Fun.11.py
462
3.9375
4
def mesExtençao(d,m): lista = [["janeiro",31],["fevereiro",28],["março",31],["abril",30],["maio",31],["junho",30],["julho",31],["agosto",31],["setembro",30],["outubro",31],["novembro",30],["dezembro",31]] return lista[m-1][0] dia = int(input("Digite o dia: ")) mes = int(input("Digite o mes: ")) ano = int(input("Digit...
bf232e52810fbb75ecf39c6bea4f9afd217b0e9c
emanoelmlsilva/ExePythonBR
/Exe.Lista/EL.10.py
267
3.671875
4
lista = list(range(10)) A = [] B = [] C = [] print('vetor A') for i in range(len(lista)): num = int(input('Informe o valor: ')) A.extend([num]) print('vetor B') for i in range(len(lista)): num2 = int(input('Informat o valor: ')) B.append(num2) C = A+B print(C)
1aa843542486e1490046c963454c6cb1191dee99
Spuntininki/Aulas-Python-Guanabara
/ex0065.py
829
3.953125
4
choice = '' maior = menor = c1 = c = n = media = divisor = 0 count = 1 while c == 0: n = int(input('Digite um número: ')) c1 = 0 media += n divisor += 1 if divisor == 1: menor = n maior = n else: if n < menor: menor = n if n > maior: maior ...
39559102ae362429f4ae8fbe1835aecbbc024bb2
Spuntininki/Aulas-Python-Guanabara
/ex0070.py
1,062
3.53125
4
condition = prodbarato = '' totalgasto = prodacima = contbarato = 0 c = 1 print('\033[1;33m-'*30) print('MERCADÃO GOSTOSÃO') print('-'*30, '\033[m') while True: nome = str(input('Insira o nome do produto: ')) preço = float(input('Preço R$ ')) totalgasto += preço if preço >= 1000: prodacima +=1 ...
27c08ed8c4d0b80c7039144a170f6375b6daba3f
Spuntininki/Aulas-Python-Guanabara
/ex0060.py
493
4.15625
4
#Programa que lê um numero inteiro positivo qualquer e mostra seu fatorial from math import factorial n = int(input('Digite um número: ')) f = factorial(n) print('O fatorial de {} é {} '.format(n, f)) '''c = n fator1 = n resultado = n * (n-1) for c in range(1, n-1): n -= 1 resultado = resultado * (n-1) print('...
7109cabf64155f383420680e9703c34cf57d1fa7
Spuntininki/Aulas-Python-Guanabara
/ex0050.py
430
3.890625
4
#Desenvolva um programa que leia 6 numeros inteiros e mostre a soma daqueles apenas que forem pares se o valor digitado #for impar desconsidere-o soma = 0 sumim = 0 for c in range(0, 6): n = int(input('Digite um numero inteiro: ')) if n % 2 == 0: soma = soma + n else: sumim = sumim + n prin...
150309146dee3aa590e2eaec982de8de7002f72e
Spuntininki/Aulas-Python-Guanabara
/ex0019.py
469
3.96875
4
#Um professor quer quer sorter um de seus quatro alunos para apagar o quadro. crie um programa que leio o nome de cada aluno # e escreva o nome de um dos alunos from random import choice a = str(input('Insira o nome do primeiro aluno: ')) b = str(input('Insira o nome do segundo aluno: ')) c = str(input('Insira o nome d...
6d2f71a7b39bff19bb69df495509b77ccc566a7e
Spuntininki/Aulas-Python-Guanabara
/ex0068.py
1,177
3.625
4
#JOGO DE PAR OU IMPAR from random import randint c = randint(1, 10) soma = n = contador = 0 escolha = '' while True: n = int(input('Digite um valor: ')) escolha = str(input('Impar ou Par, qual sua escolha? ')).strip()[0] soma = c + n if escolha in 'Pp': if soma % 2 != 0: print(f'A so...
5da7271021b5c6974312a0c25859be16bb09c6ef
Spuntininki/Aulas-Python-Guanabara
/ex0024.py
259
4.03125
4
#Escreva um programa que leia o nome de uma cidade mostre se ela começa com a palavra 'SANTO' nome = str(input('Insira o Nome da Cidade: ')).strip() #nome = nome.upper() #print('SANTO' in nome[0:5]) #RESOLUÇÃO GUANABARA: print(nome[:5].upper() == 'SANTO')
f03760fa806bbe7cfb598fc77320171599350fd7
Spuntininki/Aulas-Python-Guanabara
/ex0034.py
303
3.875
4
sal = float(input('Qual o salário do funcionario?')) if sal >= 1250.00: print('O salário terá um aumento de R${:.2f} resultando no total de R${:.2f}'.format(sal*0.10, sal*1.10)) else: print('O salário terá um aumento de R${:.2f} resultando no total de R${:.2f}'.format(sal*0.15, sal*1.15))
2e613d5771e5a9a9327f45d151701ae50eab91c1
Spuntininki/Aulas-Python-Guanabara
/ex0111/utilidadecursoemvideo/dados/__init__.py
1,468
3.734375
4
def leiaDinheiro(frase): from ex0111.utilidadecursoemvideo import moeda while True: n = str(input(frase)).strip() if n.isnumeric(): moeda.resumo(float(n)) break elif len(n) <= 2: print('\033[1;31mInsira um valor Válido!\033[m') elif n[-3] in ',...
1ee0731eff4974032b12a8c37a786675d1491061
Spuntininki/Aulas-Python-Guanabara
/ex0064.py
248
3.703125
4
c = n = i = 0 soma = int(0) while c == 0: n = int(input('Insira um número: ')) if n != 999: i += 1 soma = soma + n if n == 999: c = 1 print('Você digitou {} números e a soma entre eles é {}'.format(i, soma))
57a4a52f875eb7d51b1688b913d371982df90388
Spuntininki/Aulas-Python-Guanabara
/ex0039.py
1,819
4.0625
4
#Escreva um programa que leia a data de nascimento de um Jovem e mostre de acordo com sua idade se: #ele ainda vai se alistar # se é a hora de se alistar #se já passou da hora de se alistar # mostre também quanto tempo falta para se alistar e quanto tempo já passou from datetime import date atual = date.today().year pr...
5953c14f9cbb78a7ade8da111aab6ca6bbc69355
axis7818/vscode-hello-debugger
/python/hello_debugger.py
445
3.59375
4
#!/usr/bin/env python from argparse import ArgumentParser from hello import say_hi def parse_args(): parser = ArgumentParser( prog="Hello Debugger", description="A Simple hello world app to test vscode debugging", ) parser.add_argument("-n", "--name", help="who to say hi to", required=Tru...
d7e67f1843084c4bf6a1d05cfef688d1257bbe1a
zscdh1992/test
/test/2.py
491
3.75
4
# def func(a,b): # if a>b: # return 1 # elif a<b: # return 0 # else: # return -1 # res = func(1,2) # print(res) # info = 'abcdeafa' # print(info.count('a')) # print(info.startswith('b')) # print(info.find('a',-1)) # print(info.lower( ...
fadd016b73bba0e7feb1558a3655d951685b4222
zscdh1992/test
/test/getName.py
152
3.78125
4
def getName(srcStr): return srcStr.replace(',','').split(' ') name = getName('A old lady come in, the name is Mary, level 94454') print(name[-3])
4180d61ca9b36b2af864ae9171a65254fed33af6
alvadorn/hypercube
/hypercube/algorithm.py
1,740
3.765625
4
class DataStructure: def __init__(self): self.nodes = [] self.unique = 0 def add_node(self, common_id, parent_id): self.nodes.append(Node(self.unique, common_id, parent_id)) self.unique += 1 return self.unique - 1 def find_path(self, last_father): print("l...
8c8d97344606a1c8bcaa7e68a645b9c8004525dd
luisdcb97/Project-Euler
/Problems/[#3] Largest prime factor/main.py
763
3.90625
4
import math from typing import Generator def is_prime(number: int) -> bool: for factor in factors(number): if factor != number and factor != 1: return False return True def factors(number: int) -> Generator[int, None, None]: factor_list = [] for factor in range(1, int(math.sqrt(n...
6211f0a1f045716911bdce57ce3db6a21d7b3326
MayKeziah/CTRL_V
/GUIStuff/gui.py
7,321
4
4
import graphics as g #-------------------------------------------------------------------------- # Global Variables #-------------------------------------------------------------------------- """ Size of Pop-Up Window (Square) """ dimension = 600 """ X and Y Coordinate upper limit (Square) """ limit = 100 """ Number...
4c2f0f9e1239f6126889916d34432da9a73fc7e7
KetanSingh11/Revolut-Python-Engineer-Data-Task
/nest.py
8,816
3.5625
4
import json import argparse import logging import sys import os from tabulate import tabulate # Creating an object logging.basicConfig(stream=sys.stdout, level=logging.INFO) # Setting the threshold of logger to DEBUG logger = logging.getLogger(__name__) COLUMN_MAP = {} FILE_HEADER = [] # stored keys from raw...
66e3b71deb2d62ebc2cb9a9ef2a0885befd834b0
hank08tw/CodeFromLeetcode
/solutions/105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal_5.py
748
3.75
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {integer[]} preorder # @param {integer[]} inorder # @return {TreeNode} def buildTree(self, preorder, inorder): ...
6aa3b21dce8b6ee7c192e4a49d1bc741cead9bc0
yuchenz/koalaNLP
/simplifyTree.py
892
3.890625
4
#!/usr/bin/python2.7 def simplifyTree(tr): ''' if a subtree in this tree has only one child, combine the subtree's node label and the child's node label, and reduce a level of the subtree (keep POS tags for words) e.g. input: "(TOP (S (NP (NN (XX I))) (VP (XX (VV love) (NP (XX (NN python)))))))" output: "(TOP+...
8a3c3db3196cc72e02cdf7f42667ad4cb47c35c0
susanpray/python
/count.py
187
3.546875
4
class counter(): def add(self,a,b): c=a+b print c def sub(self,a,b): c=a-b print c susan=counter() susan.add(5,6) susan.sub(7,5)
60e61dc9c6194e1dafb38e0a46a218c2b537cd90
susanpray/python
/switchWordTryFile.py
1,079
3.765625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- ##把一个文件里面的英语单词首字母大写 import os import sys file = "testdata/22" newfile = "testdata/newsusan.txt" def read_file(file,newfile): try: f_open=open(file,'r+') except IOError, e: print "No such file" sys.exit() else: print "%s is existed" %(file) nf_...
3431a10b3fdade169b93d211b5a1d4291d14a2d8
tdn548/PythonFoundation
/Bai27_Tr7.py
382
3.53125
4
print('Bài 27') n=int(input("Nhập n:")) # n>m >0 m=int(input("Nhập m:")) i=1 count=0 while i<n: if n%i==0 and i<m: if count==0: print('Các ước số của %d nhỏ hơn %d: ' % (n, m), end=' ') print("%5d" %i,end="") count++ i++ if count==0: print("Không có ước số...
6a6263798ce30d664a693adc25bc06ee7edbf29b
vkphere3/interview-preparation
/2. Counting Valleys/counting-valleys-English- Solution.py
706
3.796875
4
#!/bin/python3 import math import os import random import re import sys # Complete the countingValleys function below. def countingValleys(n, s): below_sea=0 count_valley=0 steps=0 for step in s: if(step=='D'): steps-=1 elif(step=='U'): steps+=1 else: ...
c6c2ca4fcf728fbbd54a3ea74efbb6512c060012
Prashantbangar03/coriolis_assingment
/14.maps_list_of_word.py
276
4.03125
4
def getlength(word): cnt=0 for i in word: cnt=cnt+1 return cnt def mapwords(word): touple=() length=getlength(word) touple=(word,length) list1.append(touple) words=input("enter the Words ") words=words.split() list1=[] for i in words: mapwords(i) print(list1)
79621e67c3a685512b7a8a6c61b7d5e666d211ef
Prashantbangar03/coriolis_assingment
/40.anagram.py
438
4.03125
4
import random import itertools words = ['red', 'black', 'brown', 'green'] word, anagram = random.sample(words, 1)[0], '' perms = itertools.permutations(word) for perm in perms: if ''.join(perm) != word: anagram = ''.join(perm) break print ("Colour word anagram: %s" % anagram) input = raw_input("G...
296352b1de742a74e24ccb8bed77940daaef0038
Prashantbangar03/coriolis_assingment
/27.wordmap.py
424
3.875
4
def map_to_lengths_for(words): lengths = [] for word in words: lengths.append(len(word)) return lengths def map_to_lengths_map(words): wordlist=list(map(len, words)) print(wordlist) def map_to_lengths_lists(words): return [len(word) for word in words] words = ['abv', 'try me', ...
e91cdde843ea9d830f96c4161ee18a7ae398fc1c
Prashantbangar03/coriolis_assingment
/Find_length.py
182
3.96875
4
def Compute_length(list1): cnt=0 for i in list1: cnt=cnt+1 return cnt string=input("Enter String OR List") list1=string.split(',') length=Compute_length(list1) print(length)
caacbf28f1072cf91a4acb7b1176f542fd1eb561
Prashantbangar03/coriolis_assingment
/28.findlongestword.py
123
3.71875
4
def find_longest_word(words): return max(map(len, words)) print (find_longest_word(['prashant', 'vishal', 'suraj']))
07f451388e034a2546cb2c0f40e27aef270b783e
SmartAppUnipi/RoboComment
/Symbolic/server/game_model/interpreter/boolean_matcher.py
1,103
3.78125
4
from game_model.interpreter.regex_matcher import regex_matcher ''' This method picks a set of regexes and checks wether they all match in AND. The regex is an object with the following structure: Regex structure { 'pattern': [Object1, Object2, ...], 'stack': Stack } This means that for each regex object this...
4462c51c05cfeb1b3f68211b0b8467dbdcd5feb6
Jingjing-guan/MASY3540
/HW2_JINGJING_GUAN.py
7,040
4.0625
4
# -*- coding: utf-8 -*- """ Created on Mon Nov 5 12:12:04 2018 @author: miche """ import math import unittest import numpy as np import requests as r def exercise01(): # Create a list called animals containing the following animals: cat, dog, crouching tiger, hidden dragon, manta ray # -----...
7bbcb1ddfb304392e36917298b2cb04c81564e55
wbyxxmy/python
/aBytePython/using_dict.py
395
3.796875
4
ab = { 'zhangsan' : 'zhangsan@qq.com', 'lisi' : 'lisi@chinaredstar.com', 'wangwu' : 'wangwu@163.com', 'zhaoliu' : 'zhaoliu.123.com' } print("zhangsan's address :", ab['zhangsan']) del ab['zhangsan'] print("There are {0} items in ab".format(len(ab))) for name,address in ab.items(): print("{0}'s address is :{1}...
44d98208ba633db7d2a055fb39d5750b03f4a2bd
zoelzw/MachineLearning-practice
/insertion_sort.py
306
3.9375
4
def insertion_sort(nums): for i in range(1, len(nums)): cur_value = nums[i] k = i while k > 0 and cur_value < nums[k - 1]: nums[k] = nums[k - 1] k -= 1 nums[k] = cur_value return nums numbs = [1, 2, 3, 4, 5, 6] print(insertion_sort(numbs))
b21553d707de0f71d8137baa38831ff87bcfc499
dhruvsingh-coder/LearningRepo
/for loop.py
83
3.625
4
for i in range(5): print("hello") print("done with for loop") print("how are you")
3c071359f6da068aedcff91678fafb0018c364d7
AlejandroIV/MetNum_repo
/Mets1_SolNumEc1Var/Met3_NewtonRaphson.py
3,214
3.8125
4
"""Modulo que contiene el Metodo de Newton-Raphson""" import sys import sympy as sp def Newton_Raphson(expresion, xr, tolerancia, limite): """Funcion que llevara a cabo el proceso del Metodo de Newton-Raphson""" # Declaracion de variable simbolica (esta variable no puede ser global, sino causaria error...
739bcbba602c297103951959c41301e86bfa702f
AlejandroIV/MetNum_repo
/Mets3_FactLU/Met1_Cholesky.py
2,321
3.734375
4
"""Modulo que contiene el Metodo de Descomposicion de Cholesky""" import numpy as np import sys import math def matrizA(orden): """Funcion para definir los elementos de la matriz A y comprobar que sea simetrica y definida positiva""" # Pide al usuario los elementos de la matriz 'A' global A A = np.zer...
dc35ad336440ef50e9ce70d6a592c78681ac874f
gakeane/Numerical_Methods
/Root_Finding/Newton_Raphson_Univariate.py
7,794
4
4
""" This script implements te Newton Raphson method for finding the roots of an equation This is a refined version of the fixed point iteration method where the slope of g(x) is designed to be zero This ensures high speed convergence The algorithm works for any function f(x) = 0 an initial guess is made for the root...
6ca90806ac36b6dc24d2d2b6325771b7427b66a1
akshatshah21/PL-Lab
/jobScheduling.py
1,653
3.765625
4
''' Question: Job scheduling ''' import random import pprint #emp = [[y+1 if x==0 else None for y in range]] products = [chr(i) for i in range(65,70)] cost = [i*100 for i in range(1,6)] #emp = #l = [i[0]for i in emp] print(products) print(cost) def SortbyCost(val): return val[2] database = [[y+1 if x == 0 else...
5291b4c93015270086a3f273b80d10a477f4967f
LeetCodeSolution/LongestSubstringWithoutRepeatingCharacters
/solution1.py
626
3.546875
4
class Solution: def repeated(self, s): if len(set(list(s))) < len(s): return True return False def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ length = len(s) max_length = 0 for i in range(length): ...
e9bb0dcc45f8bb56e0d075012fe29ca231a4ea54
cxv8/CSE
/notes/kentzu xiong - Mad Lib.py
803
3.78125
4
print("Today is Monday") verb1 = input("Enter an 'ing' verb ") adjective = input("Enter an adjective ") noun1 = input("Enter an noun ") verb2 = input("Enter an 'ing' verb ") noun2 = input("Enter an noun ") verb3 = input("Enter an 'ing' verb ") adjective2 = input("Enter an adjective ") noun3 = input("Enter an noun ") a...
54c9a4f29e142515c282c9f01fa6ac515b1cf326
cxv8/CSE
/notes/Kentzu Xiong - Guess Game.py
846
4.09375
4
import random number = (random.randint(0, 10)) guess_taken = 1 guess_number = int(input("Guess a number between 0 and 10. ")) if guess_number < number: print("Your guess is to low") elif guess_number > number: print("Your guess is to high") elif guess_number == number: print("You guessed it!. It took %s gue...
419d9357b397ca6440e272a24e616793192969a1
niyasimonc/PROJECTS
/Toy-vm/Test cases/sum.py
92
3.828125
4
def sum(n): if n==0: return 0 else: return n+sum(n-1) print sum(5)
bfa4cd171831f50848856dd016fb4fdf0461bc47
davidjeet/Learning-Python
/PythonHelloWorld/MoreLists 2/MoreLists_2.py
948
4.125
4
z = 'Demetrius Harris' for i in z: print(i,end = '*') print() eggs = ('hello', 323, 0.5) print(eggs[2]) #eggs[1] = 400 # illegal #converting tuple to list a = list(eggs) a[1] = 500 b = tuple(a) print(b) spam = 42 cheese = 100 print(spam) print(cheese) #different than spam, because by-value spam = [0,1,2,3,4,5] c...
1c7472684b1621d64c77426d62733997f027b60d
LFValio/aprendendo-vetores
/vetores-aprendendo/ex-03.py
625
4.125
4
# Exercício 3: ler vários nomes mas só armazenar aqueles que começam com C. nome = [] cNome = 0 # contagem nome sNome = [] # string nome for x in range(1, 6): nome.append(str(input(f"{x}º Nome: "))) for x in nome: # varrerá o vetor nome, verificando todas as palavras que con...
f8243a20e58304ee0dbdec66c38d290fe8fd8874
olusegun23/13301338176-ml
/reinforcement_learning/David-Silver-RL/David-Silver-RL/Assign/easy21.py
1,525
3.640625
4
import numpy as np import random class Easy21(object) : # class of easy21 game def __init__(self) : self.dealer_sum = 0 self.player_sum = 0 self.game_in_progress = False def draw_card(self) : number = random.randint(1, 10) if random.random() <= 0.333333 : number = -number return number ...
aa1d86e1bd876632b1db4d2d5f9381a162db051f
wavecrasher/Turtle-Events
/main.py
416
4.21875
4
import turtle turtle.title("My Turtle Game") turtle.bgcolor("blue") turtle.setup(600,600) screen = turtle.Screen() bob = turtle.Turtle() bob.shape("turtle") bob.color("white") screen.onclick(bob.goto) #bob.ondrag(bob.goto) screen.listen() #The pattern above consists of circles drawn repeatedly at different angles -...
5a3998e34772c95e05f2fd5a5e5e0e1835858943
archeraghi/swarm-sim
/lib/swarm_sim_header.py
2,522
3.546875
4
import sys def eeprint(*args, sep=' ', end='\n'): """ prints error message to stderr, stops the program with error code -1 :param args: like in print() :param sep: like in print() :param end: like in print() :return: """ print(*args, sep, end, file=sys.stderr) exit(-1) def eprint...
77f35eac9b402200cd4baee2a2326db2860896ac
RuchaCB/Trio_Chess
/Demo_1/trial_refactor.py
5,516
3.6875
4
import turtle import math from centroid import centroid polygon = turtle.Turtle() polygon.speed(0) count = 0 def square(x, l): polygon.forward(x) polygon.right(90) p1 = polygon.pos() polygon.forward(l) polygon.right(120) p2 = polygon.pos() polygon.forward(l) polygon.r...
b9bc55c14baaf0d0f11234c3c8593fe4b5a4ba47
Benzlxs/Algorithms
/sorting/merge_sort.py
1,103
4.125
4
# merge sortting https://en.wikipedia.org/wiki/Merge_sort import os import time def merge(left, right): # merging two parts sorted_list = [] left_idx = right_idx = 0 left_len, right_len = len(left), len(right) while (left_idx < left_len) and (right_idx < right_len): if left[left_idx] <=...
cf8a92e8c176b67a92520c79cfe8d642963f8aba
Benzlxs/Algorithms
/exercise/Niuke_wang/path_in_a_matrix.py
2,164
3.890625
4
""" 题目描述:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。 路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。 如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"abccee"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后, 路径不能再次进入该格子。 """ ## recrusive class Solution: def hasPath(self, matrix, rows, cols, path...
cac68f6a0cb20080f211d0c83f6482a2827f60c7
Benzlxs/Algorithms
/sorting/selection_sort.py
784
4.40625
4
# merge sortting https://en.wikipedia.org/wiki/Selection_sort # time complexity is O(n^2) import os import time def selection_sort(list_nums): for i in range(len(list_nums)): lowest_value_index = i # loop through unsorted times for j in range(i+1, len(list_nums)): if list_nu...
2d9528978712ccd090ebc0e435f690d3866a24d4
syedareehaquasar/Chess-PGN-to-FEN-convertor
/piece.py
4,552
3.578125
4
import re SPACE = " " def castle(move, board_view, piece_view): if move in "OOO": home_rank, king, rook = "1", "K", "R" else: home_rank, king, rook = "8", "k", "r" king_before = "e" + home_rank if len(move) == 2: rook_before = "h" + home_rank king_after = "g" + home_ran...
d37176cdcefee0beada57418aed22bc3d421e34a
C00kieMonsta/uni-linear-regression
/helpers.py
912
3.84375
4
import numpy as np import matplotlib.pyplot as plt # Compute cost for linear regression def compute_cost(X, y, theta=np.array([[0],[0]])): m = len(y) h = np.dot(X,theta) cost = (1.0/(2*m)) * np.dot((h-y).T,(h-y)) return cost # Compute gradient descent to fit theta params for linear regression def grad...
86fe3b36626dc4325a15594f93f51beb3bd111be
dmesquita/tide
/tidecv/functions.py
2,544
3.59375
4
import matplotlib.pyplot as plt import numpy as np import os, sys def mean(arr:list): if len(arr) == 0: return 0 return sum(arr) / len(arr) def find_first(arr:np.array) -> int: """ Finds the index of the first instance of true in a vector or None if not found. """ if len(arr) == 0: return None idx = arr.arg...
a703521f886ba2011beae0623dc3251de5ac165f
bartosz98765/rest_chess_solver
/solver/models.py
3,653
3.59375
4
from abc import ABC, abstractmethod def set_figure(field, name): figure = None if name == "king": figure = King(field, name) if name == "rook": figure = Rook(field, name) if name == "bishop": figure = Bishop(field, name) if name == "queen": figure = Queen(field, nam...
577fff341d8a7e541c48ac96941dbc178d4516d9
Unstablecat/CompCamps2018
/Python/main.py
279
3.875
4
name = input("hello what is your name") def welcome(name): if name == "Max": print("hello Max") else: print("welcome to python {}".format(name)) welcome(name) Mits = ["Bennett","kaitlin","Rhiannon","Austin","Travis"] for mit in Mits: welcome(mit)
251b46112a4ba9c6983a3baa6545bd2f47a10edb
PersianBuddy/emailsearcher
/main.py
1,039
4.25
4
#! Python 3 # main.py - finds all email addresses import re , pyperclip # user guid print('Copy your text so it saves into clipboard') user_response = input('Are you ready? y=\'yes\' n=\'no\' :') while str(user_response).lower() != 'y': user_response = input("Make sure type 'y' when you copied your desired text :...
1dc223d19d6a6dd7c0b5b5faeee55c8053c4101e
uecah/shujvjiegou2
/shujvjiegouyvsuanfa/likou_56.py
1,084
3.515625
4
""" 56. 合并区间 给出一个区间的集合,请合并所有重叠的区间 输入: [[1,3],[2,6],[8,10],[15,18]] 输出: [[1,6],[8,10],[15,18]] 解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]. """ class Solution(object): def merge(self, intervals): """ :type intervals: List[List[int]] :rtype: List[List[int]] """ intervals.sort(key=l...
6ed11737fc26a89cabf1730e7ef3bcb88e39db37
uecah/shujvjiegou2
/shujvjiegouyvsuanfa/my_test.py
1,978
3.796875
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ self.flag = True ...
6762dd770f5d6a9dd7ac8d6b8a4216cfe4b284a9
uecah/shujvjiegou2
/lagou/03_滑动窗口最大值59.py
1,334
3.59375
4
""" 单调双端队列:放入里面的元素值一定是从左向右递减的, 操作步骤: (1)依次逐个遍历原数组中的值,遍历取出来一个a; (2)查看双端队列左侧是否有超出窗口长度的元素,如果有,逐个删除一个; (3)从右侧查看是否有比a小的元素,如果有,则删除; (4)将a放入双端对列的右侧; (5)返回左侧第一个元素值,作为当前窗口中的最大值。 """ import operator class Solution(object): def isBipartite(self, graph): """ :type graph: List[List[int]] :rtype: boo...
2f73b768f8fca02c922be82265a8a6a9d0218ac9
filvet80/pythonProject4
/WHILE.py
148
4
4
def function(a, b, c): while a < c: print(a + b) a += b if a >= c: break print("The Cycle is Over") function(9, 3, 18)
7ce7b8965c78c0e772953895bc81b4bd9023f15a
pezLyfe/algorithm_design
/intro_challenges/max_pairwise_product_2.py
615
4.15625
4
# Uses python3 ''' The starter file provided by the course used nested for loops to calculate the solution as a result, the submission failed due to an excessive runtime. The list.sort() method in python works really fast, so use that to order the list and then multiply the largest entry in the list by the second large...
28c4a9c382e199e14d97b9171a5e24f63befa8fa
f3ath/learning-python
/test.py
833
3.640625
4
import unittest from fibonacci import fibonacci, NumberLengthChecker class TestFibonacci(unittest.TestCase): def test_first_7_numbers_match_expected(self): fibo = fibonacci() for n in [1, 1, 2, 3, 5, 8, 13]: self.assertEqual(n, next(fibo)) class TestNumberLengthChecker(unittest.TestC...
cfeb09f3cf81d37b73873519f45e33d16910c03c
csn-intern-choy/DoubleAuctionMarket
/trader.py
5,357
3.796875
4
import random class SimpleTrader(object): """ A class that makes a trader""" def __init__(self): self.name = "" self.limits = (0, 0) self.type = "" self.values = [] self.costs = [] def offer(self, contracts, standing_bid, standing_ask): num_contracts = 0 # ...
b10e3165a70616b89df9e3df762c787e51bb3238
Moebutla/Engr-102-Class
/Lab11B/Lab11B-e_Butler.py
1,230
3.90625
4
# By submitting this assignment, I agree to the following: # “Aggies do not lie, cheat, or steal, or tolerate those who do” # “I have not given or received any unauthorized aid on this assignment” # # Name: Mose Butler, 128004413 # Section: 535 # Assignment: (lab 11b-e) # Date: (...
4aa6d82337112bf67745624caa5cc685aa52d5f9
Moebutla/Engr-102-Class
/Lab3B/Lab3B_ProgD.py
783
3.96875
4
# By submitting this assignment, I agree to the following: # “Aggies do not lie, cheat, or steal, or tolerate those who do” # “I have not given or received any unauthorized aid on this assignment” # # Name: Mose Butler # UIN: 128004413 # Section: 535 # Assignment: Lab 3b-1d # Date: 09/...