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
a6ddff6674c46af7c320f625f023c2d1e20b396d
dustin181/javareference
/docs/python algorithms/mine/leetcode50/find_start_of_linked_list_cycle.py
951
3.890625
4
class ListNode: def __init__(self, x): self.val = x self.next = None def findCycle(head): slow = fast = head while fast and fast.next: fast = fast.next.next slow = slow.next if slow == fast: break if not fast or not fast.next: return None ...
da9db48b67eed5cf855d082d4a9a8e8cb091f801
dustin181/javareference
/docs/python algorithms/mine/leetcode50/find_median_of_stream.py
1,242
3.765625
4
from heapq import * class median_of_ages: maxHeap = [] minHeap = [] def insert_age(self, num): if not self.maxHeap or -self.maxHeap[0] <= num: heappush(self.maxHeap, -num) else: heappush(self.minHeap, num) if len(self.maxHeap) > len(self.minHeap) + 1: ...
ea029de53a728d7ac0c021f96a5e5df053a0e44d
dustin181/javareference
/docs/python algorithms/mine/leetcode50/lowest_common_ancestor_binary_tree.py
1,683
4.03125
4
from typing import Optional from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def __repr__(self): return str(self.val) def lowestCommonAncestor(root: Optional[TreeNode], p: Optio...
5a369f6dacd4f1abb5c7c776d5317f90c0081a3a
dustin181/javareference
/docs/python algorithms/mine/leetcode50/bfs.py
1,028
3.859375
4
from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def insertEdge(self, v1, v2): self.graph[v1].append(v2) def DFS(self, startNode): visited = set() st = [startNode] while len(st): cur = st[-1] ...
5a796e303c758e89249603eb61b8604fdf6e0e55
dustin181/javareference
/docs/python algorithms/mine/leetcode50/jump_game.py
338
3.734375
4
from typing import List def canJump(nums: List[int]) -> bool: last_position = len(nums) - 1 for i in range(len(nums) - 2, -1, -1): if (i + nums[i]) >= last_position: last_position = i # Since we just need to reach to this new index return last_position == 0 input = [2,3,1,1,4] pri...
6cc970fc780aec346382348ac43e9ced69d02383
dustin181/javareference
/docs/python algorithms/mine/leetcode50/contains_duplicates.py
438
3.890625
4
from typing import List def containsDuplicate(nums: List[int]) -> bool: n = len(nums) i = 0 tracker = {} while i < n: if nums[i] in tracker: return True else: tracker[nums[i]] = i i += 1 return False nums1 = [1,2,3,1] nums2 = [1,2,3,4] nums3 = [...
5fe7a7d1b5a79f4fc64e5057c95c88b7c520f65c
dustin181/javareference
/docs/python algorithms/mine/leetcode50/three_sum_smaller.py
767
3.921875
4
from typing import List def threeSumSmaller(nums: List[int], target: int) -> int: nums.sort() count = 0 for k in range(len(nums)): left, right = 0, k - 1 while left < right: if nums[left] + nums[right] + nums[k] < target: count += right - left le...
7c0c161c34ec4dbc4edf29a83f4c71eaaea59987
dustin181/javareference
/docs/python algorithms/mine/TDD/tuple_comprehension.py
96
3.703125
4
numbers = [1,2,3,4,5,6,7] new_tuple = tuple(t for t in numbers if t % 2 == 0) print(new_tuple)
656eafe6243c964063ca8cb4abc3fcff8d69da59
dustin181/javareference
/docs/python algorithms/mine/leetcode50/lowest_common_ancestor_binary_tree2.py
1,229
4
4
from typing import Optional from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def __repr__(self): return str(self.val) def lowestCommonAncestor(root: Optional[TreeNode], p: Optio...
2c4b4af12f95901785463695df59bd2d5b92136f
dustin181/javareference
/docs/python algorithms/mine/bitwise_xor/find_duplicate_number.py
170
3.546875
4
def find_single_number(arr): num = 0 for i in arr: num ^= i return num def main(): arr = [1, 4, 2, 1, 3, 2, 3] print(find_single_number(arr)) main()
81e85984309681953d37ba37f8cb324442d9fa31
dustin181/javareference
/docs/python algorithms/mine/TDD/temptest.py
528
3.734375
4
def square(x): return x * x def numberToStates(x): states = {4: "Delaware", 16: "Nevada"} if x in states: return states[x] else: return "not found" myList = [2,3,4,5] myList2 = [square(x) for x in myList] myList3 = [numberToStates(x) for x in myList2] print(myList) print(myList2) prin...
70d226dab92cd2853d0a148c1e7f06ff2ef2321e
dustin181/javareference
/docs/python algorithms/mine/leetcode50/valid_mountain_array.py
605
3.8125
4
from typing import List def validMountainArray(arr: List[int]) -> bool: length = len(arr) if length < 3: return False i = 1 while i < length and arr[i] > arr[i - 1]: i += 1 if i == 1 or i == length: return False while i < length and arr[i] < arr[i-1]: i += ...
75190038c1658038554534b04a7e1942f80f48a8
pepelasa/hello-world
/Lab3/Lab33.py
5,843
3.765625
4
import unittest file_name = "directory.txt" class directory(): # def __init__(self, name, email, age, country): # self.name = name # self.email = email # self.age = age # self.country = country def addRecord(name, email, age, country): if not isinstance(name...
bfb24a739c79bffb1f60dbb54481ceb9ecd13ceb
BoynChan/Python_Brief_lesson_answer
/Char7-Import&While/char7.1.py
511
4.125
4
car = input("What kind of car do you want to rent?: ") print("Let me see if I can find you a "+car) print("------------------------------") people = input("How many people are there?: ") people = int(people) if people >= 8: print("There is no free table") else: print("Please come with me") print("-----------...
be1c832239fc5c42a1c0c0171ed80ae45742e596
BoynChan/Python_Brief_lesson_answer
/Char10-File&Error/char10.3.py
847
3.921875
4
print("---Give me teo number---") print("---I will give the sum--") print("---Press '0' to exit----\n") while True: try: num1 = input("Number 1:") num1 = int(num1) except ValueError: print("Can't enter text") continue else: if num1 == 0: break try: ...
2b50b338ffb8cdc4f5d55b11951979ac27300c10
BoynChan/Python_Brief_lesson_answer
/Char8-Function/char8.3.py
775
4.09375
4
def city_country(city, country): place = city + "," + country return place city1 = city_country('guangzhou', 'china') print(city1) print("------------------------------") def make_album(singer_name, album_name, numbers=''): songs = {'Singer Name': singer_name, 'Album Name': album_name} ...
b10c5d94748b90b0561402c353976a83d4b65fa3
2n2n/python_udemy
/python_refresher/variables_methods.py
429
3.5
4
a = 5 b = 10 my_variable = 56 my_10_variable = 10 any_variable_name = 10 string_variable = "hello" single_quotes = 'strings can have single quotes' #print(my_variable) #print(string_variable) ## def my_print_method(my_parameter): print(my_parameter) #my_print_method("Hello, world!") def my_multiply_method(number...
529402a5a5de14174db8206be4d1d24cef30396b
veshhij/prexpro
/cs101/homework/1/1.9.py
422
4.21875
4
#Given a variable, x, that stores #the value of any decimal number, #write Python code that prints out #the nearest whole number to x. #You can assume x is not negative. # x = 3.14159 -> 3 (not 3.0) # x = 27.63 -> 28 (not 28.0) x = 3.14159 #DO NOT USE IMPORT #ENTER CODE BELOW HERE #ANY CODE ABOVE WI...
1964d8f2e0d201ff2babd06a9918607b01c93ea8
veshhij/prexpro
/cs101/homework/2/2.4.py
373
3.96875
4
# Define a procedure, countdown, that takes a # positive whole number as its input, and prints # out a countdown from that number to 1, # followed by Blastoff! def countdown( n ): if n < 1: return while 0 < n: print n n = n - 1 print 'Blastoff!' #-----------------...
ba5a8a6281771377b23757f465b1f74edccc0ca7
rilwal/Hack-Assembler
/symbol_table.py
845
4.0625
4
class SymbolTable: """ This class is used for the symbol table. """ def __init__(self): """ Creates a new empty symbol table. """ self.table = { "sp": 0x0000, "lcl": 0x0001, "arg": 0x0002, "this": 0x0003, "that": 0x0004, ...
8fdf7b5c6996cff692bf1cf6efc22367665ed480
shraddhakushwaha/cyber-security
/volume.py
89
4
4
r=float(input("enter the value of radius:")) volume=4.0/3.0*3.14*pow(r,3) print(volume)
20f0ff07c7e1d3df9b46ad9d2e449a2916c6e419
bm3719/practice
/python/pi_lab/5_rgb_led.py
1,200
3.609375
4
# Make LED cycle through random RGB colors. import RPi.GPIO as GPIO from time import sleep from random import randint pins = {"red": 11, 'green': 12, 'blue': 13} def setup(): global pwmRed, pwmGreen, pwmBlue GPIO.setmode(GPIO.BOARD) # Use physical board numbering. GPIO.setup(list(pins.values()), GPIO...
c32bedb643c75697f97d9d567720a203183a461a
bm3719/practice
/python/lpthw/ex29.py
729
4.03125
4
people = 20 cats = 30 dogs = 15 if people < cats: print "Too many cats! The world is doomed!" if people > cats: print "Not many cats! The world is saved!" if people < dogs: print "The world is drooled on!" if people > dogs: print "The world is dry!" dogs += 5 if people >= dogs: print "People ...
66d175778f291adcef24f21f1f95697ed9d85af6
bm3719/practice
/python/pi_lab/4_analog_pwm.py
800
3.5625
4
# Make LED fade in/out import RPi.GPIO as GPIO from time import sleep ledPin = 33 def setup(): global pwm GPIO.setmode(GPIO.BOARD) # Use physical board numbering. GPIO.setup(ledPin, GPIO.OUT) # Set the ledPin to OUTPUT mode. GPIO.output(ledPin, GPIO.LOW) pwm = GPIO.PWM(ledPin, 500) # Set P...
6c10c4d6360ac5ebe4bf129e49e10c3f6f49db0e
bm3719/practice
/python/lpthw/ex20.py
750
4.03125
4
from sys import argv script, input_file = argv def print_all(f): print f.read() def rewind(f): f.seek(0) def print_a_line(line_count, f): print line_count, f.readline() current_file = open(input_file) print "First let's print the whole file:\n" print_all(current_file) print "Now let's rewind, kind o...
a6865286d63f4389d3534d532531f98db9f702f5
bm3719/practice
/python/pi_lab/1_blink.py
758
3.734375
4
import RPi.GPIO as GPIO import time ledPin = 11 def setup(): GPIO.setmode(GPIO.BOARD) # Use physical board numbering. GPIO.setup(ledPin, GPIO.OUT) # Set the ledPin to OUTPUT mode. GPIO.output(ledPin, GPIO.LOW) # Make ledPin output LOW level. print('Using pin' + str(ledPin)) def loop(): whil...
b193f350666a9a5d296c1bf0906bcb841efb444d
oelnenimmat/physics-sim
/geometry.py
503
3.6875
4
from numpy import matmul from math import pi from math import cos, sin import maths def regularPolygon(numPoints): # Make sure to rotate clockwise R = maths.rotation(-1 * 2 * pi / numPoints) vertices = [] # Use homogeneous coordinates vertex = [0, 1, 1] for i in range(numPoints): verti...
f694bca698b848d41d4c2145807feae34d6f8835
PacktPublishing/Natural-Language-Processing-Python-and-NLTK
/Module 2/Chapter 1/7853OS_01_codes/chapter1.py
9,126
3.8125
4
""" ============================== Tokenizing Text into Sentences ============================== >>> para = "Hello World. It's good to see you. Thanks for buying this book." >>> from nltk.tokenize import sent_tokenize >>> sent_tokenize(para) ['Hello World.', "It's good to see you.", 'Thanks for buying this book.'] >>...
448fd19ed2ef52e2294b9cb8a1792d19f940d880
Heez27/python-basics
/practice02/05.py
294
3.671875
4
# 함수 s를 만드세요. 이 함수는 임의의 개수의 인수를 받아서 그 합을 계산합니다. # def s(*arg): # return sum(arg, 0) def s(*arg): result = 0 for n in arg: result += n return result print(s()) print(s(1, 2)) print(s(1, 2, 5, 7, 2, 3))
42fba80658b8dfac714eb3ac167256c24138e523
Heez27/python-basics
/03/range.py
334
3.953125
4
# range # seq = range(0, 10, 1) seq = range(10) print(seq, type(seq)) for i in seq: print(i, end=' ') else: print('') for i in range(5, 15): print(i, end=' ') else: print('') for i in range(0, 10, 2): print(i, end=' ') else: print('') for i in range(0, -10, -1): print(i, end=' ') else: ...
3ebe34a84dced2da2dd210256e0213ba2fdf39a4
Heez27/python-basics
/03/operator-logical.py
804
4.28125
4
# 논리연산자 (not, or, and) a = 30 b1 = a <= 30 # not # not True -> False # not False -> True b2 = not b1 # or(논리합) # False or False -> False # True or False -> True # False or True -> True # True or True -> True b3 = (a <= 30) or (a >= 100) # and(논리곱) # False and False -> False # True and False -> False # False or True...
87eda1397f9f0e3e694edc8cbadee4cdf38107d2
Heez27/python-basics
/03/str.py
3,473
4.09375
4
# 한줄 문자열 리터럴 s1 = 'Hello World' s2 = "Hello World" print(s1, type(s1), type(s2)) # 여러줄 문자열 리터럴 print('========== Multi-line String Literal ==============') # s3 = 'Hello\nworld' s3 = """Hello world """ print(s3) # 여러줄 주석을 대신하여 사용할 수 있다 """ 주석1 주석2 주석3 """ # escape(\붙어있는 문자) print('================= escape ==========...
feed7cfb959c7e730800202979eff5669d466f61
subahm/Guessing-
/Guessing.py
638
4.0625
4
from random import randint guesses = 0; number = randint(0,30) print("You will get 5 attempts to guess a number between 0 to 30") while guesses < 5: print("Take a guess.") guess = input() guesses = guesses + 1 if guess < number: print("Your guess is too low") if guess > number: print("Yo...
33f2c5721233820859f3eb9f5664e0caebee6439
silviodeigiudici/AD_Code
/ex5.py
2,448
3.6875
4
class MySet: def __init__(self): self.set = set() #in order to do side effect on the set def union(self, new_set): #new_set is a MySet instance, not a set standard instance self.set = self.set.union(new_set.set) def add(self, elem): self.set.add(elem) def __str__(self...
79bf67cb2f66661a013c0b0cacf7f153460ff6fb
fldragonn/pygame
/py_minesweeper/recursive01.py
210
3.9375
4
# recursive call # # recursive01.py # 재귀함수 def hello(cnt): # 재귀 종료 조건 if cnt == 0: return print('hello, recursive!', cnt) cnt = cnt - 1 hello(cnt) hello(3)
8bee81938c98df974b97cbc3c0876e5b32cd1c35
fcdwg/Code
/snapchat/time.py
1,011
3.6875
4
import sys def number_of_digits(hour, minute, sec): used = set() nums = [hour, minute, sec] for x in nums: if x / 10 not in used: used.add(x / 10) if x % 10 not in used: used.add(x % 10) if len(used) <= 2: return True return False def add_one(hour, minute , sec): carry = 0 if sec + 1 == 60: carry =...
a7eaab722cf023a8f956017e0293fd2b0032c035
fcdwg/Code
/google_interview/01tree.py
1,194
3.609375
4
from collections import deque class TreeNode: def __init__(self,v): self.val = v self.left, self.right = None, None class Zero_One_Tree: def __init__(self, s): self.q = deque() for e in s: self.q.append((TreeNode(e), 0)) def generate(self): if not self.q: return None while len(self.q) > 1: l, le...
4fb2c85051c38754ce3620f1583b5a5c5ef6bce0
fcdwg/Code
/snapchat/toddle.py
1,061
3.734375
4
class ListNode: def __init__(self, value): self.val = value self.prev = None self.next = None class Sender: def __init__(self): self.table = {} self.head = None self.tail = None def toddle(self, v): if v not in self.table: new_node = ListNode(v) if self.head is None: self.head = new_node ...
67752a7742ec7157fc73cc678de0694074b589de
Dhaour9x/cSLAM
/Yaml Converter/MakeROSMap.py
4,189
3.546875
4
import math import os.path import cv2 # # This is a start for the map program # import pywt.tests.data.generate_matlab_data #import pywt prompt = '> ' print("What is the name of your floor plan you want to convert to a ROS map:") #file_name = eval(input(prompt)) file_name = input(prompt) print("You will need to ch...
794692d632d689aa10433987bdc91ad04a7dbfde
DraftiestHat/whiteElephantChooser
/main.py
1,585
3.515625
4
#!/usr/bin/python import argparse import string import random import re import sys parser = argparse.ArgumentParser(description='Takes lists of people and randomly matches them with other people. You can also have another file of people that are disallowed from giving each other things.',fromfile_prefix_chars='@') par...
004facdb680b2f9ff0492588d649a3f7b3489335
MiccWan/python-challenge
/src/p01.py
576
3.71875
4
from string import ascii_lowercase def caesar(plaintext, shift): alphabet = ascii_lowercase shifted_alphabet = alphabet[shift:] + alphabet[:shift] d = {} for i in range(len(alphabet)): d[alphabet[i]] = shifted_alphabet[i] return ''.join(map(lambda x: d.get(x, x), plaintext)) msg = """g fm...
01ccaa78ebe6cc532d8caca853365d8d05f29b22
francomattos/COT5405
/Homework_1/Question_08.py
2,021
4.25
4
''' Cinderella's stepmother has newly bought n bolts and n nuts. The bolts and the nuts are of different sizes, each of them is from size 1 to size n. So, each bolt has exactly one nut just fitting it. These bolts and nuts have the same appearance so that we cannot distinguish a bolt from another bolt, or a nut fro...
f50d27b0f425199214581842e8a1913eaa35f3b1
LeeMax117/LeetCode_practise
/Jinglong/robb.py
1,420
3.796875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # below two dicts used to store the current node's max value # to avoid duplicated computing. node_dict1 = {} node_dict2 = {}...
db0682bd8033187a2ec73514dd2d389fb30ff2d0
wpiresdesa/hello-world
/stable/PowerOf2.py
639
4.5625
5
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ # Add this line today - 29/October/2018 11:08Hs # Add another line (this one) today 29/October/2018 11:10Hs # Add another line (this one) today 29?october/2018 11:18Hs # Python Program to display the powers of 2 using anonymous function # Change this value for a differe...
efe543c68cd0c434bc46586c4e2246d92255064a
drewbrew/advent-of-code-2019
/day01.py
489
3.515625
4
from math import floor with open('input1.txt') as infile: lines = infile.read().split('\n') inputs = list(int(i.strip()) for i in lines if i.strip()) def fuel(module): return floor(module / 3) - 2 def part_two(module): needed_fuel = fuel(module) total = needed_fuel while needed_fuel > 0: ...
0eb02567f446894a0fef487d556626ab2b7e83dd
frsojib/python
/Anisur/list2.py
183
3.546875
4
subject = ['c','f','d','g','e'] subject.append('boss') subject.insert(2,'guru') subject.remove('c') subject.sort() subject.reverse() subject.pop() pos = subject.index('d') print(pos)
fa5ff543127811bd8e535d337f8d1e7d65b1bf24
frsojib/python
/Code with herry/05_average.py
65
3.5625
4
a = int(input()) b = int(input()) avg = (a + b)/2 print(int(avg))
74230ef4f22a17ac8f0472f6bccb8a76251e084b
frsojib/python
/Anisur/set.py
249
4.0625
4
num1 = {1,2,3} num2 = set([4,5,6]) # function for set num2.add(7) num2.remove(7) num1.clear() print(num1) print(num2) print(7 in num2) # operation in set print(num1 | num2) #union between two sets print(num1 & num2) #intersection between two sets
88074bfed63c071d5aa3558c1a9fe1798b3af34c
frsojib/python
/Code with herry/07_tamplate.py
225
4.4375
4
letter = ''' Dear <|NAME|>, You're selected! Date <|DATE|> ''' name = input('Enter your name: ') date = input('Enter date: ') letter= letter.replace("<|NAME|>", name) letter= letter.replace("<|DATE|>", date) print(letter)
92701d6d0bb44d90148cca6b2f8dfe24346f892e
frsojib/python
/Anisur/function intro.py
161
3.734375
4
def add(x,y): sum = x+y print(sum) def multiply(x,y,z): math = x*y*z print(math) multiply(10,55,66) add(10,20) add(5,20) add(10,25) add(15,20)
123b5bf7e281461dc517f0c517127ab268d61c95
SaliouMbalo/simplon-p2-saliou
/projet-python/boucle_nombre_aleatoire.py
432
3.921875
4
from random import randint nombre_genere = randint(0, 9) chance = 3 while chance > 0: nombre = int(input("Veuillez entrer un nombre compris entre 0 et 9: ")) if nombre == nombre_genere: print ("Bravo, le nombre entré correspond à celui généré!") break elif nombre != nombre_genere: ...
4fc9c3595ddcbe3b8d20996178af30bc30e9f00c
leenatomar123/loop
/perfect number.py
203
3.8125
4
num=int(input("enter the number")) b=num a=1 sum=0 while a<num: if num%a==0: sum+=a a+=1 if sum==b: print(b,"is perfect number") else: print(b,"is not perfect number")
650919e645b7a619cd63c17fc3698ad8d7372daf
leenatomar123/loop
/fibonic series.py
135
3.9375
4
num=int(input("enter a num")) a=0 b=1 sum=0 count+=1 while count<=num: print(sum,end="") count+=1 a=b b=sum sum=a+b
98ed9be141e1a19b29fce3f4359612f51ed039db
mleue/project_euler
/problem_0072/python/e0072.py
2,164
3.8125
4
from itertools import combinations from factorize import get_prime_factors, primes_set def calc_product(*args): """Return product of args.""" product = 1 for arg in args: product *= arg return product def number_of_reduced_fractions(prime_factors, thresh): """Return number of reduced fractions with de...
cb80ab1f5972ae2884a0e3080c8fbb3d6e52e3f9
mleue/project_euler
/problem_0043/python/e0043.py
874
3.90625
4
from itertools import permutations def check_divisibility(number_str, check_ranges): """return True if number_str can be divided in all check_ranges a check range is a tuple (substr_start, substr_end, divisor)""" for substr_start, substr_end, divisor in check_ranges: #-1 because the given ranges are 1-bas...
d974cd6b8c7f5e8ea7672f0e935acac30dbd82a9
mleue/project_euler
/problem_0052/python/e0052.py
840
4.15625
4
def get_digits_set(number): """get set of char digits of number""" return set((d for d in str(number))) def is_2x_to_6x_permutable(number): """check if all numbers 2x, 3x, 4x, 5x, 6x contain the same digits as number""" digits_set = get_digits_set(number) multipliers = (2, 3, 4, 5, 6) for m in multipliers:...
58ebdea5bb5f9c6a4b1370a11111c7662ef7ebcd
mleue/project_euler
/problem_0004/python/test.py
2,335
3.5625
4
import unittest from e0004 import is_palindromic, create_palindromic_numbers, largest_palindromic_number_as_product, is_product_of_two_n_digit_numbers, get_number_of_digits class Test0004(unittest.TestCase): def test_is_palindromic_correct_examples(self): """it should get some correct example palindromes right""...
0763ff301d76da0d99843f66acacfea50987a289
mleue/project_euler
/problem_0024/python/e0024.py
228
3.53125
4
from itertools import permutations if __name__ == '__main__': nth = 1000000 pool = '0123456789' print("The {}th lexicographic permutation of {} is {}" .format(nth, pool, ''.join(list(permutations(pool))[nth-1])))
2cd2556ea0e7650c9804935ddc96e4a664aa2786
mleue/project_euler
/problem_0007/python/test.py
522
3.734375
4
import unittest from e0007 import prime_generator, nth_prime class Test0007(unittest.TestCase): def test_prime_generator(self): """it should generate the known sequence of primes below 30""" test_case = ([2,3,5,7,11,13,17,19,23,29], 30) self.assertEqual(list(prime_generator(test_case[1])), test_case[0])...
0e030106466e85ab289a6194b06fc557595822f6
mleue/project_euler
/problem_0092/python/e0092.py
819
3.828125
4
precomputed_digit_squares = {str(n): n**2 for n in range(10)} def square_digit_sum(number): """Return the sum of the square of the digits of a number, e.g. 32 -> 13.""" return sum(precomputed_digit_squares[digit] for digit in str(number)) # TODO speed up if __name__ == '__main__': assert square_digit_sum(44) ...
15ef581fb3755a06f15ab3b19494daa0c58fff6b
mleue/project_euler
/problem_0008/python/e0008.py
1,001
3.96875
4
import re import functools def import_number_string(filename): """import the 1000 digit number for this question from file as a string""" with open(filename, 'r', encoding='utf-8') as f: return re.sub(r'[^\d]', '', f.read()) def all_n_char_substrings(string, n): """returns generator for all n-char substring...
ff4159c0bca4b3cc50dbd0a9c79e85aee8e73cd5
mleue/project_euler
/problem_0003/python/test.py
552
3.65625
4
import unittest from e0003 import largest_prime_factor, prime_numbers class Test0003(unittest.TestCase): def test_prime_numbers(self): """it should generate the known sequence of primes below 30""" test_case = ([2,3,5,7,11,13,17,19,23,29], 30) self.assertEqual(list(prime_numbers(test_case[1])), test_case...
b6eb5f56b67634036a43c6408894214af6c06ce4
mleue/project_euler
/problem_0016/python/e0016.py
211
4.0625
4
def digit_sum(n): """sum up n's digits""" return sum((int(digit) for digit in str(n))) if __name__ == '__main__': n = 2**1000 print("The sum of the digits of {} is {}" .format(n, digit_sum(n)))
51c67d7e981f3020d0da3aa74c16b9005248b970
mleue/project_euler
/problem_0025/python/e0025.py
335
3.96875
4
def fib(): """an infinite fibonacci generator""" a, b = 1, 0 while True: yield a a, b = a+b, a if __name__ == '__main__': l = 1000 fibonacci = fib() count = 1 while len(str(next(fibonacci))) < l: count += 1 print("The {}th is the first fibonacci number with at least {} digits." .for...
9c19ebb4092e34d434d200487334b80af1806334
mleue/project_euler
/problem_0050/python/e0050.py
944
3.75
4
import time def prime_sieve(thresh): """return a list of primes below thresh""" is_prime_lookup = {n: True for n in range(2, thresh)} for n in range(2, thresh): if is_prime_lookup[n]: for i in range(n+n, thresh, n): is_prime_lookup[i] = False return sorted((n for n, is_prime in is_prime_look...
ca7b7fa19be848ad772dc18ef2c458307b1adaf3
mleue/project_euler
/problem_0053/python/e0053.py
501
3.5625
4
def factorial(n): """return n!""" if n == 0: return 1 else: return n * factorial(n - 1) def n_combinations(n, r, factorials): """return number of combinations from n and r""" return factorials[n] // (factorials[r] * factorials[n-r]) if __name__ == '__main__': thresh = 1000000 factorials = {n: fa...
82973a7a9c0513c07327a5b621024312628d3a31
btrekkie/batch
/src/batch/shared_generator.py
5,229
3.90625
4
import sys from gen_result import GenResult class SharedGenerator(object): """Provides the ability to safely yield a Generator from multiple places. SharedGenerator hides the difficulties associated with yielding a single batchable generator from multiple function calls. Sample usage is as follows:...
10d87d4658a799e35d52fd40358ab9f46778caf8
gunit84/Code_Basics
/Code Basics Beginner/ex5_lists.py
611
3.75
4
#!python3 # Lists Learning expenses = [2200, 2350, 2600, 2130, 2190] febdiffJan = expenses[1] - expenses[0] # a) print("In February we spent ${} more dollars then January!".format(febdiffJan)) # b) totalExpense = expenses[0] + expenses[1] + expenses[3] print("The total expenses for the first quarter is ${}.".forma...
4ff167bec52d0c1ab4196536b6ec81be4f3d13fe
gunit84/Code_Basics
/Code Basics Beginner/ex20_class_inheritance.py
1,288
4.34375
4
#!python3 """Python Class Inheritance... """ __author__ = "Gavin Jones" class Vehicle: def general_usage(selfs): print("General use: transportation") class Car(Vehicle): def __init__(self): print("I'm Car ") self.wheels = 4 self.has_roof = True def specific_usage(self)...
aefbb26fdbb2c4d2b7420cdaaa2f0abd8cc8e9ef
gunit84/Code_Basics
/Code Basics Beginner/ex28_Multithreeading_before.py
715
4.0625
4
#!python3 """Python3 Multithreading... """ __author__ = "Gavin Jones" import time # Calculate the square of Numbers def calc_square(numbers): print("calculate square numbers") for number in numbers: time.sleep(0.2) print("squares: ", number * number) print() # Calculate the Cube of th...
a4cbca54fefaf0d53b211eb63c34575c2d99bfdd
gunit84/Code_Basics
/Code Basics Beginner/ex11_functions2.py
292
3.921875
4
#!python3 """Basic Function for addition... """ __author__ = "Gavin Jones" def sum(a, b): """A function about sum""" return a + b # The Sum Result sumResult = sum(3, 4) print("The result of the sum is {}".format(sumResult)) # Call the docstring funcHelp = help(sum) print(funcHelp)
9ccec78a2031229a5abba1f14ad16bf3f5f858b8
gunit84/Code_Basics
/Code Basics Beginner/ex10_4.py
242
4.03125
4
#!python3 """Print square of numbers 1 to 5 EXCEPT even Numbers... """ __author__ = "Gavin Jones" for number in range(1, 6): if number % 2 == 0: continue else: print("Odd Number Squared {}:".format(number), number ** 2)
d10ced02db8f0c93bd026b745cf916c1519fe4ef
gunit84/Code_Basics
/Code Basics Beginner/ex21_class_multiple_inheritance.py
572
4.46875
4
#!python3 """Python Multiple Inheritance Example... """ __author__ = "Gavin Jones" class Father(): def skills(self): print('gardening, programming') class Mother(): def skills(self): print("cooking, art") # Inherits from 2 SuperClasses above class Child(Father, Mother): def skills(se...
dfcb3fdc1097921c915fd274de30709b0b296d1a
gunit84/Code_Basics
/Code Basics Beginner/ex24_generators.py
311
3.796875
4
#!python3 """Python3 Information about Generators... """ __author__ = "Gavin Jones" def remote_control_next(): yield "cnn" yield "espn" itr = remote_control_next() print(next(itr)) print(next(itr)) # Runs a for loop on the actual generator function. for item in remote_control_next(): print(item)
5325093f17c9d2bf1a3a6914762a80f1e35d5c01
prasanthkp89/MTA_98-381_Intro_to_Programming_Using_Python
/Lesson 2-3.py
3,149
4.4375
4
# Define and call Functions # Basic Function Syntax: # def function_name(args): # statements # Remember: # Don't forget def or the colon. # Indentation is important (discussed next). # args is zero or more arguments. # Function Example: def pr_values(a, b, c): print('a is', a) print('b is', b) print('...
abeff0ad607b967669befa6734ece65bbcb88f43
sugengpriyanto/rock-paper-scissors
/main.py
1,013
4.0625
4
import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ...
12a7da2b3332e10ffd87ff76ba3a2125060083ef
wanggao1990/PythonProjects
/= Fishc bbs/43 魔法方法 算术运算2.py
2,213
4.15625
4
# int()、float()、str()、len()、tuple()、list() 等函数调用时,就创建一个相应的实例 ####### 算术运算符 ## ## __add__(self, other) 定义加法的行为:+ ## __sub__(self, other) 定义减法的行为:- ## __mul__(self, other) 定义乘法的行为:* ## __truediv__(self, other) 定义真除法的行为:/ ## __floordiv__(self, other) 定义整数除法的行为:// ## __mod__(self, other) 定...
717960af26b7ea86826098d33ca68b9e7ca2bced
wanggao1990/PythonProjects
/= Fishc bbs/34 简洁的else 和 while 语句.py
1,782
3.671875
4
# else 可以和while语句搭配使用 def showMaxFactor(num): # 最大公约数 count = num //2 while count>1: if num % count == 0: print("%d的最大公约数是%d" %(num,count)) break count -= 1 else: # 整个while循环都执行了一遍,没有break print('%d是素数' % num) num = int(input(...
48026881d3c45fcb1b1d5b4e0c55af58a0fdb0fd
wanggao1990/PythonProjects
/= Fishc bbs/18 函数参数.py
2,328
3.671875
4
####### 函数参数 def my_add(num1,num2): '这个是函数文档, 通过.__doc__调用, 或者 help(func_name)查看' if not isinstance(num1,(int,float)) or not isinstance(num2,(int,float)): return return num1+num2 def my_sum(r): sum = 0 for i in r: sum += i return sum print(my_add.__doc__) # 打印函数说明文档,位于def行下的第一...
64aa1163557a4251ce8a3fb6db090700dd82eb6b
wanggao1990/PythonProjects
/= Fishc bbs/8 for in range.py
1,806
3.828125
4
#元组、列表 都是容器 name = 'wang gao' for i in name: print(i,sep = ' ',end=' ') # print(value, ..., sep=' ', end='\n', # 默认分隔符为空格,end=默认每个取值后添加换行符 print() member = ['abc','defg','hijkl'] #列表 len(member) # 元素的个数,3 for each in member: print(each, len(each)) # 每个元素长度 for i in range(1,101): ...
f1f60ca62925b1aca5207890f69260829d1944cc
wanggao1990/PythonProjects
/= Fishc bbs/53-63 爬虫/61 网络爬虫9 异常处理.py
1,051
3.8125
4
# 网络异常处理 URLError ,其子集 HTTPError (同时捕捉是,将HTTP放在前面检测) import urllib.request import urllib.error ## req = urllib.request.Request("http://www.baidu.com") try: urllib.request.urlopen(req) except urllib.error.URLError as e: print(e.reason) else: print('conneted!') # 没有错误抛出时执行。 ## req = urllib.r...
50a71ddfe001c5a76ce6a9d06ee9940adce44761
wanggao1990/PythonProjects
/= Fishc bbs/22-24 递归: 阶乘、斐波那契数列、汉诺塔.py
2,020
4.0625
4
########## 递归: 阶乘、斐波那契数列、汉诺塔 ##### 阶乘 n! ### # 方法一 迭代 def factorial_1(n): result = n for i in range(2,n): result *= i return result print(factorial_1(20));print(); # 方法二 递归 def factorial_2(n): if n == 2 : return 2 else: return n*factorial_2(n-1) print(factorial_2(20))...
98888d25ea574d342d4a9b3d79854bdb27f09447
wanggao1990/PythonProjects
/= Fishc bbs/16 序列(str,list,tuple转换) 序列运算.py
2,155
4.46875
4
# list、tuple、str 统称 序列(能迭代) # 1 通过索引获得 # 2 默认索引值都是从0开始 # 3 分片方法获得元素的集合 # 4 操作符 (重复 拼接 关系) ## str,tuple => list # 不带参数 空列表 a = list(); print(a) # str转list,str每个字符都成为list元素 ['1', 'a', '2', 'b', '3', 'c'] a='1a2b3c'; a= list(a); print(a) # tuple转list,每个元素都成为list元素 [1, 1, 2, 3, 5, 8, 13, 21] a=(1,1,2,3,5,8,13,21); a= ...
f35826bb279c55f7827a258a9ff63e7b4ae8171d
edgemund/ANN-Backward-Progation-with-Animated-Graph
/Logistic Regression on Data 1/MLP.py
3,997
3.578125
4
############################################################################ # LOGISTIC REGRESSION # # Note: NJUST Machine Learning Assignment. # # Task: Logistic Classification # ########...
e841913c1f2c05a0094dcbb3ac7ce77e84d5c9a2
lilsweetcaligula/sandbox-online-judges
/leetcode/easy/valid_anagram/py/solution.py
434
3.5625
4
# # Anagram definition: # https://en.wikipedia.org/wiki/Anagram # # Classic solution to the anagram problem. Sort both strings # and check if they are equal. # # Time complexity depends on the sorting algorithm # but we can have O(n log n) at best. # class Solution(object): def isAnagram(self, s, t): """...
803bc00f33eacfba6ce509ef9224f3e756d5bea8
lilsweetcaligula/sandbox-online-judges
/leetcode/easy/swap_nodes_in_pairs/py/solution.py
1,365
3.890625
4
# # Another approach to solve the problem still makes use # of the dummy node technique, however this time around # we do not actually append to the "dummy"-headed list's # tail. Instead we use the dummy to accommodate the "prev" # pointer on the first iteration of the loop. The "prev" # pointer points to the last node...
2be847aec885eed2e2ba73e506af22c46d2e175f
lilsweetcaligula/sandbox-online-judges
/leetcode/easy/guess_number_higher_or_lower/py/solution.py
659
3.75
4
# The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): class Solution(object): def guessNumber(self, n, lo=0): """ :type n: int :rtype: int """ if lo >= n: ...
184d9ebdcd5132606f1e2ad75a76824990e8a75d
lilsweetcaligula/sandbox-online-judges
/lintcode/easy/count_and_say/py/count_and_say.py
691
3.625
4
# coding:utf-8 ''' @Copyright:LintCode @Author: lilsweetcaligula @Problem: http://www.lintcode.com/problem/count-and-say @Language: Python @Datetime: 17-02-15 14:07 ''' class Solution: # @param {int} n the nth # @return {string} the nth sequence def countAndSay(self, n): def helper(n, s='1'): ...
bd19551e8fdb8d896cae6ccb17ebe0a7b652cab0
lilsweetcaligula/sandbox-online-judges
/hackerrank/algorithms/strings/easy/game_of_thrones_i/py/solution.py
343
3.515625
4
def solution(source): import collections counter = collections.Counter(source) parities = tuple(counter[char] % 2 == 0 for char in counter) if len(source) % 2: return parities.count(False) == 1 return all(parities) s = input().strip() if solution(s): print('YES')...
464e83f211c6f1d7e7126ec1fb4c6ca1866c701f
lilsweetcaligula/sandbox-online-judges
/hackerrank/algorithms/implementation/easy/repeated_string/py/solution.py
422
3.671875
4
#!/bin/python3 import sys def repeated(s, n, c='a'): lookup = [0] * len(s) curcnt = 0 for index, char in enumerate(s): if char == c: curcnt += 1 lookup[index] = curcnt if n % len(s) == 0: return n // len(s) * curcnt return n // len(s) * curcnt + look...
18ccef8281d46711f3b0b115713e86a3227d38f7
lilsweetcaligula/sandbox-online-judges
/leetcode/easy/missing_number/py/solution.py
343
3.53125
4
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ ordered = sorted(nums) for index, value in enumerate(range(ordered[-1] + 1)): if value != ordered[index]: return value ...
5b3ae06bb5ab6d7fbedf32e70113462324728453
lilsweetcaligula/sandbox-online-judges
/leetcode/easy/number_of_segments_in_a_string/py/solution.py
528
4.125
4
# # In order to count the number of segments in a string, defined as # a contiguous sequence of non-space characters, we can use the # str.split function: # https://docs.python.org/3/library/stdtypes.html#str.split # # Given no parameters, the string is split on consecutive runs of # whitespace and produce a list of...
e7cf338e6f2a013921be458b4882f836f4dd403a
lilsweetcaligula/sandbox-online-judges
/leetcode/easy/palindrome_linked_list/py/solution.py
478
3.6875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ values = [] node = ...
80e5adbdcb0cf56f35ea9676103e5dad73771473
lilsweetcaligula/sandbox-online-judges
/leetcode/easy/move_zeroes/py/solution.py
1,633
4.125
4
# # We use a slow/fast pointer technique. The fast pointer (index) is running ahead, # reporting whether the value it is pointing to is a zero value or not. # # If nums[fast] is not a zero value, we copy the value to nums[slow] and increment # the slow pointer. This way, by the time the fast pointer reaches the end of...
bcc7f1a9cad612f2608c384291200cd2b30bbb9d
lilsweetcaligula/sandbox-online-judges
/leetcode/easy/find_all_numbers_disappeared_in_the_array/py/solution.py
1,528
3.8125
4
# # The functional approach to this problem would be to use a hash set. A set will # eliminate all duplicates in the array as well as all numbers already present in # the array via set.difference method. # # First thing we have to do, however, is to pinpoint the range. The problem spec # states that the range is defi...
f1ec4f075c7b6f12c0a610549b3cd0eeb7106300
lilsweetcaligula/sandbox-online-judges
/leetcode/easy/contains_duplicate/py/solution.py
494
3.9375
4
# # An interesting approach to the problem of finding a duplicate # in an array can be the following. # # We use a set to rid the array of duplicates and compare its # length to the original length of the array. If the original # array happens to have a greater length, then we definitely had # the duplicates. # class ...
8ade08f71e8ab075f9d1e183396beb6f462abc96
lilsweetcaligula/sandbox-online-judges
/leetcode/easy/single_number/py/solution.py
1,053
3.921875
4
# # The functional approach we could use to locate the single number is # to group the numbers by value and return the group with only a single # number in it. # # The caveat to the groupping approach is we need a sorted array for # best performance - O(n log n). Hence: itertools.groupby(sorted(nums)) # # A more costl...
9258fc9db7d8297b616ed2f26df827556ae67479
ConConRob/Breakout
/src/block.py
2,084
3.53125
4
import pygame from pygame.math import Vector2 from pygame import Rect class Block: """ Base class for square or rectangular object """ def __init__(self, position, width, height, color): # Create a rectangle centered around the x and y self.position = position self.rectangle =...
ddf5d794e295055e7290905bd7d01800c598d283
jian-en/imooc-holdem
/poker.py
5,662
3.90625
4
def card_ranks(hand): """ """ # dict mapping ranks = ['--23456789TJQKA'.index(r) for r,s in hand] ranks.sort(reverse=True) # what to change # return ranks return [5, 4, 3, 2, 1] if ranks == [14, 5, 4, 3, 2] else ranks def straight(ranks): "Return True if the ordered ranks form a 5-c...
dbc869209a77dbdce1d63cbc172f011a1f5aa9af
peterKlivnoy/BlackJack
/player.py
2,207
3.703125
4
import decks import random class Player: def __init__(self, name): self.hand = [] self.val = [] self.aces = self.val.count(1) self.name = "Player "+str(name) self.total = sum(self.val) def take_bet(self): self.bet = int(input(f'Hvor mye vil...