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
2594e6b33ded0bb45324826fc3366143fd075141
hg19991220/myproj
/kao2.py/ti4.py
726
3.6875
4
if __name__ == '__main__': klist = [ "good ", "good ", "study", " good ", "good", "study ", "good ", " good", " study", " good ", "good", " study ", "good ", "good ", "study", " day ", "day", " up", " day ", "day", " up", " day ", "day", " up", ...
16d4717d55ec21bdcb2f618b1e8a7983fddfd0ee
hg19991220/myproj
/day2/chongfu.py
683
3.65625
4
if __name__ == '__main__': klist = [ "good ", "good ", "study", " good ", "good", "study ", "good ", " good", " study", " good ", "good", " study ", "good ", "good ", "study", " day ", "day", " up", " day ", "day", " up", " day ", "day", " up", ...
cc817a4efd7e18bebdc9f9ebf9f79d470c4bfd9e
hg19991220/myproj
/day3/lx1.py
936
3.78125
4
if __name__ == '__main__': #数据源 klist = [ "good ", "good ", "study", " good ", "good", "study ", "good ", " good", " study", " good ", "good", " study ", "good ", "good ", "study", " day ", "day", " up", " day ", "day", " up", " day ", "day", " up"...
a131829e5f9ef5f6cd8868b61912ff146b69e3b4
tiandrioni/python
/lesson3/lesson3-5.py
1,695
3.59375
4
""" Программа запрашивает у пользователя строку чисел, разделенных пробелом. При нажатии Enter должна выводиться сумма чисел. Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа вводится специал...
30308e649cd535fdaf8dde99e24d3d00c1061104
tiandrioni/python
/lesson2/lesson2-1.py
201
3.546875
4
big_list = [0, True, 2.0, [3, ], (4, ), {5}, '6', {7: 8}] for element in big_list: el_type = str(type(element)).split("'")[1] print(f'Элемент {element} имеет тип {el_type}.') input()
2f288985a6f9a652688bf2112a8fb5599a60080d
tiandrioni/python
/lesson4/lesson4-5.py
728
4.3125
4
""" Реализовать формирование списка, используя функцию range() и возможности генератора. В список должны войти четные числа от 100 до 1000 (включая границы). Необходимо получить результат вычисления произведения всех элементов списка. Подсказка: использовать функцию reduce(). """ from functools import reduce def mu...
4cf91a43cd5ec949c06980b244a0abba7cf3321b
ToriiLab/CreLox
/Sample Distribution Generator.py
7,867
3.625
4
#Generates sample point probablistic distributions relative to a sector # and calculates the sector-point correlation function relative to a #uniformly random point distribution. import numpy as np; import matplotlib.pyplot as pyplot; import random; import math; import shapely.geometry as shg; ''' Begin section for ...
61908ac4a42e640b2b920cbbd4e5c5a6aad2d07b
mike373/Sortable
/sortable_test.py
7,264
3.734375
4
''' Michael Bearden Sunday June 21 2015 Sortable coding chalange files products.txt and listings.txt should be placed in same directory as this file, sortable_test.py. Results will be printed to file in the same directory in results.txt ''' import sys class Product: # Ba...
e484433c1128bbfd420a7b170c5d638caec8d431
PikaKight/Calculator
/equations/physic_eq.py
4,195
3.734375
4
import typing, math class Base_velocity_equation: def velocity(self, d:float, t:float) -> float: self._velocity = d / t return self._velocity def distance(self, v:float, t:float) -> float: self._distance = v * t return self._distance def time(self, v:float, d:float) -> flo...
c997dd390c7e9419f18d3e7a9122c28b2d82cef1
ChangePlusPlusVandy/change-coding-challenge-jstallings2
/twitter-game.py
6,033
3.859375
4
""" This file contains a script that runs a game that allows the user to specify two Twitter users, load their tweets, then displays tweets randomly and asks the user to identify which user tweeted each tweet. The game ends when the user runs out of their initial 3 lives. @author Jacob Stallings Last updated 9/25/20 D...
79319a0a370a2bba58d80dd5810856566d49704d
JimGilmour/python
/lesson3_easy1.py
294
3.96875
4
def qwerty(a, b, c): d = a + b + c return d a = 'Василий,' b = '21 год,' c = 'Проживает в городе Москва' result = qwerty(a, b, c) print(result) # Старался использовать пройденное ранее, но не получалось
95ffbc7e0a8de37f65271ec209ec9d0e4bc43958
BilalZQ/Face-Recognition-Snippet
/detector.py
1,337
3.546875
4
import cv2 import numpy as np subjects = ["", "random1", "random2", "Barack Obama" , "", ""] imagePath = 'd.jpg' #cascPath = sys.argv[2] # Create the haar cascade faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') rec = cv2.face.LBPHFaceRecognizer_create(); rec.read("C:\\Users\\Bilal\\Desktop...
5138f943edb6d3af8e827ff7c288175a39782992
mchlrhw/aoc
/python/aoc/year_2018/day_09/__init__.py
2,269
3.75
4
from dataclasses import dataclass from typing import Any @dataclass class Node: anticlockwise: Any clockwise: Any marble: int class Circle: def __init__(self): self.root = Node(None, None, 0) self.root.anticlockwise = self.root self.root.clockwise = self.root self.cur...
92606a13b6888228a896262657710d427b4da0fc
inwk6312fall2019/wordplay-Chintan1491
/9.3.py
359
3.671875
4
#prog 9.3 def avoids(word,forbidden): for letter in word: if letter in forbidden: return False return True fin = open('words.txt') count = 0 forbidden_letters = input('Enter any forbidden letters: ') for line in fin: word = line.strip() if avoids(word, forbidden_letters) == ...
e0f361a4f715ca02f869bf24d1f9a0c9f5008c06
froesecom/SwervinMervin
/swervin_mervin/util.py
392
3.703125
4
from pygame.font import Font def limit(v, low, high): """Returns v, limited to low/high threshold""" if v < low: return low elif v > high: return high else: return v def render_text(text, window, font, color, position): """Renders a font and blits it to the given window""" ...
dd3f2d3cfa51f1d49b1bea63cfa18bf877393b0c
poojithaganta/sololearn-solutions
/sololearn python/easy/pro/guard flamingos/guard_flamingos.py
68
3.59375
4
perimeter = 2*(int(input()) + int(input())) print(int(perimeter/2))
ba796eb4b2e3288275da19e6cc213d8a045cd0b7
poojithaganta/sololearn-solutions
/sololearn python/easy/free/jungle camping/jungle_camping.py
289
3.6875
4
sound = input().split(" ") out = [] for noise in sound: if noise=="Rawr": out.append("Tiger") if noise=="Grr": out.append("Lion") if noise=="Ssss": out.append("Snake") if noise=="Chirp": out.append("Bird") print(" ".join(out))
22f031af0c15458895ac471c0e2e4f3b10c3ba77
Kendoll10/My-tkinter-Program
/Example3.py
1,699
3.78125
4
# this is a desktop converter app that converts year into seconds, minutes etc... from tkinter import * window = Tk() def years_converter(): seconds = float(e1_value.get()) * 31536000 minutes = float(e1_value.get()) * 525600 hours = float(e1_value.get()) * 8760 days = float(e1_value.get()) * 365 ...
f5c5d034ca85c7b226611192c26a4cb8a9aa02bc
RonDingDing/Algorithm4th
/leetcode/数据结构/队列与广度搜索优先/279.完全平方数.py
1,383
3.75
4
# 给你一个整数 n ,返回 和为 n 的完全平方数的最少数量 。 # 完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,1、4、9 和 16 都是完全平方数,而 3 和 11 不是。 #   # 示例 1: # 输入:n = 12 # 输出:3 # 解释:12 = 4 + 4 + 4 # 示例 2: # 输入:n = 13 # 输出:2 # 解释:13 = 4 + 9 #   # 提示: # 1 <= n <= 104 import math from 数据结构.队列与广度搜索优先.队列 import ListQueue as Queue class Solution:...
71fbb9b1da94b7bd6052c900c5f123fb77a084a2
RonDingDing/Algorithm4th
/leetcode/数据结构/循环/29.两数相除.py
2,181
3.765625
4
# 给你两个整数,被除数 dividend 和除数 divisor。将两数相除,要求 不使用 乘法、除法和取余运算。 # 整数除法应该向零截断,也就是截去(truncate)其小数部分。例如,8.345 将被截断为 8 ,-2.7335 将被截断至 -2 。 # 返回被除数 dividend 除以除数 divisor 得到的 商 。 # 注意:假设我们的环境只能存储 32 位 有符号整数,其数值范围是 [−231, 231 − 1] 。本题中,如果商 严格大于 231 − 1 ,则返回 231 − 1 ;如果商 严格小于 -231 ,则返回 -231 。 # 示例 1: # 输入: dividend = 10, div...
d8077291c60c2f7d030e597a548a6e00f80b7e45
RonDingDing/Algorithm4th
/leetcode/数据结构/链表/21.合并两个升序列表.py
1,518
4.0625
4
from typing import List, Optional # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __repr__(self) -> str: cur = self string = "" while True: if cur is None: break ...
d041a717ec4b7937aa8712c750f0112470c03440
RonDingDing/Algorithm4th
/leetcode/数据结构/动态规划/12.爬楼梯.py
945
3.703125
4
# 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 # 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? # # 示例 1: # 输入:n = 2 # 输出:2 # 解释:有两种方法可以爬到楼顶。 # 1. 1 阶 + 1 阶 # 2. 2 阶 # 示例 2: # 输入:n = 3 # 输出:3 # 解释:有三种方法可以爬到楼顶。 # 1. 1 阶 + 1 阶 + 1 阶 # 2. 1 阶 + 2 阶 # 3. 2 阶 + 1 阶 # # 提示: # 1 <= n <= 45 class Solution: storage = [0, 1, 2] def climbStair...
19d945f2f6ea70445b696089e85a9bac0886e990
AlexHinojosaRubio/Examen
/EjercicioRepasoFunciones15.py
899
4.03125
4
def calculadora(): operacion= input("Que operacion quieres") a = float(input("Escribe un número")) b = float(input("Escribe otro número")) sum = a+b rest = a-b multi = a*b div = a/b residuo = a/b%2 if operacion == "suma" or operacion=="Suma" or operacion == "SUMA": print ("El...
0ddb9093b999c6a916c8432f4285a87598432016
gregorybutterfly/scripts
/filename-changer.py
1,845
3.84375
4
"""Change the name of your favorite files in bulk. Copy your files to 'images' directory and run the script with name argument. >> python filename-changer.py -n NEWNAME >> python filename-changer.py -n 'NEW NAME WITH SPACES' """ import os import argparse __AUTHOR__ = 'Grzegorz Motyl' __PYTHON_VER__ = 'Python 3.5.2'...
c6cda2c6f183a38a17621f043c8fe57f61eb3980
leekylej/emailer
/Email_Sender_1.4.4.1.1.py
2,638
3.875
4
#! python3 # This program sends out personalized, plain text emails from a csv file. # The csv has to have all fields filled out. # The list has to have a header row with the following: First Name, Full Name, Username, Domain. # Have to have python 3.7 and pandas installed. # Make sure the current directory is ...
6a0b6f550fbd00cf80b035789b7364626d2b55d1
wesleyhooker/assign1
/ccpin.py
1,355
4.40625
4
#!/usr/bin/env python3 """ Validates that the user enteres the correct PIN number """ def valid_input(input): """ Checks for valid PIN Number Argument: input = the users inputted PIN Returns: Any Errors with the input TRUE if it passes, False if it doenst """ if(len(inp...
b1746f5a447ee0bb232094005a2710426374a4ee
toku345/RayTracerChallenge_Python
/raytracerchallenge_python/helpers.py
160
3.53125
4
EPSILON = 0.00001 def equal(a, b): """ Comparing Floating Point Number""" if abs(a - b) < EPSILON: return True else: return False
f365b31b78b46ca9c95fd064410034ec58aec612
erickrex/python-cheatsheet
/multidimensional_lists.py
784
3.546875
4
menus = [['Egg Sandwich', 'Bagel', 'Coffe'], ['BLT', 'PB&J', 'Turkey'], ['Soup', 'Salad', 'Spaghetti', 'Taco']] print('Breakfast menu:\t', menus[0]) print('Lunch menu:\t', menus[1]) print('Dinner menu:\t', menus[2]) menus_list = {'Breakfast': ['Egg Sandwich', 'Bagel', 'Coffe'], 'Lunch': ['BLT', 'PB&J', 'Turkey'], 'D...
54b0cd187220630c9595697f368626aab13fe0c9
p2w34/wlips
/scripts/compute_file_hash.py
471
3.84375
4
import argparse from scripts.src.file.FileHash import FileHash parser = argparse.ArgumentParser( description="Calculate SHA-3 hash of a file in hex form and outputs least significant 8 characters.", epilog="Example: python3 scripts/compute_file_hash.py -f wlip-0003/english-a1d03317-obsolete") parser.add_argume...
9e3ab4a69570dbfa2ef0d5e63e97279ec6dfbe2b
rajesh-priyadarshi/python-scripts
/if_else_even_odd_number_check.py
173
4.1875
4
# program for Even odd number check for each in range(1,11): if each%2 == 0: print(f'{each} is even number') else: print(f'{each} is odd number')
6e392e89f14b3e7b52116349b329f7b7e583c0c6
Sindhujapranav/guvi
/add.py
215
4
4
#You are given Two Numbers, A and B. If C = A + B. Find C. def add(): #getting two numbers from the user A=int(input()) B=int(input()) # adding the values we get from user C=A+B return C ans=add() print(ans)
409d44d99831d77f51423a09aa08febae48248a9
Sindhujapranav/guvi
/looping/multiplication_table.py
175
4.0625
4
# MULTIPLICATION TABLE a=int(input("Enter the value to display your table:")) print("The Muultiplication table of no:",a) for i in range(1,11,): print(a,'*',i,'=',a*i)
6defae7ca24cec51e30519ef97a8df38f72b1718
Sindhujapranav/guvi
/codekata/absolute beginner/factorial.py
142
3.90625
4
#getting the input as N from the usser N=int(input()) fact=1 #factorial of the number for i in range(1,N+1): fact=fact*i print(fact)
585ac856c6627cfbce6db9baa8c47bd1cc18128d
jeffvswanson/DataStructuresAndAlgorithms
/Stanford/06_Selection/Randomized/test_selection_algorithm_example.py
694
3.765625
4
import selection_algorithm_example as sa import unittest class TestSelectionAlgorithm(unittest.TestCase): def test_swap(self): """ Test that swap function will swap values in a list. """ data = [1, 2] result = sa.swap(data, 0, 1) self.assertEqual(result, ...
e56abf20dfb145e05de7108ca27c8f36f0eedce7
jeffvswanson/DataStructuresAndAlgorithms
/Stanford/ProgrammingQuestion6_HeapsSearchTreesAndHashTables/Question2a_HeapMedianMaintenance/heap.py
5,416
4.40625
4
# heap.py class Node: """Node represents where a value goes in the heap""" def __init__(self, value): self.node = value class Heap: """ Heap represents the heap data structure. Default heap kind is a min-heap, unless 'max' denoted. """ def __init__(self, kind=...
384cb75137c4702da88da4a227e2af8c72f3a0a8
jeffvswanson/DataStructuresAndAlgorithms
/Stanford/10_BinarySearchTrees/red_black_node.py
2,069
4.25
4
# red_black_node.py class Node: """ A class used to represent a Node in a red-black search tree. Attributes: key: The key is the value the node shall be sorted on. The key can be an integer, float, string, anything capable of being sorted. instances (int): The number o...
2e5a06126a45a34352b3e4ab1219700d9db86d1d
jeffvswanson/DataStructuresAndAlgorithms
/Stanford/09_HeapSort/test_heap_sort.py
5,398
3.5
4
# test_heap_sort.py import copy import heap_sort as hs import unittest class TestHeapSort(unittest.TestCase): def test_get_parent_index(self): """ Test to ensure proper parent index is returned. """ # Remember the 0 is a place-holder and heap has a 1-based index. ...
99bdd7a719174906e6494050465d1782c099604e
H-Yous/pythonTraining
/python/section 3: Functions/dataStructures.py
2,296
3.90625
4
import pprint, random theBoard = {'top-l': ' ', 'top-m': ' ', 'top-r': ' ', 'mid-l': ' ', 'mid-m': ' ', 'mid-r': ' ', 'low-l': ' ', 'low-m': ' ', 'low-r': ' '} done = False pprint.pprint(theBoard) def createBoard(): print(theBoard['top-l'] + ' | ' + theBoard['top-m'] + ' | ' + theBoard['top-r']) print('-- --- --')...
10a86672400793c6ace2ccce31e1f40bb59054e6
oda9/python-play-ground
/play-ground/janken.py
1,109
3.796875
4
# -*- coding: utf-8 -*- import sys import random JANKEN = {"p":"パー", "c":"チョキ", "g":"グー"} def main(player): if player != "p" and player != "c" and player != "g": print("正しい文字を入力してください。") else: cpu = ["p", "c", "g"][random.randint(0, 2)] print("あなたの手は" + JANKEN[player] ...
8ca5f332dd43e2c73985116a49fe8bec77ca5639
Joaquim10/openfoodfacts
/views/category_view.py
930
3.8125
4
#!/usr/bin/python3 # -*- coding: UTF-8 -*- """ category_view: category_view contains the CategoryView class. Classes: CategoryView: The CategoryView object processes the category view. Methods: display_categories(categories): Displays the specified categories and returns the prompt. """ class Cate...
addf53ccadd359e5dba82a223b33121254448459
JCarr172/pythonexercises
/Exercise5.py
393
3.796875
4
x = input('Please enter numbers seperated by spaces') x = x.split(' ') xint = [] N = 0 for i in range(0,len(x)-1): if x[i].isdigit() == True: xint.append(int(x[i])) else: N = 1 if N == 1: print('Not everything was a number') else: print(xint[0], xint[-1]) print(xint + xint) pri...
39b7d31a5d2a55ec2f5fcb8c87f5dff75fc1a340
JCarr172/pythonexercises
/whileloop.py
132
3.953125
4
x = 0 name = [] while x < 5: name.append(input('What is your name? ')) x += 1 for x in name: print(f"{x} is awesome")
bc413069cadcff3286a539b4ff7f821588885180
JCarr172/pythonexercises
/easy_tasks/near.py
244
3.578125
4
def near(x,y): for i in range(0,len(x)): z = '' if i == 0: z = x[1:] elif i == len(x)-1: z = x[:-1] else: z = z + x[:i] z = z + x[i+1:] return(z == y)
e9e5351e782b1c890fcade2fc6d7c6f0b341db7c
AuburnFord/kattis
/Python/peasoup.py
358
3.875
4
def main(): restaurants = int(input()) flag = True for _ in range(restaurants): items = int(input()) menu = set() name = input() for i in range(items): menu.add(input()) if "pea soup" in menu and "pancakes" in menu: print(name) flag = False break if flag: print("Anywhere is fine I guess") ...
6c3c684f3c6baf4c4a99deffba4596b0337c7fe4
AuburnFord/kattis
/Python/parsingHex.py
440
3.609375
4
def validNum(c): if c <= 0x39 and c >= 0x30 or c >= 0x41 and c <= 0x46: return True return False def main(): while True: try:#how line = str(input()) except: break i = 1 while i < len(line): if line[i-1:i+1].upper() == "0X": j = i + 1 while j < len(line) and j - i <= 8 and validNum(ord(l...
c7e9a4c1b9ac8abb4d14d454d3ef523293d3b8ba
parastuffs/adventofcode-2020
/Day-01/Jesus.py
392
3.546875
4
def findThem(values): a = b = 0 for i,value in enumerate(values): a = value for subvalue in values[i+1:]: b = subvalue if (a+b) == 2020: return a,b if __name__ == "__main__": with open("input", 'r') as f: values = f.readlines() values = [x.strip("\n") for x in values] values = list(map(int, valu...
103f9ffeba49887f4e2540a19deccf84247ab27e
parastuffs/adventofcode-2020
/Day-10/Present.py
375
3.578125
4
with open("input", 'r') as f: lines = f.readlines() lines = [x.strip("\n") for x in lines] values = list(map(int, lines)) values.append(0) values.append(max(values)+3) values.sort() diff3 = 0 diff1 = 0 for i, value in enumerate(values[1:]): if (value - values[i]) == 1: diff1 += 1 elif (value - values[i]) == 3: ...
8000c2a7ae9a6a3ab2bcc9bd425b9ce04a630487
intangere/Genetics
/examples/find_numbers.py
895
3.859375
4
########################################### # Genetic Algorithim to # # Find values that add up to a number # # By Intangere # ########################################### from genetics import Genetics, Individual World = Genetics(100) #Define a world where the goal is t...
0df8bc76b8032de39bddf7272220230e370b9219
meir367612/File_Project_oop
/SuperFile.py
494
3.546875
4
class SuperFile: def __init__(self, name:str, content:str,who_created:str,description:str,file_size:int): self.name = name self.content = content self.who_created = who_created self.description = description self.file_size = file_size def __str__(self): return "na...
b3a2b5b71dc6e02a429fa4400071fb6395f23eaa
angelaoj04/respostas-listas
/tarefa01.py
161
4.0625
4
numeros = [] for i in range(5): numero = int(input("Informe o {}º numero: ".format(i+1))) numeros.append(numero) for i in numeros: print(i)
24f638bb070ffa900d346adf355fa7dd70ae62a2
innovationcode/stack-queue
/stack.py
558
4.0625
4
class Stack(object): def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] def printStack(self): ...
6deacd6d58cfe6d47f47f6090c445d576a92f196
icicchen/PythonGameProgramming
/Onboarding - easy.py
575
3.96875
4
# Onboarding - easy '''This program shoots the closest enemy ships by comparing distances between the ship and mine. CodinGame planet is being attacked by slimy insectoid aliens.''' import sys import math while 1: enemy_1 = input() # name of enemy 1 dist_1 = int(input()) # distance to enemy 1 enemy_2 =...
48d5cceebb8342eab2e8c0a18554b15a46ee4a29
icicchen/PythonGameProgramming
/solarSystemLib.py
4,127
3.984375
4
import pygame import random import math # -- definition of the config variables backgroun_color = (255,255,255) (width, height) = (1000, 400) class Particle(): ''' creates a particle object ''' num_particles = 0 def __init__(self, x, y, size, color=(255,255,255), angle=math.pi/2, speed=1, mass=1...
5fd2e1ce1bb2dd34be5958f80787f04a4b0dcacf
icicchen/PythonGameProgramming
/Power of Thor - episode 1.py
2,073
4.46875
4
# Power of Thor - easy '''This program allows Thor to reach the light of power by giving it directions''' import sys import math # light_x: the X position of the light of power # light_y: the Y position of the light of power # initial_tx: Thor's starting X position # initial_ty: Thor's starting Y position light_x, l...
7d272d9d3f97dea3b5842439f0914b952c9d57b2
icicchen/PythonGameProgramming
/Dictionary.py
1,074
4
4
'''This program is a dictionary between French and English, translate the English numbers to French, vice versa''' # Add the number up to ten to the dictionary english2french = {'one':'un','two':'deux','three':'trois','four':'quatre','five':'cinq','six':'six','seven':'sept','eight':'huit','nine':'neuf', 'ten':'dix'} #...
b2424f0a85a2de11a5ed5bb3d45be87ba6ebe897
icicchen/PythonGameProgramming
/Combo Box.py
1,079
3.59375
4
''' This is a program that displays a text file contains the names and prices available at a certain store. Read the text file in Python and show the items using a Widget QTComboBox. ''' import sys from PyQt5.QtWidgets import QApplication, QWidget, QComboBox class comboBox(QWidget): def __init__(self): s...
8f8f2b00b1ab42447c02d17f6d933d174c970117
gd1035/FunWithPrimes
/primes.py
545
4.03125
4
from math import sqrt import time N = int(input("Enter the number of primes you would like to calculate: ")) begin = time.time() primes = [2,3,5,7] possiblePrime = 11 while len(primes) < N: isPrime = 1 for j in primes: if (j*j == possiblePrime) | (j > sqrt(possiblePrime)): break if possiblePrime % j ==...
71847e9eb2f36bc059a18fa75bb9541db03f6dd9
kyle10n/hackerrank
/print_function.py
332
3.640625
4
if __name__ == '__main__': n = int(input()) empty_list = [] counter = 0 while counter < n: empty_list.append(counter) counter = counter + 1 empty_list.append(n) new_string = map(str,empty_list) new_string = ''.join(new_string) new_number = int(new_string) print...
d49012d69cc584bd49642b6f3c7ada3085715d56
alastair-droop/scientific-computing-2015
/count-bases.py
696
3.765625
4
#! /usr/bin/env python # This script shows how we can open and read files in python. from sys import argv, exit try: # Try to open the file: f = open(argv[1], "r") except: #If there is an error, give up: print("ERROR: Failed to open input file") exit(1) # Set up the data: bases = ['A', 'C', 'G', ...
2c6883f73522c971670cae797200f454968a635f
Neeragrover/HW04
/HW04_ex00.py
1,265
4.21875
4
#!/usr/bin/env python # HW04_ex00 # Create a program that does the following: # - creates a random integer from 1 - 25 # - asks the user to guess what the number is # - validates input is a number # - tells the user if they guess correctly # - if not: tells them too high/low # - only lets t...
3ec08d9e5985e5ab19eae234835ae990bd31d8ac
lamngockhuong/python-guides
/basic/dictionaries/dictionaries-1.py
1,106
4.46875
4
# https://www.w3schools.com/python/python_dictionaries.asp thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) x = thisdict["model"] print(x) y = thisdict.get("model") print(y) # Change values thisdict["year"] = 2019 print(thisdict) # Return values of a dictionary for x in ...
c317ce84cfe9396ec35d95e66de2722295a88103
lamngockhuong/python-guides
/basic/lists/lists-4.py
166
4.125
4
# https://www.w3schools.com/python/python_lists.asp thislist = ["apple", "banana", "cherry"] if "apple" in thislist: print("Yes, 'apple' is in the fruits list")
524b7612faa6b189b228d9f8e6aca0f69fbf6364
lamngockhuong/python-guides
/basic/strings/strings-2.py
497
4.375
4
# https://www.w3schools.com/python/python_strings.asp x = "Hello, world!" print(x[2:5]) y = " Hello world " print(y.strip()) # remove any whitespace from the beginning or the end print(len(y)) # return the length of a string print(y.lower()) # return the string in lower case print(y.upper()) # return the strun...
97151b5c5f3c33aafa412f9149a9c94f05d9da7c
lamngockhuong/python-guides
/basic/lists/lists-7.py
139
3.734375
4
# https://www.w3schools.com/python/python_lists.asp thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist)
d77c6a7f30610c677feee045a40c14fbd5f3603d
sprax/1337
/python3/l0098_validate_binary_search_tree.py
492
3.78125
4
from common import TreeNode class Solution: def isValidBST(self, root: TreeNode) -> bool: def is_valid_bst(root: TreeNode, min_val: float, max_val: float) -> bool: if not root: return True if root.val <= min_val or root.val >= max_val: return False ...
b95842d11a5f92ec67ca4c3805fe19dc47cc8d55
sprax/1337
/python3/l0075_sort_colors.py
576
3.734375
4
from typing import List class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ p0, p2, p = -1, len(nums), 0 # p0 points to last 0; p2 points to first 2 while p < p2: if nums[p] == 0: ...
17ac7c933dde318586872ec6665d1340cbf3d044
sprax/1337
/python3/l0173_binary_search_tree_iterator.py
1,073
3.640625
4
from common import TreeNode class BSTIterator: def __init__(self, root: TreeNode): self._stack = [] self._current = root self._next = self._getNext() def next(self) -> int: """ @return the next smallest number """ next = self._next self...
1664978925297f98ba8cec7bb158496f240d2ed9
sprax/1337
/python2/l0166_fraction_to_recurring_decimal.py
1,101
3.671875
4
class Solution(object): def fractionToDecimal(self, numerator, denominator): """ :type numerator: int :type denominator: int :rtype: str """ sign = '' if numerator*denominator < 0: sign = '-' numerator = abs(numerator) denom...
b5c49b0d6f7e9843243d20fb030fddb78ca447cb
sprax/1337
/python2/l0337_house_robber_3.py
775
3.640625
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 rob(self, root): """ :type root: TreeNode :rtype: int """ def rob(ro...
da515c54f60ee198388bfe038181e09185210f93
sprax/1337
/python3/l0310_minimum_height_trees.py
923
3.59375
4
from collections import defaultdict from typing import List class Solution: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: nodes = set(range(n)) node_map = defaultdict(list) for e in edges: node_map[e[0]].append(e[1]) node_map[e[1]].append...
aee21d805c25c41248edd58a35decfe2f5083bd7
sprax/1337
/python3/l0143_reorder_list.py
573
3.65625
4
from common import ListNode class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ stack = [] p = head while p: stack.append(p) p = p.next p = head num_to_li...
27cdaf8ebd80c91fafe5c687919f4d5afa368993
sprax/1337
/python2/l0106_construct_binary_tree_from_inorder_and_postorder_traversal.py
1,173
3.90625
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 buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] ...
cd3429c99778bb2cf61580028a3fb423e0baa14a
sprax/1337
/python3/l0045_jump_game_2.py
944
3.5
4
from typing import List class Solution: def jumpDP(self, nums: List[int]) -> int: # min_jumps[i] num of min jump to i. min_jumps = [float('inf')] * len(nums) min_jumps[0] = 0 for i, n in enumerate(nums): for j in range(i+1, min(len(nums), i+n+1)): min_jum...
1af145c23273d85d5cfba8354f4e77ffa49bdaea
sprax/1337
/python3/l0320_generalized_abbreviation.py
756
3.609375
4
class Solution: """ @param word: the given word @return: the generalized abbreviations of a word """ def generateAbbreviations(self, word): # Write your code here queue = [(word, 0)] visited = set([word]) result = [] while queue: w, start = queue.p...
736b6404662669f845019005c5249f7c609ca47b
sprax/1337
/python3/l0253_meeting_rooms_2.py
878
3.875
4
""" Definition of Interval. """ class Interval(object): def __init__(self, start, end): self.start = start self.end = end class Solution: """ @param intervals: an array of meeting time intervals @return: the minimum number of conference rooms required """ def minMeetingRooms(se...
7d1ff054431d6a4c78ec0308f95fbeac290c14e6
sprax/1337
/python3/l0071_simplify_path.py
520
3.578125
4
class Solution: def simplifyPath(self, path: str) -> str: if not path: return '' p1, p2 = 0, -1 stack = [] while p1 < len(path): while p1 < len(path) and path[p1] != '/': p1 += 1 seg = path[p2+1:p1] if seg == '..': ...
6a2e2e5dd53b37eac58c28682c8489e32b09db6b
sprax/1337
/python3/l0272_closest_binary_search_tree_value_2.py
2,413
3.640625
4
from common import TreeNode class Solution: """ @param root: the given BST @param target: the given target @param k: the given k @return: k values in the BST that are closest to the target """ def closestKValues(self, root, target, k): # write your code here # Find k lower b...
c4a348f6ba812baaf2993d3958d42ee55369a0f8
sprax/1337
/python2/l0289_game_of_life.py
1,307
3.703125
4
class Solution(object): def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ def num_of_live_neighbours(board, i, j): neighbors = [row[max(j-1, 0):j+2] for row in board[max(i-1, 0):i+...
11c46d2e369f4a299d89533439a8d4fd41ec9913
sprax/1337
/python3/l0293_flip_game.py
390
3.65625
4
class Solution: """ @param s: the given string @return: all the possible states of the string after one valid move """ def generatePossibleNextMoves(self, s): # write your code here next_strings = [] for i in range(len(s)-1): if s[i:i+2] == '++': n...
c5fb2b3c33c05d3d098923f788b3b057571ae73c
sprax/1337
/python3/l0148_sort_list.py
1,336
3.828125
4
from common import ListNode from typing import Tuple class Solution: def sortList(self, head: ListNode) -> ListNode: def merge_sort(head: ListNode, length: int) -> Tuple[ListNode, ListNode]: # Sort list for given length, return sorted list and list after length. if not head: ...
2553a5e6c891b66665790df2a79b021b84946457
sprax/1337
/python3/l0285_inorder_successor_in_bst.py
600
3.6875
4
class Solution: """ @param: root: The root of the BST. @param: p: You need find the successor node of p. @return: Successor of p. """ def inorderSuccessor(self, root, p): # write your code here if not root or not p: return None if p.right: n = p.r...
6a2424432390137123ec3c1eeb8389e07feae946
sprax/1337
/python3/l0061_rotate_list.py
594
3.625
4
from common import ListNode class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if not head or k == 0: return head tail, length = head, 1 while tail.next: length += 1 tail = tail.next k = k % length ...
b9b5c85c13c28265c0e01a9bb1b701cd9abc3b09
sprax/1337
/python2/l0116_populating_next_right_pointers_in_each_node.py
749
3.90625
4
# Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree link node # @return nothing def connect(self, root): def ...
3471a616f794dcbddf65693990eb1944efc0da33
sprax/1337
/python3/l0138_copy_list_with_random_pointer.py
779
3.578125
4
class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random class Solution: def copyRandomList(self, head: 'Node') -> 'Node': dummy = p0 = Node(0) dummy.next = head p1 = head ...
503047c118fdc2cc1eb361583bfe67a174ecd811
sprax/1337
/python2/l0160_intersection_of_two_linked_lists.py
954
3.8125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ p1, p2 = h...
c90c3a287defcac3fc373652e6f52f51b61782b6
sprax/1337
/python3/test_l0186_reverse_words_in_a_string_2.py
394
3.9375
4
import unittest from l0186_reverse_words_in_a_string_2 import Solution class Test(unittest.TestCase): def test_solution(self): self.assertEqual('blue is sky the', Solution().reverseWords('the sky is blue')) self.assertEqual('world! hello', Solution().reverseWords('hello world!')) self...
d9510cc952f378c3c569a5f3fd5827d1a1fa93ff
sprax/1337
/python2/l0189_rotate_array.py
1,116
3.8125
4
# O(n) solution by reversing and reversing. class Solution(object): def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ def reverse(nums, start, end): i, j = start, end ...
bc2933922662ecdda6cb14a13a30d03857af7afe
sprax/1337
/python3/l0281_zigzag_iterator.py
1,152
3.640625
4
class ZigzagIterator: """ @param: v1: A 1d vector @param: v2: A 1d vector """ def __init__(self, v1, v2): # do intialization if necessar self._v1 = v1 self._v2 = v2 self._i1 = 0 self._i2 = 0 self._s = 1 if not self.hasNext(): self._...
0ef19651b9b794554c0b6347a25805cf4859f568
sprax/1337
/python3/l0305_number_of_islands_2.py
2,354
3.78125
4
from collections import defaultdict """ Definition for a point. """ class Point: def __init__(self, a=0, b=0): self.x = a self.y = b class Solution: """ @param n: An integer @param m: An integer @param operators: an array of point @return: an integer array """ def numI...
74c5998257bc10a08bd0f5fdaac4c54f36a59802
sprax/1337
/python3/l0222_count_complete_tree_nodes.py
515
3.765625
4
from common import TreeNode class Solution: def countNodes(self, root: TreeNode) -> int: if not root: return 0 l_depth = 0 p = root while p: p = p.left l_depth += 1 r_depth = 0 p = root while p: p = p.right ...
c6822af161760756084586781b723e157f58dcca
sprax/1337
/python2/l0114_flatten_binary_tree_to_linked_list.py
1,096
3.984375
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 flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify roo...
18aff7108ae0acf145fef485287a630f45124200
sprax/1337
/python2/l0002_add_two_numbers.py
1,834
3.765625
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None from common import ListNode class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListN...
a23854e8d712b64fcf34f982b5a10932c0f043ff
Mlordx/MAC0499
/src/onedim.py
2,843
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from primitives import * class LimitTree: def __init__(self,v): self.root = self.buildTree(sorted(v,key = lambda k: k.x)) def inRange(self,rng,p): w1,w2 = rng return w1 <= p and p <= w2 def buildTree(self,points): ...
cad0f9685879a728b91f653ad7540b237be24b8e
peskywyvern/homework9
/92.py
901
3.875
4
# Write a class Product that has 4 attributes: # - type # - name # - price # - quantity # and the following methods: # - add(amount) - adds a specified quantity of a single product # - set_discount(percent) - adds a discount for current product. # discount must be specified in percentage clas...
cc076d959217e9ef4750a92e0d5a9f1b813ee61b
sanylax/canvasCal
/setup.py
1,048
3.703125
4
from canvasapi import Canvas import gcal API_URL = input("Please enter your institution's canvas url (like 'https://example.instructure.com'): ") API_KEY = input("Please enter your canvas API key: ") file = open('canvas.txt', 'w') file.write(API_URL + '\n') file.write(API_KEY) file.close() canvas = Canvas(API_URL, AP...
de9b2cef5eea479083e2932d8291e8ba6a4188bf
kisa411/CSE20211
/isPalindrom.py
476
4.15625
4
word = raw_input("Enter a word:") list = [] start = 0 end = len(word) - 1 def isPalindrome(word): global start global end for letter in word: list.append(letter) while (start < end): if list[start] != list[end]: return False else: return True s...
96cd39fd764120432521f2bc9495bd17965377e2
robert-karl/miscPython
/workInProgress/Harvard_Classics_downloader.py
1,799
3.5
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 20 13:03:57 2019 This program scrapes the website /www.myharvardclassics.com and downloads all of the harvard classics collection to a local directory. Currently that directory is hard coded internally. This can be changed to make it user supplied @author: rinfi_000 "...
ed4e6d398a8e9399b3022d562a14d2e55ffd43f6
AlexSelby1/turtle-crossing
/scoreboard.py
620
3.625
4
from turtle import Turtle FONT = ("Courier", 15, "normal") class Scoreboard(Turtle): def __init__(self): super().__init__() self.score=0 self.pu() self.color("black") self.goto(-230,270) self.ht() self.update_scoreboard() def update_scoreboard(s...
965e94ec4b6c447066a26e1ffb80dfdbe027357f
petersont/landscape
/graph.py
1,313
3.5625
4
import math class Vector: def __init__(self, x, y, z): self.x = float(x or 0.0) self.y = float(y or 0.0) self.z = float(z or 0.0) def __add__(self, other): return Vector(self.x + other.x, self.y + other.y, self.z + other.z) def __sub__(self, other): return Vector(...
b0f26fc98716307747c63e4bbc3921dd660ac6b1
waddahAldrobi/RatebTut-
/Python Algs copy/print bst by level.py
504
4.125
4
def print_bst(tree): current_level = [tree.root] while current_level: next_level = [] for node in current_level: print(node.value,end='') # Logic to start building the next level ##Added if node.left: next_level.append(node.left) ...