blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
81a3f54d52f62b4b671493006c68160c296e475d
CouchNut/Python3
/Class/special_getitem.py
912
3.984375
4
#!/sur/local/bin python3 # -*- coding: utf-8 -*- # 要表现得像list那样按照下标取出元素,需要实现__getitem__()方法: class Fib(object): # 不支持切片去下标值 def __getitem__(self, n): a, b = 1, 1 for x in range(n): a, b, = b, a + b return a f = Fib() print(f[0]) print(f[1]) print(f[2]) print(f[3]) print(f[4]) print(list(range(100)...
7a85ef27ee90462fcaeb8717d51176fd5c5a3b58
CouchNut/Python3
/IO/use_json.py
886
3.671875
4
#!/usr/local/bin python3 # -*- coding: utf-8 -*- print('---------- JSON ----------') import json # d = dict(name='Bob', age=20, score=88) # print(json.dumps(d)) # json_str = '{"name": "Bob", "age": 20, "score": 88}' # print(json.loads(json_str)) class Student(object): def __init__(self, name, age, score): se...
2719bb52f591e7edf5abd6e0ca0eec8f494ab7ab
CouchNut/Python3
/inlinemodule/use_itertools.py
1,374
4.03125
4
#!/usr/local/bin python3 # -*- coding: utf-8 -*- # 无限迭代器 import itertools # count() 会创建一个无限的迭代器, # 所以下列代码会打印出自然数序列,根本停不下来,只能按Ctrl+C退出。 # natuals = itertools.count(1) # for n in natuals: # print(n) # cycle() 会把传入的一个序列无限重复下去 cs = itertools.cycle('ABC') # 注意字符串也是序列的一种 # for cc in cs: # print(cc) # repeat()负责把一个元素无限...
ca8a902c87c57f7aa79c18ae63621783de6f07f9
CouchNut/Python3
/Class/network.py
1,164
3.515625
4
# 字符串正则匹配 import re result1 = re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') print(result1) result2 = re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') print(result2) # from urllib.request import urlopen # for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): # line = line.decode(...
ceda294e6c7eab793c25954308c6d5b28686b072
CouchNut/Python3
/Class/special_call.py
352
3.5625
4
#!/sur/local/bin python3 # -*- coding: utf-8 -*- class Student(object): def __init__(self, name): self.name = name def __call__(self): print('My name is %s.' % self.name) s = Student('Michak') s() # self 参数不要传入 print(callable(Student('Copper'))) print(callable(max)) print(callable([1, 2, 3])) print(None) pr...
05e4f07ceed5dd24c9550d97cad830b442f0d0d7
CouchNut/Python3
/Class/do_filter.py
1,110
3.921875
4
# filter()把传入的函数依次作用于每个元素, # 然后根据返回值是True还是False决定保留还是丢弃该元素。 # 在一个list中,删掉偶数,只保留奇数,可以这么写: def is_add(n): return n % 2 == 1 L = list(filter(is_add, [1, 2, 3, 4, 5])) print(L) # 把一个序列中的空字符串删掉 def not_empty(s): return s and s.strip() L2 = list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])) print(L2) # 用filter 求...
2b44c016feeed5be184877be0e84ba5ff8e7f38c
VishalSinghRana/Basics_Program_Python
/Squareroot_of_Number.py
284
4.34375
4
y="Y" while(y=="y" or y=="Y"): number = int(input("Enter the number")) if number < 0: print("Please Enter a postive number") else: sqrt= number**(1/2) print("The squareroot of the numebr is ",sqrt) y=input("Do you want to continue Y/N?")
b843c702d381a81003db27bb0acc2ca3696baa07
patiregina89/Desafios-Prof_Guanabara
/Desafio51.py
336
3.828125
4
'''Desenvolva um programa que leia o primeiro termo e a razão de um PA. No final mostre os 10 primeiros termos dessa progressão.''' pt = int(input('Informe o primeiro termo: ')) r = int(input('Informe a razão: ')) dec = pt + (10 - 1) * r for c in range(pt, dec + r, r): print('{}'.format(c), end=' ► ') pr...
429a1a5a27ce1a2d1166d16de7b33bfc2b947008
patiregina89/Desafios-Prof_Guanabara
/Desafio59.py
1,191
4.34375
4
'''Crie um programa que leia dois valores e mostre um menu na tela. 1 - somar 2 - multiplicar 3 - maior 4 - novos números 5 - sair do programa O programa deverá realizar a operação solicitada em cada caso''' num1 = int(input('Informe um número: ')) num2 = int(input('Informe outro número: ')) maior = num1 op...
8b16882875c4e0825937d099f2de099ed67f013c
patiregina89/Desafios-Prof_Guanabara
/Desafio10.py
311
3.859375
4
#crie um programd e quanto dinheiro a pessoa tem na carteira e mostre quantos dolares pode comprar (US$1 = R$3,27) real = float(input('Informe quantos reais você possui: ')) dolar = real // 3.27 valorexato = 3.27*dolar print('Você pode adquirir {:.0f} dólares com {:.0f} reais'.format(dolar, valorexato))
83878954d0b3f8e8282c949ec281fd0cae96892f
patiregina89/Desafios-Prof_Guanabara
/Desafio56.py
962
3.875
4
'''Desenvolva um programa que leia o nome, idade, sexo de 4 pessoas e no final mostre: a média de idade qual o nome do homem mais velho e quantas mulheres tem menos de 20 anos''' somaidade = 0 media = 0 velho = 0 nomevelho = '' mulher20 = 0 for pessoa in range(1, 5): print('------------{}ª Pessoa-------...
213f68b5b6efd33a4629362d53d1a93ebe1848c3
patiregina89/Desafios-Prof_Guanabara
/Desafio48.py
717
3.59375
4
'''Faça um programa que calcule a soma entre todos os números ímpares que são multiplos de três num intervalo de 1 - 500''' s = 0 #a variável S está fazendo um papel de ACUMULADOR, isto é, soma de valores cont = 0 #a variável cont está fazendo o papel de CONTADOR, isto é, ele soma o item e NÃO seu valor. for c in ...
50d762b59501da6bfdd72dc3c44b2c7426ad0d78
patiregina89/Desafios-Prof_Guanabara
/Desafio53.py
752
4.0625
4
'''Crie um programa que leia uma frase qualquer e diga se ele é palíndrome, desconsiderando os espaços.''' frase = str(input('Digite uma frase: ')).strip().upper() #.strip tira os espaços vazios e .upper deixa tudo maiúscula. palavras = frase.split() #.split divide a frase em palavras junto = ''.join(palavr...
a40d22e90f1681fa814a4506e7810567f705adfa
matthewharrilal/Hangman-Project-CS1
/Hangman-Project.py
3,279
4.09375
4
#First create a list of the whole alphabet #Pick a random word #Prompt user to choose a letter. Success or fail #If success, ask again until the word is spelled import string import random #alphabet alphabet = list(string.ascii_uppercase) #number of tries attempts = 10 #generate list def create_list_words(file):...
0e45077e319db70fa7943da9ebe4937f01f9bafd
SoundaryaJagan/SoundaryaJagan
/index.py
169
3.53125
4
def(l): for i in range(len(l)): if i==l[i]: print(i) def main(): try: n=int(input()) l=[] for i in range(n): l.append(int(input())) f(l) except: print('invalid') main()
703e5205c272fd205a3dc6fc950e64663cdcdae6
kcwebers/Python_Fundametnals
/OOP/users_with_accounts.py
2,123
4.03125
4
class BankAccount: def __init__(self, account_balance, account_interest): self.account_balance = account_balance self.account_interest = account_interest def deposit(self, amount): self.account_balance += amount return self def withdrawal(self, amount): # decreases the ac...
b81bf5104838515302768a79df37c945fa7a4f5a
kcwebers/Python_Fundametnals
/fundamentals/insertion.py
2,060
4.3125
4
# Build an algorithm for insertion sort. Please watch the video here to understand how insertion sort works and implement the code. # Basically, this sort works by starting at index 1, shifting that value to the left until it is sorted relative to all values to the # left, and then moving on to the next index positio...
d7b0e48b7a6446b065973c0b4d509002bd3bd19c
Mr-Patate/Server-Clients-Chat
/clientSide.py
2,432
3.6875
4
from socket import AF_INET, socket, SOCK_STREAM from threading import Thread import tkinter # The receive function is listeling in While loop # It will display messages that are oncoming def receive(): while True: try: msg = client_socket.recv(BUFSIZ).decode("utf8") # the message is...
07a2b70ca25f20852834cf6b5451951ad90e4a33
psyde26/Homework1
/assignment2.py
501
4.125
4
first_line = input('Введите первую строку: ') second_line = input('Введите вторую строку: ') def length_of_lines(line1, line2): if type(line1) is not str or type(line2) is not str: return('0') elif len(line1) == len(line2): return('1') elif len(line1) > len(line2): return('2') ...
4b22e88cf40b60ca9f2296117d4e73e0fe51cd70
swane/ceres
/carrot_line.py
430
3.6875
4
#!/usr/bin/env python import math def carrot_point(CN,CE,N1,E1,N2,E2,Aim): AF=((N1-CN)*(N1-N2)+(E1-CE)*(E1-E2))/(math.sqrt((N1-N2)**2+(E1-E2)**2)) AB=math.sqrt((N1-N2)**2+(E1-E2)**2) FN=N1+(N2-N1)*(AF/AB) FE=E1+(E2-E1)*(AF/AB) carrot_N=FN+(N2-N1)*(Aim/AB) carrot_E=FE+(E2-E1)*(Aim/AB) return carrot_N,ca...
f13caafb7e6a5ca85fc1517005200bcb8c45a784
jacarty/weekly-python-exercise
/exercise #2: Read_N/countdown.py
330
3.65625
4
#!/usr/bin/python import sys, time def countdown(num): print 'starting' while num > 0: print num yield num num -= 1 time.sleep(2) if __name__ == '__main__': val = countdown(int(sys.argv[1])) try: for i in val: next(val) except StopIteration: ...
45b08672f5802bd07e54d45df20b24c1538a2673
jxthng/cpy5python
/Practical 03/q7_display_matrix.py
383
4.4375
4
# Filename: q7_display_matrix.py # Author: Thng Jing Xiong # Created: 20130221 # Description: Program to display a 'n' by 'n' matrix # main # import random import random # define matrix def print_matrix(n): for i in range(0, n): for x in range (0, n): print(random.randint(0,1), end=" ") ...
02f76ae07d4bb429bf6a8319cce2aba0cb80ef58
jxthng/cpy5python
/compute_bmi.py
634
4.59375
5
# Filename: compute_bmi.py # Author: Thng Jing Xiong # Created: 20130121 # Modified: 20130121 # Description: Program to get user weight and height and # calculate body mass index (BMI) # main # prompt and get weight weight = int(input("Enter weight in kg:")) # prompt and get height height = float(input("Enter heigh...
723f43c5f3555576fb2f01526ac4924675e93c5f
jxthng/cpy5python
/Practical 03/q2_display_pattern.py
515
4.40625
4
# Filename: q2_display_pattern.py # Author: Thng Jing Xiong # Created: 20130221 # Description: Program to display a pattern # main # define display pattern def display_pattern(n): prev_num = [] for i in range(1, n + 1): prev_num.insert(0, str(i) + " ") length = len("".join(prev_num)) prev_num...
1b40fd6dfbc67682a85fed5140d9f1d16a810286
Usuallya/python
/class-object/c4.py
1,727
4.1875
4
#python类的封装、继承和多态 #import people from people import People #1、继承的写法 class Student(People): # sum = 0 # def __init__(self,name,age): # self.name=name # self.age = age # self.__score=0 # self.__class__.sum+=1 #派生类的构造函数需要传入父类需要的参数,然后调用父类的构造函数来完成初始化 def __init__(self,school,nam...
6c7f001981ebbfb6ecfb45269132071bfcd7c513
suxanovvv/Lab10
/1.3.py
2,313
3.90625
4
#3. Сформувати функцію для обчислення індексу максимального елемента масиву #n*n, де 1<=n<=5. import numpy as np import random while True: #Задання розміру масиву та його ініціалізація. n=int(input('Введіть розмірність масиву від 1 до 5!: ')) if n>5 or n<0: print('Виберіть розмірні...
3c144e821443e44da6317169ecdc9992134a34fc
DevJ5/Automate_The_Boring_Stuff
/Dictionary.py
1,184
4.28125
4
import pprint pizzas = { "cheese": 9, "pepperoni": 10, "vegetable": 11, "buffalo chicken": 12 } for topping, price in pizzas.items(): print(f"Pizza with {topping}, costs {price}.") print("Pizza with {0}, costs {1}.".format(topping, price)) # There is no order in dictionaries. print('che...
7fe206dde03d362f26ee79a10f4f3f0b51586a38
zhuqywx/study
/练习/练习30.py
244
3.75
4
# 一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。 a = input("输入一串数字: ") b = a[::-1] if a == b: print("%s 是回文"% a) else: print("%s 不是回文"% a)
befe1f747a224f42d64f00a63c6dc9a83ac7151e
Jayasree357/Jayasree357
/percentage of classes attended.py
303
3.953125
4
ch=int(input("enter the number of classes held:")) ca=int(input("enter the number of classes attended:")) percent=(ca/ch)*100 print(percent,"%") if percent<float(75): print("The student is not allowed to write the exam") else: print("The student is allowed to write the exam")
fa865a7b8178f5d040d66999747a828d51011895
hemang-75/Data_Structures_and_Algorithms
/problem_3/problem_3.py
1,737
3.984375
4
def rearrange_digits(input_list): """ Rearrange Array Elements so as to form two number such that their sum is maximum. Args: input_list(list): Input List Returns: (int),(int): Two maximum sums """ frequency = [0 for i in range(10)] for i in input_list: freque...
cab3375a9684ff239092eab89c23e8a6ab0a9d42
anasreis/ts-mut
/ts-mut-vestibulando/vestibulando.py
375
3.703125
4
def verificaVestibulando(nota: int) -> str: res = None if nota > 400: res = 'Você está selecionado' elif nota > 0 and nota < 200: res = 'Você não foi selecionado' elif nota >= 200 and nota <= 400: res = 'Você está na lista de espera' elif nota == 0: res = 'É nece...
589c8cea58e6e7ac9199ddaa5476aac4fdb7ff7a
alejandrosocorro/pyprog
/fibonacci/fib-memoization.py
251
3.671875
4
from typing import Dict memo: Dict[int, int] = {0: 0, 1: 1} # base cases def fib(n: int) -> int: if n not in memo: memo[n] = fib(n - 1) + fib(n - 2) return memo[n] if __name__ == "__main__": print(fib(5)) print(fib(50))
633c8634b9bca8cb92d6b73090e68d144e7b8969
mattratliff/python-games
/Pong/pong.py
1,739
3.734375
4
import pygame import paddle as p import gameball as b import constants as c import inputhandler as d score1 = 0 # Call this function so the Pygame library can initialize itself pygame.init() # Create an 800x600 sized screen screen = pygame.display.set_mode([800, 600]) # Set the title of the window pygame.display...
bf3962b867de1898be23a3157db82caede7075f3
Sm0rezDev/PyPong
/pong.py
2,041
3.5
4
from tkinter import * import time import keyboard WIDTH = 800 HEIGHT = 500 GAME_SPEED = 0.005 ballSpeedX = 0 ballSpeedY = 0 PADDLE_SPEED = 2 BG = "Black" tk = Tk() canvas = Canvas(tk, width=WIDTH, height=HEIGHT, bg=BG) tk.title("PyPong") tk.resizable(0,0) canvas.pack() paddleStartPos = (HEIGHT/2)-120 paddle1 = c...
4421472dc076956dbfedd7591dea5dd2f457ee6d
michaelcjoseph/ProjectEuler
/projecteuler21.py
601
3.765625
4
#Project Euler 21 #Amicable Numbers import math #This function returns the sum of the divisors of the argument def divisor_sum(num): sums = 1 for i in range(2, int(math.sqrt(num)) + 1, 1): if num % i == 0: sums += i + (num / i) return sums def main(): amicable_sums = 0 amicable_numbers = [] for x in ra...
a55c565ed331cc2aed98fa2a0f023476cfccfe4d
billmania/auv_bonus_xprize
/AUV_Bonus_XPrize/searchspace/geometry.py
12,209
3.828125
4
# # Designed and written by: # Bill Mania # bill@manialabs.us # # under contract to: # Valley Christian Schools # San Jose, CA # # to compete in the: # NOAA Bonus XPrize # January 2019 # """Geometry Classes and methods for representing and interacting with points, lines, and polygons. """ from math import sqrt, radia...
66202b46a953ccc4695716e49fd5fa55b2cf3a6d
ritika142/assignment1
/Noun_Phrase extractor.py
242
3.625
4
from textblob import TextBlob data = input("Enter the data => ") obj = TextBlob(data) lst = obj.noun_phrases print("There are ", len(lst), " noun phrases in the inputed text-:", end="\n\n") for np in lst: print(np, end="\t\t")
47fbd5f510372e9b3d34b7e14ea8c212f43dd342
MachFour/info1110-2019
/week6/W15A/sorter.py
805
3.890625
4
import sys if len(sys.argv) < 2: print("Filename not given") sys.exit(1) # Open the file for reading f = open(sys.argv[1], 'r') # Read all the lines from the file and puts them in a list of strings lines = f.readlines() # Closes the file f.close() # This sorts the file lines.sort() # Using split to split be...
e55f852bf24b11285909b1741c7ee8e5b737df02
MachFour/info1110-2019
/week3/max/sphere.py
147
4.21875
4
pi = 3.14159 r = float(input("Radius: ")) print("The surface area is {:.2f}".format(4*pi*r*r)) print("The volume is {:.2f}".format(4/3*pi*r*r*r))
7517aaf899655c8fd71ba01062032df57211ceed
MachFour/info1110-2019
/week6/W13B/turtles.py
460
3.765625
4
names = [] ages = [] while True: turtle_input = input("Turtle data: ") # "Adam, 3" --> ["Adam", "3"] # Lucy, 4 --> ["Lucy", "4"] if turtle_input == "STOP": break turtle_input = turtle_input.split(", ") names.append(turtle_input[0]) ages.append(turtle_input[1]) if(len(names) == 0): ...
76a080b08119cc6bb161405eae30cd5ec38ad8ad
MachFour/info1110-2019
/week8/nahian/quadratic_test.py
776
3.5625
4
from quadratic import quadratic # ^ from the file `quadratic.py`, import the function `quadratic` # (so we can test that function here in this program) # Run the `quadratic` function against the first test case def example_1(): expected = (2.5, 1.0) actual = quadratic(2, -7, 5) assert actual == expected, ...
0bb5501ebf856a20a70f2ec604495f21e10a4b0c
MachFour/info1110-2019
/week3/W13B/integer_test.py
399
4.25
4
number = int(input("Integer: ")) is_even = number%2 == 0 is_odd = not is_even is_within_range = 20 <= number <= 200 is_negative = number < 0 if is_even and is_within_range: print("{} passes the test.".format(number)) # Else if number is odd and negative elif is_odd and is_negative: print("{} passes the test....
bf86e2e9ac26825248273684b72b95427cc26328
MachFour/info1110-2019
/week6/W13B/exceptions.py
778
4.25
4
def divide(a, b): if not a.isdigit() or not b.isdigit(): raise ValueError("a or b are not numbers.") if float(b) == 0: # IF my b is equal to 0 # Raise a more meaningful exception raise ZeroDivisionError("Zero Division Error: Value of a was {} and value of b was {}".format(a,b)) ...
b9d7faf00bcac19f2e292331e9800c05b4b489fa
MachFour/info1110-2019
/week11/W13B/fibonacci.py
923
4.1875
4
def fibonacci(n): if n < 0: raise ValueError("n can't be negative!") # just for curiosity print("fibonacci({:d})".format(n)) # base case(s) if n == 0: return 0 elif n == 1: return 1 # else return fibonacci(n-1) + fibonacci(n-2) def fibonacci_iterative(n): if ...
4e9406b7baee498fbeb12450f92299aa86697bdf
MachFour/info1110-2019
/week3/max/integer-first-try.py
282
4.03125
4
i = int(input("Number: ")) # check if i is even and in the range [20, 200] (inclusive), # or i is odd and negative if (i % 2 == 0 and i > 20 and i < 200) or (i % 2 == 1 and i < 0): print("{:d} passes the test!\n".format(i)) else: print("{:d} fails the test :(\n".format(i))
02930644ec3cd051b1416e2860a002da5d374224
MachFour/info1110-2019
/week5/R14D/control-flow-revision.py
354
4.25
4
a = 123 if a == "123": print("a is 123") if a > 0: print("a is greater than 0") else: print("a is less than or equal to 0???") a = 123 while True: if a == 123: print("Hello from inside the while loop") a = a - 1 elif a > 122 or a < 0: break else: a = a - ...
cd3f58edcfc7245925785a84c06a876369838ef3
MachFour/info1110-2019
/week6/T14C/readlines.py
601
3.921875
4
def readlines(path): # this will store the lines in the file lines = [] f = open(path, 'r') # reads until the next newline character while True: next_line = f.readline() if next_line == "": # end of file break # remove whitespace at the start and the ...
83938e37f0e8d574da391f1022b355c6d9218ea6
MachFour/info1110-2019
/week2/W15A/modulo.py
295
3.96875
4
import sys n = int(sys.argv[1]) m = int(sys.argv[2]) remainder = n % m # print("After dividing ", n, "by ", m, "the remainder is ", remainder) # print("After dividing {} by {}, the remainder is {}.".format(n, m, remainder)) print(f"After dividing {n} by {m}, the remainder is {remainder}")
a1d6af728642205b7489852afef7d6b2732c0344
MachFour/info1110-2019
/week3/max/desk-check.py
306
4
4
# # Print out all triangular numbers that are: # less than 15 # and either a multiple of 2 or 5 # t_num = 1 step = 2 print('Hello!') while True: if t_num >= 15: break if t_num % 2 == 0: print(t_num) elif t_num % 5 == 0: print(t_num) t_num += step step += 1
ab0a3bc307ffbb77610d03ef14f875e6bb2e586c
MachFour/info1110-2019
/week10/R14D/spell.py
2,157
3.578125
4
class Spell: def validate(name, school, level, cast_limit, effect): if not isinstance(name, str): raise ValueError("name must be a string") if not isinstance(school, str): raise ValueError("school must be a string") if not isinstance(level, int) or not 0 <= level <= ...
c0350c45ecd900dc2ecf76ff0edb377bbd1b2ae9
MachFour/info1110-2019
/week10/T14C/spellbook.py
3,693
3.984375
4
class Spellbook: # store the error message as a class variable capacity_error = "We're nearing the end of our power budget. " \ "You can't write '{}' into this spellbook." @staticmethod def validate(material, capacity, spells): if not isinstanceof(material, str): ...
70514719b85a8c73f1881ae521606a66466b215c
aarthymurugappan101/python-lists
/append.py
289
4.1875
4
numbers = [2,3,5,7,89] # List Datatype # print("Before",numbers) numbers.append(100) # print("After",numbers) numbers.append(33) # print(numbers) numbers.insert(2, 66) # print(numbers) print(numbers) numbers.pop() print(numbers) numbers.pop(1) print(numbers) numbers.sort() print(numbers)
3a77a728965b3053670a7711600984abdb61b23b
ESBrunner/conIntProject
/confidenceIntervalProject.py
2,560
4.0625
4
#!/usr/bin/env python from random import randint import csv import confidenceInterval import dateConvert #helper function to make set of random numbers #create an empty set and populate it with random numbers. #x is the number of numbers I want in the set. def randNums(x): randSet=set() while len(randSet)<...
4b8c836942110e10a11ac524573b2b4056eece7c
hjlarry/leetcode
/heap/heap_sort.py
401
3.53125
4
import random from adt import MaxHeap def heap_sort(arr): m = MaxHeap() result = [] for i in arr: m.add(i) for _ in range(len(arr)): result.append(m.extract()) return result def test_heapsort_reverse(): ll = list(range(10)) random.shuffle(ll) assert heap_sort(ll) == s...
5ffd02056ce98b921b8b376a722ce109752100a6
hjlarry/leetcode
/binarytree/adt.py
4,717
3.84375
4
""" 相关练习题 1. 第226题 翻转二叉树 https://leetcode.com/problems/invert-binary-tree/ 2. 第104题 求二叉树的最大深度 https://leetcode.com/problems/maximum-depth-of-binary-tree/ 3. 第112题 找一个路径上节点的和等于给定值 https://leetcode.com/problems/path-sum/ 4. 第144题 二叉树先序遍历 https://leetcode.com/problems/binary-tree-preorder-traversal/ 5. 第94题 二叉树中序遍历 https:...
f97ebcc156c4efa26381f3d0e5e65e9aa5300dd1
hjlarry/leetcode
/other/7.reverse-integer.py
1,399
3.796875
4
# # @lc app=leetcode id=7 lang=python3 # # [7] Reverse Integer # # https://leetcode.com/problems/reverse-integer/description/ # # algorithms # Easy (25.10%) # Total Accepted: 606.1K # Total Submissions: 2.4M # Testcase Example: '123' # # Given a 32-bit signed integer, reverse digits of an integer. # # Example 1: # ...
52fb5e46e93eb73c840b93b6a014708aa96a37b3
hjlarry/leetcode
/hashtable/706.design-hash-map.py
4,352
3.546875
4
# # @lc app=leetcode id=706 lang=python # # [706] Design HashMap # # https://leetcode.com/problems/design-hashmap/description/ # # algorithms # Easy (54.03%) # Likes: 350 # Dislikes: 59 # Total Accepted: 39.5K # Total Submissions: 69.7K # Testcase Example: '["MyHashMap","put","put","get","get","put","get", "remo...
e004214cb135668b88ace3d0f8ef636d33434d7f
hjlarry/leetcode
/heap/355.design-twitter.py
2,099
3.828125
4
# # @lc app=leetcode id=355 lang=python3 # # [355] Design Twitter # import collections import heapq # top voted solution # 使用列表, 94% # 使用deque, 85% class Twitter: def __init__(self): """ Initialize your data structure here. """ # self.tweets = collections.defaultdict(list) s...
da08ec7f402966f5a848a95295375b820fdc1657
hjlarry/leetcode
/linklist/141.linked-list-cycle.py
1,144
3.6875
4
# # @lc app=leetcode id=141 lang=python # # [141] Linked List Cycle # # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): # my solution, 73.69% # def hasCycle(self, head): # """ # ...
09b8e7e351751ab2bbe3807178150b36f91039b9
hjlarry/leetcode
/homework/4_4_server.py
913
3.59375
4
""" 4\. 使用多进程模块写一个使用优先级队列的例子 ``` ❯ python 4.py put :7 put :36 put :91 put :10 put :73 put :23 [PRI:7] 7 * 2 = 14 [PRI:10] 10 * 2 = 20 [PRI:23] 23 * 2 = 46 [PRI:36] 36 * 2 = 72 [PRI:73] 73 * 2 = 146 [PRI:91] 91 * 2 = 182 ``` 提示:用BaseManager共享queue.PriorityQueue """ # Server side from multiprocessing.managers import Bas...
8a4861edea8b6d88a03780ae959faf71c5e309ea
hjlarry/leetcode
/stack/num_converter.py
888
3.671875
4
from adt import ArrayStack print("示例一、 十进制转二进制") def divide_by2(num): remstack = ArrayStack() while num > 0: rem = num % 2 remstack.push(rem) num = num // 2 bin_str = "" while not remstack.is_empty(): bin_str = bin_str + str(remstack.pop()) return bin_str prin...
6bc8b56943b59bf8049310dcb740a84e88dbafff
hjlarry/leetcode
/other/14.longest-common-prefix.py
1,522
3.6875
4
# # @lc app=leetcode id=14 lang=python3 # # [14] Longest Common Prefix # # https://leetcode.com/problems/longest-common-prefix/description/ # # algorithms # Easy (32.95%) # Total Accepted: 421.5K # Total Submissions: 1.3M # Testcase Example: '["flower","flow","flight"]' # # Write a function to find the longest comm...
0dd7836cf9f3d44d7ae19a51d0ac6da000002493
titi9011/tp4_git
/Untitled-1.py
214
3.53125
4
def test(nombre): return nombre + 1 def boucle(nombre): ouverte = True while ouverte: nombre = test(nombre) print(nombre) if nombre == 10: ouverte = False boucle(2)
c3ab4a1cca397fcd4ba80aba802b71b34b496ec7
ShaamP/Snake
/snake.py
3,692
3.703125
4
import turtle import time import random delay = 0.075 #Set the screen window = turtle.Screen() window.title("Snake By Shaam") window.bgcolor("green") window.setup(width = 600, height = 600) window.tracer(0) #Turns off the screen updates #Snake head head = turtle.Turtle() head.speed(0) head.shape("...
35f9a1fc4c45112660f9cd871d1514b348990ddf
Jyun-Neng/LeetCode_Python
/103-binary-tree-zigzag-level-order.py
1,644
4.09375
4
""" Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ ...
da7b7caea279a8444cd63c43cabe65240ca21b57
Jyun-Neng/LeetCode_Python
/104-maximum-depth-of-binary-tree.py
1,301
4.21875
4
""" Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its depth = 3....
09036f2fb24f0e4b948ae75772f0419cbceb443c
Jyun-Neng/LeetCode_Python
/998-maximum-binary-tree.py
1,516
3.9375
4
""" We are given the root node of a maximum tree: a tree where every node has a value greater than any other value in its subtree. Just as in the previous problem, the given tree was constructed from an list A (root = Construct(A)) recursively with the following Construct(A) routine: If A is empty, return null. Otherwi...
2b9140d9f9ba91e321f456701f0d7e3776563f5f
Jyun-Neng/LeetCode_Python
/963-min-area-rect-II.py
1,565
3.828125
4
""" Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the x and y axes. If there isn't any rectangle, return 0. Input: [[3,1],[1,1],[0,1],[2,1],[3,3],[3,2],[0,2],[2,3]] Output: 2.00000 Explanation: The minimum area rectan...
6e784b269099a926400bc136e6810610a96a88ed
Jyun-Neng/LeetCode_Python
/729-my-calendar-I.py
2,328
4.125
4
""" Implement a MyCalendar class to store your events. A new event can be added if adding the event will not cause a double booking. Your class will have the method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start <= x ...
8d711c973ddf321c5179ece8b3148d9069461d77
Jyun-Neng/LeetCode_Python
/988-smallest-string-from-leaf.py
1,596
4.0625
4
""" Given the root of a binary tree, each node has a value from 0 to 25 representing the letters 'a' to 'z': a value of 0 represents 'a', a value of 1 represents 'b', and so on. Find the lexicographically smallest string that starts at a leaf of this tree and ends at the root. (As a reminder, any shorter prefix of a s...
cfa3efce6a57266795519d75ce8ce974125b80ca
ramosconde/03-Python-Homework
/pyPoll_homework.py
3,051
3.5
4
# import dependencies import csv import os #import print_function # define the path to the file file_path = os.path.join("PyPoll_Resources_election_data.csv") saveFile = open("PyPoll_output.txt", "a") vote_total = 0 #Row/total vote counter canidate_name = [] counter={} with open(file_path) as vote_data: #...
e0d5c5e157b386a9caeb626dea57ddea639237b1
Elizabethtown-College-CS-Club/feather
/app.py
2,133
3.5
4
from flask import Flask from flask import render_template, request, redirect, url_for, session app = Flask(__name__) app.debug = True app.secret_key = b'_MZqRP5HJE&M5mBXZ*pu3fnf8Um%?m$7' @app.route('/') def index(): """ This is the main landing page for logged in users. :return: If session is invalid th...
7c6b8efdef47a0bb5e406073402ae140a46d551c
yxl5521/CSCI631
/Project1/Project1/cnn_model.py
1,788
3.5625
4
import torch.nn as nn import torch.nn.functional as f class cnn_model(nn.Module): ''' The CNN model contains three convolutional layers, one fully connected layer and one output layer with 4 nodes. A kernel of size 5 with stride 1 is applied in each convolution layer. The first two convolutional layers are fo...
40663eb8f38f7a09cc049beacaf5aedd566b6441
charubak-chakraborty/DSPython
/LinkedList.py
576
3.921875
4
class Node(): def __init__(self,data=None): self.data = data self.next = None class LinkedList(): def __init__(self): self.head = None def display(self): ptr = self.head while ptr is not None: print(ptr.data) ptr = ptr.next def insertAtEnd...
7fabe025fdf1c8bdd5d69919cac47e53cbe9d295
vsofat/SoftDev
/Fall/03_csv/occupationPicker.py
917
3.671875
4
import csv import random # csv library makes reading the csv we have easier because there are "," in various spots and we can not simply split along the "," with open('occupations.csv') as csv_file: #code by Vishwaa, edited by kiran read = csv.reader(csv_file, delimiter = ",") dict = {} l = 0 for ...
06c42a6614395f56c07b5e5c918b9957368af93b
JoelPercival/BirthdaySurprise
/LishaProject.py
3,267
4.09375
4
#Birthday Hide and Seek Game print("welcome to my first game!") name = input("What is your name? ").lower() is_birthday = bool(input("Is today your birthday? (True/False) ")) if name == "lisha" and is_birthday is True: print("ITS YOUR BIRTHDAY!!") print("Hi Lisha, welcome to your birthday game!") print("i...
9fc8a137dc9da6ce31fde20a0f51d9ace0c54bed
Sangwan5688/python-scripts
/scripts/09_basic_link_web_crawler.py
886
3.578125
4
import requests import re try: from urllib.parse import urljoin except ImportError: from urlparse import urljoin # regex link_re = re.compile(r'href="(.*?)"') def crawl(url): """ Crawls a page Arguments: - URL of the page to crawl Return: - List of all unique li...
f5962331fe76396acd16fa9c170ae4d0024eab63
deepakdhull80/CP
/LinkList/is_palindrome.py
1,183
3.90625
4
class node: def __init__(self,data): self.data=data self.next=None class linklist: def __init__(self): self.head=None self.last=None def push(self,data): tmp=self.head if tmp==None: tmpi=node(data) print(tmpi.data) tmp=tm...
6fe310456b27adcf9c0f82036d063a0918ba071d
deepakdhull80/CP
/stack and queue/push_bottom.py
313
3.8125
4
stack=[1,2,3,4] stack1=[] def push_bottom(m): if len(stack)==0: stack.append(m) stack.append(stack1[len(stack1)-1]) stack1.pop() return stack1.append(stack[len(stack)-1]) stack.pop() push_bottom(m) if len(stack1)-1 >=0: stack.append(stack1[len(stack1)-1]) stack1.pop() push_bottom(0) print(stack)
4038b6ca7e62b6bd3b5ba7ef3cf01de2d3e8ee84
rishabh2811/Must-Know-Programming-Codes
/Series/Geometric.py
751
4.3125
4
# Geometric.py """ Geometric takes the first number firstElem, the ratio and the number of elements Num, and returns a list containing "Num" numbers in the Geometric series. Pre-Conditions - firstElem should be an Number. - ratio should be an Number. - Num should be an integer >=1. Geometric(firstElem=...
9407551d2fd6bea72683a890329ec86c880f4832
rishabh2811/Must-Know-Programming-Codes
/String Functions/string_times.py
458
4.09375
4
""" Given a string and a non-negative int n, return a larger string that is n copies of the original string. string_times('Hi', 2) → 'HiHi' string_times('Hi', 3) → 'HiHiHi' string_times('Hi', 1) → 'Hi' """ def string_times(given_str, times): print_str = '' while( times > 0 ): print_str += given_str ...
24eb50260ff182ad58f58665b2bbbe609a713f6b
manansharma18/BigJ
/listAddDelete.py
1,280
4.34375
4
def main(): menuDictionary = {'breakfast':[],'lunch':[], 'dinner':[]} print(menuDictionary) choiceOfMenu = '' while choiceOfMenu != 'q': choiceOfMenu = input('Enter the category (enter q to exit) ') if choiceOfMenu in menuDictionary: addOrDelete= input('Do you want to list, a...
bbb34bbef200e873645e45b50c095447587b2723
INST-326-Final-Project/FinalProject
/Final_Project_Life_Expectancy.py
7,447
3.921875
4
""" Script takes the users input and outputs information & data on a country. """ #Import necessary modules. from argparse import ArgumentParser import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as st import sys import seaborn as sns #Create the class class dframe: """Instantiate events...
2bee0aebaaab145385076c92f7b201ae913dfc78
fport/YazYap
/Kodlar/Ders-11/soru1.py
787
3.84375
4
def Toplama(x,y): return x+y def Cikarma(x,y): return x-y def Carpma(x,y): return x*y def Bolme(x,y): return x/y while True: print(""" Yapmak istediğiniz işlemi seciniz. *********** 1- Toplama 2- Çıkarma 3- Çarpma 4- Bölme *********** """) secim = int(input("Secim yapınız 1...
41de08e6122c24c905f11d1505c13e50d7f2aa8f
fport/YazYap
/Kodlar/Ders-7/example.py
3,837
3.875
4
# ödev """ kare olusturun ücgen olusturun """ sayi = int(input("bir sayi gir :")) for i in range(sayi): print(i,"🧐 " * (i)) """ sayi = int(input("bir sayi gir :")) for i in range(sayi): print("🧐 " * (sayi-i)) """ """ sayi = int(input("bir sayi gir :")) for i in range(sayi): print("🧐 " * (i)) """ """ ...
417606bce8499dea26f56607a4f4a1da66d4e85c
minh84/udacity_carnd
/CarND-P2-Traffic-Sign-Classifier/pipeline/data.py
7,755
3.53125
4
import numpy as np class BaseTransform(object): ''' A base class that used to pre-processing data e.g: convert RGB to Gray-scale RGB to YUV e.t.c ''' def __init__(self, transform_func = None): self._transform_func = transform_func def fit(self, training_inputs,...
8fd80cef949135e8942792458178dd5081f0fefd
clarek20/Programming-project
/api.py
11,571
3.671875
4
import pandas as pd import requests, json import matplotlib.pyplot as plt import matplotlib.dates as mdates import seaborn as sns def get_no_of_items_by_org(org, code): """ Specify a organisation code e.g 14L for Manchester CCG and a BNF code e.g 5.1 for Antibacterials. Will request the data in JSON format...
00821b437981b330cd9284c2bdf76ced2ac4c92f
iwob/pysv
/pysv/contract.py
13,492
4.03125
4
from pysv.interm import Var from pysv import utils def formula_test_cases_py(test_cases): """Transforms specified set of test cases into analogous Python expression. :param test_cases: List of tuples containing input and output expressions lists. :return: Logical formula encoding all test cases. INPUT =...
8f5a88a37e966df30ce17f70b98e0ee23c9db4d5
ShayBenIshay/decision-trees
/DT.py
4,366
3.59375
4
import time import pandas as pd from ID3_algorithm import ID3Alg from Temp_classes import * import numpy as np import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeClassifier def compute_accuracy(class_vector, true_class_vector): true_positive = 0 true_negative = 0 N = len(clas...
d6f7a02cd03634786a3bf5168094e7560044cd18
alexisanderson2578/Data-Structures-and-Algorithms
/SortingAlgorithms.py
1,400
4.125
4
def InsertionSort(alist): for i in range(1,len(alist)): key = alist[i] currentvalue = i-1 while (currentvalue > -1) and key < alist[currentvalue]: alist[currentvalue+1]= alist[currentvalue] currentvalue =currentvalue-1 alist[currentvalue+1] = key ...
9d23f7059bd46c0f35222ea55368df4a02d2997a
CVencode/LeetCode
/剑指offer/tree/55maxDepth.py
910
3.59375
4
# -*- coding: utf-8 -*- """ Creator: YJ Create time: 2020-06-27 Introduction:offer55--二叉树的深度 """ """DFS:后序遍历(递归)""" class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution1: def maxDepth(self, root): if not root...
b26cb3c067eb7103acc12095d2488c6bcc1f854e
rizkinabil/K-Nearest-neighbors
/Tupro_3_KNN.py
6,441
3.640625
4
import pandas import math dataset = pandas.read_excel('Dataset Tugas 3.xls') #fungsi normalisasi untuk data training def normalisasi(): data = [] for i in range(0, len(dataset)): data.append([ list_namaMobil[i], (list_ukuran[i] - list_ukuran.min()) / (list_ukuran.max() - list_ukuran.min()), (list_...
e3b44e845a6bebe3672dc6ac179f263b506b05dc
tiff178/assignment6
/graphics_v4.py
12,891
3.875
4
# Imports import pygame import math import random # Create functions def draw_cloud(x, y): '''This piece of code is the function to draw the clouds that stay consistent through the program param x: the value taken in for the smaller part of the ellipse shape of the cloud param y: the value taken in...
0e8709a8e836f347dbfdc431305a727a63317919
cmcginty/mktoc
/mktoc/progress_bar.py
2,730
4.03125
4
# Copyright (c) 2011, Patrick C. McGinty # # This program is free software: you can redistribute it and/or modify it # under the terms of the Simplified BSD License. # # See LICENSE text for more details. """ mktoc.progress_bar ~~~~~~~~~~~~~~~~~~ Module for mktoc that prints a progress indication. The...
9eb916239c5c51765ead312697f3a44418abed6e
Rupam-Shil/30_days_of_competative_python
/Day17.py
456
4.03125
4
'''There are 10 students in a class some students name are same to other students. Print the names that occur more than one time. All names should be in a single string Eg. str = 'Aman Ankit Deepak Arjun Nakul Amit Priyanshu Vansh Rajat Sagar''' str = input("Enter the name of 10 students separated with space: ") arr =...
eeb66edccf33599d4452f4f0223db3a1f76a69d3
Rupam-Shil/30_days_of_competative_python
/Day28.py
194
3.765625
4
''' Dave is 13, 772, 160 minutes old in age, can you calculate his age in year''' def min_to_year(m): return int(((m/60)/24)/365) print(f"Dave is {min_to_year(13772160)} years old.")
51cfcbe6f6bdbbe98025a4ef3ca07b052fdc8188
Rupam-Shil/30_days_of_competative_python
/Day13.py
665
3.828125
4
''' 5th Graders kara and Rani both have lemonade stands. Kara sells her lemonade at 5 cents a glass and Rani sells hers at 7 cents a glass. Kara sold K number of glasses of lemonade today and Rani sold r number of glasses. Who made the most money and by what amount? k and r are user entered value..''' k = int(input(...
0ab1712df48bd99d3e5c744138caaea015ca12e1
Rupam-Shil/30_days_of_competative_python
/Day29.py
496
4.1875
4
'''write a python program to takes the user for a distance(in meters) and the time was taken(as three numbers: hours, minutes and seconds) and display the speed in miles per hour.''' distance = float(input("Please inter the distance in meter:")) hour, min, sec = [int(i) for i in input("Please enter the time taken...
3852c4bd99b94a25a996387d8a7bf996f8824f80
samuelcheang0419/python-labs
/solutions/lab-6/lab-6.py
1,227
3.625
4
################################## # CONVERTING IMAGES TO ASCII ART ################################## import pandas as pd import numpy as np from PIL import Image import requests # Load the CSV into a pandas DataFrame # either download 'secret.csv' and run: d = pd.read_csv('secret.csv') # or: d = pd.read_csv(BytesI...
8e2a512b837a6e3005dc030d78fec1e62a60d23b
samuelcheang0419/python-labs
/solutions/lab-8/tree.py
1,147
3.96875
4
import pathlib NORMAL_CONTINUATION = '├── ' FINAL_CONTINUATION = '└── ' VERTICAL = '│ ' SPACER = ' ' def tree(directory): print(directory.name) tree_helper(directory, indent='') def tree_helper(file, indent): if not file.is_dir(): return children = list(file.iterdir()) if children: ...