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
4adcd8a29c46518291001e1754cbe75f2d056e74
mshekhar/random-algs
/general/median_from_data_stream.py
1,195
3.765625
4
from heapq import heappush, heappop class MedianFinder(object): def __init__(self): """ initialize your data structure here. """ self.max_heap = [] self.min_heap = [] def addNum(self, num): """ :type num: int :rtype: void """ i...
17a57a27c91bd0d308536343a6d274f8cee8054f
mshekhar/random-algs
/epi_solutions/dynamic_prog/longest_palindrome.py
1,591
3.65625
4
class Solution(object): def generate_odd_palindrome(self, s, idx): l_idx = idx - 1 r_idx = idx + 1 p_str = [s[idx]] while l_idx >= 0 and r_idx < len(s): if s[l_idx] != s[r_idx]: break p_str.insert(0, s[l_idx]) p_str.append(s[r_idx])...
0e28d1378971ede41eb95f9cae1d34b9fdde3fd6
mshekhar/random-algs
/epi_solutions/arrays/best-time-to-buy-and-sell-stock.py
610
3.734375
4
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ minimum_till_now = float('inf') max_profit_till_now = 0 for price in prices: max_profit_till_now = max(max_profit_till_now, price - minimum_till_now) ...
8e351c012c3e7249264f9cd66e7d1188c744f160
mshekhar/random-algs
/epi_solutions/arrays/get_random_ele.py
1,672
3.765625
4
import random from bisect import insort_left class RandomizedCollection(object): def __init__(self): """ Initialize your data structure here. """ self.counter = {} self.arr = [] def insert(self, val): """ Inserts a value to the collection. Returns true ...
33faf93acba4c52ace35d12ef4b92bd972a76dd3
mshekhar/random-algs
/epi_solutions/graphs/surrounded-regions.py
2,327
3.71875
4
from Queue import Queue class Solution(object): def get_mtx_val(self, row, col, mtx): if row < 0 or col < 0: return -1 try: return mtx[row][col] except IndexError: return -1 def set_mtx_val(self, row, col, mtx): if row < 0 or col < 0: ...
9aaecd17f38cb8efa05854eebf5a442ef0ad60d0
mshekhar/random-algs
/epi_solutions/binary_tree/binary-tree-pruning.py
656
3.8125
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 helper(self, root): if not root: return 0, None left_sum, root.left = self.helper(root.l...
35cb96155665db013e8195e6ae5998721ea79136
maxoldshein/Python-Projects
/isPalindrome.py
400
4.09375
4
def main(): palindrome = str(raw_input("Please enter a string to check to see if its a palindrome: ")) reversedPalindrome = palindrome [:: -1] for i in range(0, len(palindrome)): if (palindrome[i] != reversedPalindrome[i]): print("Not palindrome") break if(i == len(p...
b5a984fc6274f54bd8fa769a900b490a46f00e75
SwethaSuresh09/guvi
/code/pro11.py
163
3.609375
4
arrr=int(input()) brrr=0 l=[] for arrr in range(1,arrr+1): 1.append(arrr) for arrr in range(len(1)): for arrr in range(arrr+1,len(1)): brrr-=1 print(brrr)
c19af5ce895c148448e87caa0f4b45cdf9e3e5ef
shalini1803/pramp_questions
/questions/array-quadruplet/solution_py3.py
1,206
3.640625
4
# O(n^4) def find_array_quadruplet_bruteForce(arr, s): n = len(arr) if n < 4: return [] arr.sort() for i in range(n - 3): for j in range(i + 1, n - 2): for x in range(j + 1, n - 1): for y in range(x + 1, n): if arr[i] + arr[j] + arr[x] + arr[y] == s: return [arr[i], a...
6c837aa721e83b62283cc847f2ec24a1371fc22b
shalini1803/pramp_questions
/questions/sudoku-solver/solution.py
1,315
3.609375
4
def getCandidates(board, row, col): candidates = [] for num in xrange(1,10): num = str(num) collision = False for i in xrange(9): if (board[row][i] == num) or (board[i][col] == num) or (board[row-(row%3)+(i/3)][col-(col%3)+(i%3)] == num): collision = True break if not collisio...
e94bd6e7092ef9ab84e3657e6509d1413e360702
kipkemoimayor/PasswordLocker
/run.py
6,200
4.34375
4
#!/usr/bin/env python3.6 from user_login import User import random from user_login import Password def register(username,password,accountName): user_details=User(username,password,accountName) return user_details def save_user(user_login): user_login.register() ''' Function to delete Account info ''' def ...
aa17ac033003889b6bc0e7659d8f64b851f139cf
ProgFuncionalReactivaoct19-feb20/laboratorio1-clase03-erickgjs99
/ejercicios/ejercicio_2.py
400
3.671875
4
""" autor: @erickgjs99 file: ejercicios_2.py """ notas = [(5, 5, 10), (10, 2, 4), (10, 1, 9), (10, 2, 3)] # funciones lambda para sumar todas las tuplas sum1 = lambda x: x[0] sum2 = lambda x: x[1] sum3 = lambda x: x[2] # funcion lambda para sumar los numeros dentro de las tuplas total_Sum = lambda x: sum1(x)+...
23e83a034b5363b25d3e99a562d7c2b297113751
yw229/Recursion
/LongestLenthofNonRepeatSub.py
729
3.59375
4
#!/data/NYGC/Software/python/bin/python2.7 def lenOflongestSubstring(s): pre = 0 dict = {} # for each char in given string, store it's index endi = 0 for i in range(len(s)): if s[i] not in dict: dict[s[i]] = i #keep track of unique substring char endi = i else: print pre , len(dict) pre = p...
5bcfe4717534aa01a831931c8244274edfe054f8
chaosannals/trial-python
/olddemo/trial/sort/merge.py
1,280
3.890625
4
import math def merge_sort_merge(target, start, middle, end): ''' ''' buffer = [0]*(end - start + 1) left = start right = middle + 1 index = 0 # 把左右排序写入缓存 while left <= middle and right <= end: if target[left] <= target[right]: buffer[index] = target[left] ...
a32b6b404fbb33fc9a2c85046d0e674e35da4502
chaosannals/trial-python
/olddemo/tool/crlf2lf.py
554
3.59375
4
import os SUFFIX_GROUP = [ 'm4', 'sh', 'guess', 'sub', ] def list_file(folder): ''' 列举目录下的文件 ''' result = [] dirname = os.path.realpath(folder) for i in os.listdir(dirname): path = os.path.realpath(dirname + '/' + i) if os.path.isdir(path): result.e...
6b18f9870023e23c328cb6e74cbd81bab4a5d42f
yaochao/untitled3
/algorithm/random100.py
621
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # created by yaochao at 2019/1/21 ''' 从 [0,100] 随机取 10 个数,使之和等于 100,用 Python 如何实现,包含0和100 ''' import random def main(): nums = [] for i in range(9): num = random.randint(0, 100) nums.append(num) nums.sort(reverse=True) nums.insert(0, 100...
369f2cf0aa7d17727e2fab967999aecb9cc81df4
yaochao/untitled3
/data_structure_algorithm/max_path_sum.py
334
3.625
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Created by yaochao at 2017/11/14 maximum = float('-inf') def max_sum(): pass def helper(root): if not root: return 0 left = helper(root.left) right = helper(root.right) maximum = max(maximum, left + right + root.val) return maximum + ma...
f8cd504dd44ff54de0c85010baced9f3b202c051
prathameshkurunkar7/common-algos-and-problems
/Math and Logic/Prime Number/Prime.py
378
4.21875
4
def isPrime(number): if number == 1 or number == 0: return False limit = (number // 2) + 1 for i in range(2, limit): if number % i == 0: return False return True if __name__ == "__main__": number = int(input("Enter a number: ")) print("Entered number is", ...
5f3def601254e9e873f48b1ec47153f6d1abc00e
seige13/SSW-567
/HW-01/hw_01_chris_boffa.py
1,044
4.3125
4
""" # equilateral triangles have all three sides with the same length # isosceles triangles have two sides with the same length # scalene triangles have three sides with different lengths # right triangles have three sides with lengths, a, b, and c where a2 + b2 = c2 """ def classify_triangle(side_a, side_b, side_c):...
cbefcfb03d52e7211ea14c7659e4667db51c9242
sutirangt/CP3-Tanit-Suthirangkoon
/Exercise5_2_Tanit_S.py
122
3.9375
4
distance = int(input("Input Distant (km):")) time = int(input("Input Time Used (hour):")) print(int(distance/time),"km/h")
1bdaf816b75fac3fc43f4d1d40eb0884fe1fd142
DiegoFFreitas7/Teste_IA
/teste_Maximizacao.py
3,575
3.546875
4
from random import randint from algoritmo_Genetico import Individuo, Algoritimo_Genetico ''' PROBLEMA Existe 3 tipos de item para se colocar em uma caixa de capacidade igual a 20Kg A massa, valor e peso de cada item e descrito abaixo Item Quantidade Massa(Kg) Valor(R$) item_A 3...
0428f1e33c4b147a82ec937813c8e4474cf0c4db
iPROGRAMMER007/OOPS
/oop_9.py
585
3.546875
4
class Student: def __init__(self,name,rollno): self.name = name self.rollno = rollno self.lap = self.Laptop() def show(self): print(self.name,self.rollno) self.lap.show() class Laptop: def __init__(self): self.brand = 'ASUS' ...
24bf43a15a1d32d3f7f9b9f2f9926bd4139edf05
darphiz/Python-Codes
/mee343.py
323
3.671875
4
import math while True: R = 70 L = 150 Q = int(input("input the value of thetha")) a = (R*R)/(L*L) b = math.sin(math.radians(Q)) c = b*b d = 1 - (a*c) e = math.sqrt(d) x = R + L -( R* math.cos(math.radians(Q)) + L *e) X = str(x) print ( "the theoretical position is >>"+ X) ...
8cf7c74fc599cd4be36594ecfa735be3c2cd076d
TannerReese/xmath
/sets.py
6,922
4.1875
4
def unique(lst): """ Removes all duplicate elements from a list """ nlst = [] for e in lst: if e not in nlst: nlst.append(e) return nlst class Equivalence: """ Represent an equivalence relation by mapping Attribute: morphism (function) -- a mapping from one set to another Default: the identity map...
88e213a4e32a570872bdad0a294bf4751673f9fa
sh971202/myNet
/unionDir.py
349
3.609375
4
import argparse def argParse(): parser = argparse.ArgumentParser() parser.add_argument('txt', help = 'txt that would be transformed') args = parser.parse_args() return args args = argParse() txt = open(args.txt, 'r') outfile = open('./newtxt.txt', 'a') for line in txt: line = line.replace('/', '_') print (li...
308e92c4dc6f53a773e2e8320463fdb7eb0925b4
manpreet1994/topgear_python_level2
/q5.py
2,347
4.5625
5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 23 12:16:54 2020 @author: manpreet python assignment level 2 Level 2 assignment: ------------------- program 1: write a python program using regex or by any other method to check if the credit card number given is valid or invalid. your python ...
5854d188ab5c0d8b16d8ffdb88cefea860c436f5
aiRobott/opencv-code
/lesson1_1.py
264
3.78125
4
""" Lesson - 1 : Read and show an Image """ # Import required packages: import cv2 # Load an color image in grayscale img = cv2.imread('messi5.jpg', -1) cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows()
d1c75949a86df8e7368d0f4d30e954270a3d63e1
rafal423/AiSD
/lab1/live_coding/lc_3.py
373
3.71875
4
# Przygotować skrypt, który pobierze od użytkownika (z klawiatury) następujące informacje: # imie # rok urodzenia # i wypisze na ekranie komunikat o następującej formie: "Witaj, [imie]. Masz [x] lat." first_name = input('Podaj swoje imie: ') birth_yr = int(input('Podaj swoj rok urodzenia: ')) age = 2020 - birth_yr p...
a18e6177e7115157ccc16797bcb5b0831a8ba3b8
bkabhilash0/Python-Beginners-Projects
/17_Fibonacci.py
356
3.8125
4
def fib_recurrsion(n): if n == 1: return 0 elif n == 2: return 1 else: return fib_recurrsion(n-1) + fib_recurrsion(n - 2) def fib_sequence(n): a = 0 b = 1 print(a) print(b) for i in range(n): c = a + b a = b b = c print(c) print...
211e3d01f7c4d681e95d270d2d7ba2130f08394a
bkabhilash0/Python-Beginners-Projects
/16_Leap_Year.py
1,985
4.375
4
import sys print("***********************************Leap Year Finder*******************************************") print("Enter a Year to check if it is a leap year or Not?") leap_years = [2004, 2008, 2012, 2016, 2020, 2024, 2028, 2032, 2036, 2040, 2044, 2048, 2052, 2056, 2060, 2064, 2068, 2072, 2076, 208...
670d909dae3a49f2698e7022764cb4ea0d5454e8
lizprogrammer/PythonFromScratch
/python_from_scratch_18.py
985
3.671875
4
import csv csv_list = dir(csv) #print(csv_list) with open('liz.csv','r') as c: r = csv.reader(c) for lines in r: print(lines[1]) with open('random.csv','w') as random: wr = csv.writer(random,delimiter=',') wr.writerow(['Elizabeth','Rosso']) wr.writerow(['Nora','Owen']) wr.writerow(['E...
4b3860beff600e1652754a3d467e8e0814c7b3c2
peleduri/baby-steps
/baby steps/Learn_py/ex9.py
361
4.3125
4
days = "Mon Tue Wed Thu Fri Sat Sun" # now we will learn how to drop one line with n months = "Jan\nFeb\nMar\nApr\nJun\nJul\nAug" # we will now just gonna print out the days and months print("Here are the days: ", days) print("Here are the months:", months) # we will learn that we can use """" to keep on typing prin...
93fc7ea4157a78aa0f7f17f72db4a68191f01aa7
judgementc/plantcv
/plantcv/plot_hist.py
1,439
3.609375
4
# Plot histogram import cv2 import numpy as np def plot_hist(img, name=False): """Plot a histogram using the pyplot library. Inputs: img = image to analyze name = name for plot output :param img: numpy array :param name: str :return: bins,hist """ import matplotlib matplotl...
e952153780c9ab4a86d21fa0edfe400c32101b3d
judgementc/plantcv
/plantcv/laplace_filter.py
1,494
3.75
4
# Laplace filtering import cv2 from . import print_image from . import plot_image def laplace_filter(img, k, scale, device, debug=None): """This is a filtering method used to identify and highlight fine edges based on the 2nd derivative. A very sensetive method to highlight edges but will also amplify bac...
b760e08bfd3b8fc49bbd4067368b222636577503
judgementc/plantcv
/plantcv/logical_xor.py
896
3.5625
4
# Join images (XOR) import cv2 from . import print_image from . import plot_image def logical_xor(img1, img2, device, debug=None): """Join two images using the bitwise XOR operator. Inputs: img1 = image object1, grayscale img2 = image object2, grayscale device = device number. Used to count ...
d1c4af4ab34514601223ed1f6c39c9021f42368e
BhuvanGoldi/Python-codes
/hangman.py
1,712
4.0625
4
from random import randint def hangman(): name = input('what is your name? \n') print("hello ",name,' its time to play hangman') print('start guessing') #determine the number of chances turns = 10 #variable to hold the guessed word guesses = " " guessed = [] guess='...
bdfcc1bdc254648afb06d5292d9e6f0fc17457ee
nsc-tai-sakakibara/submission
/Python/sosuu.py
430
3.734375
4
suuti = int(input("値入力:")) def sosuu(suuti): for i in range(2,suuti,1): if suuti%i==0: print("{}は素数ではない".format(suuti)) #return False break if suuti<=0: print("{}は素数ではない".format(suuti)) elif suuti==1: print("{}は素数である".format(suuti)) else: if sosuu(su...
51836ed833c097e9254c6add663fdac52e816660
nsc-tai-sakakibara/submission
/Python/study.py
6,189
3.78125
4
# コメント """ コメント """ import calendar import random from math import * import math from calendar import TextCalendar print("hello world") print("令和"+str(2)+"年", end="") print("西暦"+str(1998+22)+"年") print(""" あ か さ た な """) z = "hello \"takasi" print(z) z = "hello \n takasi" print(z) name = ["takesi", "hisosi", "aik...
40b78ef4b160554bfb3ca983fc38eb9fd68fa561
Joost-Robat/PythonAchievements
/TEST OPGAVEN/3_3.py
551
3.953125
4
import time weekdag = input('geef een dag aan\n').lower() print("test") time.sleep(2) if weekdag == "zondag" or weekdag == "zaterdag": print("Het is weekend!") elif weekdag == "maandag": print("Het is de kutste dag van de week...") elif weekdag == "dinsdag": print("Dinsdag is niet zo erg...") elif weekdag == "woensd...
00986cb0914cfe993898355ab91cf296a001d1e1
Joost-Robat/PythonAchievements
/TEST OPGAVEN/3_1.py
270
3.828125
4
c = True while c: print("Wat is 10 X 72183 groter of kleiner als 10?") q1 = input() if q1 == "groter" or q1 == "Groter": print("Dat is het juiste antwoord!") c = False elif q1 == "kleiner"or q1 == "Kleiner": print("Dat is niet het juiste antwoord!") continue
9398ff81fb89d098ead5c2280e6d75da72149013
Jochoniah/The-Complete-Python.PostgreSQL-Course-2.0
/PYTHON-REFRESHER/Advanced-sets/code.py
299
3.859375
4
local = {"Rolf"} abroad ={"Bob","Anne"} # local_friends = friends.difference(abroad) # friends = local.union(abroad) art = {"Bob", "Jen", "Rolf", "Charlie"} science ={"Bob", "Jen", "Adan", "Anne"} # find out which friends take both art and science both = art.intersection(science) print(both)
520c46995ceeeb24181c8b1e10e8ee779c0120c0
OliverLemke/molpy
/molpy/cli.py
816
3.734375
4
import argparse from .util import read_xyz, distance parser = argparse.ArgumentParser(description="Reads XYZ files and calculates the distance between two atoms at index1 and index2") parser.add_argument('filename', type=str, help="The XYZ file to read") parser.add_argument('index1', type=int, help="Index of the first...
375222e1c07e2b396916ed5f491a87a27dbd33db
unixwars/python_challenge
/14.py
667
3.625
4
#!/usr/bin/env python #title: walk around #hint1: image is a spiral #hint2: remember: 100*100 = (100+99+99+98) + .... (3+2+2+1)+1 #fact1: wire.jpg is 1x10000 pixels = 100*100 import Image im = Image.open("wire.png") new = Image.new(im.mode,[100,100]) doubled_steps=200 directions=[(1,0), (0,1), (-1,0), (0,-1)] # vector...
c7b881bcf8d5d8c8d4a5be23b609a4613dc733fa
tejassinghsital/Interview-Prep-Pro
/OOP with Python/OOP3.py
1,158
4.0625
4
# inherits, extend, override class Employee: def __init__(self, name, age,salary): self.name = name self.age = age self.salary = salary def work(self): print(f"{self.name} is working...") class SoftwareEngineer(Employee): def __init__(self,name,age,salary, level): super().__init__(name,age,salary) ...
b73fc490b8595a50cf05be32c48ff9266f7ac260
tangjy155/tangjyPro
/practice/python_oop/animal_oop.py
789
3.90625
4
# -*- coding: utf-8 -*- # @Time : 2020/10/25 18:41 # @Author : tangjy # @File : animal_oop.py # 动物类 class Animal: def __init__(self, color): self._color = color # 获取动物颜色 def get_color(self): # print(self._color) return self._color def speak(self): print("动物叫...
7833d3bd1dac5670c98773d5ea9ff5d3785a89f3
chanfengsr/Training
/geekTimePython/29_函数的闭包.py
165
3.984375
4
# 函数的闭包 # 计算 y = ax + b,其中 x 为频繁更改的变量 def a_line(a, b): return lambda x: a * x + b lf1 = a_line(3, 5) print(lf1(10))
0d096ed64e8d73be44da1378798502cf6a2cd1b6
siam923/Data-Stucture-Algorithm
/DataStructure/problem_6.py
3,268
3.84375
4
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) class LinkedList: def __init__(self): self.head = None def __str__(self): cur_head = self.head out_string = "" while cur_head:...
d6d79e95ee4d2ab7e669d04356965e460eb13e51
gjhartwell/cth-python
/cthmds/timeSubset.py
1,448
3.578125
4
# -------------------------------------- # timeSubset.py # # MDSplus Python project # for CTH data access # # timeSubset --- returns the subset of an array between given times # # Parameters: # taxis- the time axis that tInit and tFinal reference # data - the array to take the time subset of # tInit - the initial ti...
1dfbbcec0d1a8c47eb2d2119199687dcee8951af
pbain63/divine-code
/Thomas.py
4,218
4.1875
4
### Simple coding problems ###Sum of all digits in a number: ###Code for Sum of all Digits In Alpha-Numberic String #1 Without Recursion string = input("Enter a Alpha-Numeric String: ") sums = 0 for i in string: if( i.isnumeric() ): sums = sums+int(i) print(sums) @ Enter an Alpha-Numeric String: a11s22s5...
e4a8ecb0bd292fb9bd32d447a0cba66a0f2b024d
Jimmy-Py/Completed_Python_Programs
/arithmetic_practice_2.3.1.py
7,859
4.40625
4
# Arithmetic Practice 2.1 James B 7-27-19. # 2.0 Changes: Random operation, keeps track of score, and execution of operation choice moved from main() to compute_number(). # As a result compute_number() now tells display_number() what operation it used. # # 2.1: # (1) make integer answers for division() acceptable for t...
95e83f5f65bdbcbad1500ab2b40baf5392034fdb
pravarmahajan/TwitterDataAnalysis
/twitter_lang.py
3,275
3.640625
4
'''This script has been generated as part of the assignment 1 of the course on "Social Media and Text Analytics". It contains libraries related to language analysis of the tweets. Expected twitter data is a list of tweets represented in the form of python dictionary. The tweets should be text tweets only, other user ac...
00dc28334e35aba9c964d9588a072a911f5bd566
OsnovaDT/numerical-methods
/porabola.py
2,111
3.890625
4
########### ИМПОРТ БИБЛИОТЕК ########### from os import system from math import tan ########### ИМПОРТ БИБЛИОТЕК ########### ########### КЛАСС ДЛЯ СОБСТВЕННЫХ ИСКЛЮЧЕНИЙ ########### class MyError(Exception): def __init__(self, msg): self.msg = msg ########### КЛАСС ДЛЯ СОБСТВЕННЫХ ИСКЛЮЧЕНИЙ ########### ########...
7c5862873508638f23da8e1642da92f167e83b54
vikask1640/Demogit
/while.py
286
4
4
#while loop temp=77 while temp>=60 and temp<=90: print("room temp is maintaines {}".format(temp)) temp=temp-1 #user temp print("Enter the temp") temps=int(input()) while temps>=0 and temps<=100: print("Room temp is: {}".format(temps)) temps=temps-1
f3cd57fb8dac3c8775ee675aad8eb273cc7e8dce
yiqiangjizhang/Information-Communication-Technology
/ICT/Class_Examples/Session4/insert_data.py
659
3.984375
4
# Insert data to database # Libraries import sqlite3 # Create database sqlite_file = "database.db" # Connection conn = sqlite3.connect(sqlite_file) # Cursor for commands and accessing information cur = conn.cursor() # Insert data sql = "INSERT INTO sensors (name, description, compound) VALUES ('Pressure', 'Pressu...
e5a5e9bc7fd2e2fa71bb6ca1986a5fc81bd11287
yiqiangjizhang/Information-Communication-Technology
/ICT/Assignment1/Session2_3/introduction/time.py
1,419
3.703125
4
# Sense data from the SenseHat # Import the SenseHat object from the emulator from sense_emu import SenseHat import time # Time library import datetime # Create an object sense = SenseHat() # Infinite loop while True: # Save current beginning time start = time.time() # Read temp from temperature sensor ...
191d92772eb8464c5fa2a9e37298ae1911b2c2f2
cnastoski/Data-Structures
/Hybrid Sort/HybridSort.py
2,482
4.65625
5
def merge_sort(unsorted, threshold, reverse): """ Splits a list in half until it cant anymore, then merges them back together in order :param unsorted: the unsorted list :param threshold: if the list size is at or below the threshold, switch to insertion sort :param reverse: sorts the list in descen...
1a1de0a47bfd6fead505e572b2e11e8b36b9be71
bjpop/blip
/test/regression/features/augassign/augassign.py
360
3.546875
4
x = 12 x += 2 print(x) x *= 3 print(x) x -= 4 print(x) x /= 3 print(x) x %= 2 print(x) x **= 5 print(x) x = 256 x <<= 1 print(x) x >>= 1 print(x) x &= 1 print(x) x |= 1 print(x) x ^= 1 print(x) x = 257 x //= 16 print(x) x = [1,2,3] x[0] += 1 print(x[0]) class C(object): pass c = C() c.x = 176 c.x += 1 print(c.x) ...
40827eb430251c416eeb4d25031a223671d8b8f7
bjpop/blip
/test/regression/features/assignment/assign_unpack.py
796
4.09375
4
# singleton tuple <- singleton tuple x, = 0, print(x) # singleton tuple <- singleton list x, = [-1] print(x) # binary tuple <- binary tuple x,y = 1,2 print(x,y) # binary tuple swap x,y = y,x print(x,y) # ternary tuple <- ternary tuple x,y,z = 3,4,5 print(x,y,z) # singleton list <- singleton list [x] = [42] print(x) # s...
6c11f0c4997f49936b25e79c96bb77ae70cceb0a
Leo-Malay/Python-Scripts
/cam_recorder.py
1,565
3.625
4
# This python script helps to access the camera,record and export a video output file. # By Malay @ 2020 # ! - Warning - ! # Must have opencv installed -->> pip install opencv-contrib-python # Must understand the scripts written and then consider modifing it to meet requirement. # Must have latest pyt...
1b402588b59e4ee619d78c666dd91b5b0bcac969
mrmleonard/pyxel_examples
/pyxel/presentation_examples/ball.py
560
3.890625
4
import pyxel x = y = 30 # the position of the ball v = w = 3 # the speed of the ball pyxel.init(160, 120) # create the screen as 160x120 size while True: pyxel.cls(1) # erase the screen with color number 1 (blue) # process the movement of the ball x += v y += w if x <= 7 or x >= 152: ...
439eb0490c78ce5ca3f54199ed00ce2aebcd6577
pascalacco/jupyter-guide-to-linear-algebra
/img_src/Graph_drawing_functions.py
2,264
3.59375
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 17 10:22:19 2020 @author: Ben Vanderlei """ import matplotlib.pyplot as plt import networkx as nx def DrawGraph(A, pos = None): ''' Draws a directed graph based on adjacency matrix A. Parameters ---------- A : NumPy array object. ...
84ddee58dfc985225adf83fac439fca3bd5e767c
delfu/advent2019
/6.py
1,890
3.828125
4
star_map = {} cache = {} def number_of_ancestors(star_map, satellite, cache): if satellite in cache: return cache[satellite] if satellite not in star_map: cache[satellite] = 0 else: cache[satellite] = ( sum( map( lambda t: number_of_a...
9a7267d6baf6c0e8bb69a654d86b394354f8f8b8
Josiah-Jovido/SQLite
/SQLite_studentdata/data_app.py
1,484
4.09375
4
import sqlite3 # Query the DB and Return all RECORDs def show_all(): # Connect to database conn = sqlite3.connect('student.db') # Create a cursor c = conn.cursor() c.execute("SELECT rowid, * FROM students") items = c.fetchall() for item in items: print(item) ...
fc3c242b2c3605cb91de9fcdf2ed42258874152a
Nesqwik/SVL
/TP2/account.py
1,447
3.796875
4
class Compte: def __init__(self): ''' >>> c = Compte() >>> c.get_balance() 0 ''' self.balance = 0 def get_balance(self): ''' >>> c = Compte() >>> c.get_balance() 0 ''' return self.balance ...
a77fd5df036638d02e3fa0acd55f332d9e027895
mjirik/bodynavigation
/bodynavigation/advanced_segmentation/lines.py
4,440
3.5625
4
from loguru import logger import math import numpy as np import bodynavigation def standard_from_slopeintercept(angle, point): # TODO odstranit závislost na sympy from sympy import symbols, Eq, solve """Transfer a line's slope-intercept formulation to standard form (ax + by + c = 0). Args: a...
8bdc1dc82ca4110e9c31abad51a76a20cacdfaab
ashleyconnor/leetcode
/src/number_of_islands/solution.py
1,044
3.53125
4
class Solution: def number_of_islands(self, grid): number_of_islands = 0 visited_islands = set() for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col] == "1" and not (row, col) in visited_islands: number_of_islands += ...
b504ef265f6e711d064837402d97b52cdf0a6a8f
CMU-Robotics-Club/Red-Robot-2021
/wificontroller/generate_controller_html.py
463
3.546875
4
# Converts html file into a String in a .h file that can be used by Arduino # To run: `python3 generate_controller_html.py` with open("controller.html") as f: html = f.read() # For each line in html, surround it with quotes and add a newline character html = "\n".join(['"{}\\n"\\'.format(line) for line in ...
e5fbdec81d5e42f7bf9f7255bbca213deef59392
hinbody/find_pay
/pay.py
1,173
3.90625
4
import sys def get_hours(): try: if sys.argv[3] !=0: return sys.argv[3] except: return 40 def calculate_hourly(): hours = get_hours() salary = float(sys.argv[2]) weekly = round(salary/52, 2) hourly = round(weekly/float(hours), 2) print 'For an annual salary of $' + str(salary) + ...
18d8cf7f711890d6d8af5fe93fefbda3947e346e
rjherrera/IIC2233
/Tareas/T01/menu/menu.py
6,419
3.65625
4
# coding=utf-8 from loader.loader import usuarios, cursos, Alumno, Profesor from menu.menu_pacmatico import MenuAlumnoPacmatico from menu.menu_bummer import MenuAlumnoBummer class MenuProfesor: def __init__(self, profesor, cursos, usuarios): self.cursos = cursos self.profesor = profesor s...
d9f3e7193f60f6812cefb2a6579fa392e9653b76
rjherrera/IIC2233
/Tareas/T03/inputs.py
1,043
3.953125
4
def pedir_entero(texto): while True: entrada = input(texto) try: return int(entrada) except ValueError: print('%r no es un entero válido.' % entrada) def pedir_tupla(texto): while True: entrada = input(texto) try: lista = entrada.repl...
a83cb5b5cab2973aa697cab221e20aaf3bea570e
ksemele/coffee_machine
/coffee_machine.py
2,235
4.125
4
class CoffeeMachine: def __init__(self): self.water = 400 self.milk = 540 self.beans = 120 self.cups = 9 self.money = 550 def status(self): print("\nThe coffee machine has:") print(str(self.water) + " of water") print(str(self.milk) + " of milk") print(str(self.beans) + " of coffee beans") print(...
3cc057a27450f114ee585069b0b349a9b0ced7eb
redpurpur/pokeboll
/api/utils.py
977
3.984375
4
from typing import List def levenshtein_distance(s1: str, s2: str): """ Count distance between two strings with two matrix rows, which swapped one by one """ if s1 == s2: return 0 if len(s1) == 0: return len(s2) if len(s2) == 0: return len(s1) row_calculated: Lis...
2ca25165a87b7a7360d35e86b519469f9606da1f
Mahiuha/RSA-Factoring-Challenge
/factors
1,887
4.34375
4
#!/usr/bin/python3 """ Factorize as many numbers as possible into a product of two smaller numbers. Usage: factors <file> where <file> is a file containing natural numbers to factor. One number per line You can assume that all lines will be valid natural numbers\ greater tha...
5d623063e5a43caee25e23d9adba7895e212224c
alexssssalex/Longman
/Base.py
1,237
3.609375
4
from config import WORDS_IN_STUDY, WORDS_KNOWN, WORDS_IN_STUDY_BAK def read_arrange(path: str) -> set: """ - read file by path; - filter empty lines; - made unique list; - arrange list set and save word in the same file in alphabet order; """ with open(path, 'r') as f: data = [w.s...
bb81649a120418b370f638fd40b9dfd50b7d7963
Heinrich-XIAO/CS50
/psets/pset6/mario/more/mario.py
355
4
4
from cs50 import get_int def main(): height = get_int("Height: ") while(height > 8 or height < 1): height = get_int("Height: ") for i in range(height): for j in range(height - i - 1): print(" ", end="") for j in range(height - ((height - 1) - i)): print("#...
1a7ef6b488b6ce7e7a592d8dbeac6625547ea0fc
rdasxy/programming-autograder
/problems/CS101/0035/solution.py
350
4.21875
4
# Prompt the use to "Enter some numbers: " # The user should enter a few numbers, separated by spaces, all on one line # Sort the resulting sequence, then print all the numbers but the first two and the last two, # one to a line. seq = raw_input("Enter some numbers: ") seq = [int(s) for s in seq.split()] seq.sort() fo...
2ec0fdbe9a5dbbdf1605f15643d8fd1e36a81a2f
rdasxy/programming-autograder
/problems/CS101/0038/divider.py
389
3.953125
4
# Create a class called Divider. It should have one method, Divider.divide, that takes two # integers x and y as parameters. If y isn't 0, it should return the quotient x / y. If # y is 0, it should raise a ValueError. class Divider(object): def divide(self, x, y): try: return x / y ...
92e5c144ff2749ac26370e80ee1d0e36080ad677
rdasxy/programming-autograder
/problems/CS101/0004/solution.py
156
4.0625
4
name =raw_input("What is your name? ") times = raw_input("How many times should I greet you? ") for k in range(int(times)): print("Hello "+name)
d0f0fb34afbad8af10a77e5f693d94461debf509
rdasxy/programming-autograder
/problems/CS101/0010/solution.py
91
3.609375
4
y = int(raw_input("Enter a number. ")) while y < 1000 : print(y) y = 4*y + 3
a2cbc96e72aa03e8a7692e8f473894c378154349
rdasxy/programming-autograder
/problems/CS101/0016/vowels.py
98
3.75
4
from solution import vowels sentence = raw_input("Type in a sentence: ") print(vowels(sentence))
8b74550c766ec696d61ee038b5d869987127db42
rdasxy/programming-autograder
/problems/CS101/0014/solution.py
239
4
4
from __future__ import division n = int(raw_input("Enter an integer:")) largest = n while True: if n == 1: break if n & 1: n = 3*n +1 else: n //= 2 largest = max(largest, n) print(largest)
2d509bd4558865292386d2de26fa9b17571892a2
pzhang15/EPI-solutions-set
/EPI/Python/ch5_array/5.17_Sduoku_checker_problem.py
2,107
3.828125
4
from typing import * import math ''' Sudoku Checker, Given N x N grid, Every row, Every Column, Every sqrt(N) x sqrt(N) subarray contains no duplicate and only contains 1~N, (0 indicate empty slot) ''' #we need to check nine row constraints, nine column contrainsts , and nin sub-grid # it's convenient to use bit arra...
f5795ba149e69f8713acd8a9641f8ff2b508803c
pzhang15/EPI-solutions-set
/EPI/Python/ch12_hash_table/12.5_nearest_repeated_entry.py
380
3.640625
4
''' A = ["ALl", "Work", "and", "no","play","makes","for","no","work","no","fun", "and", "no", "result"] The nearest entry is second and third no, with differnet of 1 ''' def sol(A): dic = {} min_diff = float('inf') for i in range(len(A)): s = A[i] if s in dic: min_dff = min(min_...
ea824da1789dbdea1dc6bfbca0a8effe59bc679b
pzhang15/EPI-solutions-set
/EPI/Python/linked_list/7.6_delete_a_node.py
363
3.671875
4
''' Given a refernce to a single node, delete it in O(1) ''' class Node: def __init__(self, data=0, next=None): self.data = data self.next = next #seems impossible right? cause the previous node's next pointer needs to be updates #but we can do this: def deletion_from_list(node): node.data = no...
61b966613b94c29e092515e8e71cbeacc2c2eb6d
pzhang15/EPI-solutions-set
/EPI/Python/ch5_array/5.6_Buy_and_Sell_stock_one.py
931
3.78125
4
from typing import * '''Write a program that computes the maximum profit that can be made by buying and selling a share at most twice. The second buy must be made on another date after the first sale. Hint: What do you need to know about the first i elements when processing the (i + l)th element? ''' def my_sol(A:Li...
aba5bc2fdf7203ad25e23d61399bab9056f35fe4
pzhang15/EPI-solutions-set
/EPI/Python/ch5_array/5.20_Pascal_Triangle.py
777
3.984375
4
from typing import * ''' Pascal Triangle Wiki: https://en.wikipedia.org/wiki/Pascal%27s_triangle 每一行会比上一行多一个element, 每个element等于上面一行的相邻两个的和 Write a program which takes as input a nonnegative integer n returns the first n rows of Pascal's triangle ''' #如果想要把这个变成三角形很难, 不如把所有的数字对到 def epi_sol(n: int) -> List[List[int]]:...
d4903661177e65a3d4df89c0ac4622a4901f7b63
pzhang15/EPI-solutions-set
/EPI/Python/ch9_binary_tree/tryout.py
1,477
4.03125
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right a = TreeNode(1) b = TreeNode(2) c = a and b print(a.val) '''problem statement''' ''' 9.1 LC 110 Test if binary tree is balanced ''' ''' 9.2 LC101 Test if binary tree is sy...
ca42c3f4d5e458c744cb4593cb3214724db6b7af
pzhang15/EPI-solutions-set
/EPI/Python/ch11_searching/tryout.py
758
3.5625
4
''' 11.1 LC 287 ''' ''' take an sorted aray of distinct integer, and return an index such that the element at i is equal to i A = [-2, 0, 2, 3, 6, 7, 9] return 2, or 3 would be correct ''' ''' compute both the min and max with less than 2N comparison A = [3, 2, 5, 1, 2, 4] return 1 and 5, which is min and max ''' ...
346ddcc9039e8a5e11a8386fec9957fe13fc8613
pzhang15/EPI-solutions-set
/EPI/Python/ch12_hash_table/12.3_implement_an_ISBN_cache.py
821
3.78125
4
import collections ''' LC 146 LRU Cache LRU (ISBN - > price)cache insert lookup erase ''' class ISBNCache(): def __init__(self, capacity): self.isbn_table = collections.OrderedDict() self._capacity= capacity def insert(self, isbn, price): if isbn in self.isbn_table: pric...
9d7b83b8677c13b87ee7707aea0e5e5f663d871f
janardhanpshetty/pythonProblems
/zero.py
548
3.671875
4
#!/usr/bin/env python from __future__ import print_function def czero(a, n): ''' Sum of two elements closest to zero ''' minsum = abs(a[0] + a[1]) first = a[0] second = a[1] for i in range(n): for j in range(n): if abs(a[i] + a[j]) < minsum: first = a[i] ...
36ebecc42317c19242b214b93f3e820dbaf2d524
MuCephei/advent2020
/day_10/a.py
575
3.609375
4
def get_adapters(): adapters = [0] with open('input.txt', 'r') as file: for line in file.readlines(): line = line.strip("\n") adapters.append(int(line)) adapters.sort() adapters.append(adapters[-1] + 3) return adapters def classify_adapters(adapters): values = [...
6d211f58a4388a930a099fc3d436d672fafc0e04
MuCephei/advent2020
/day_16/b.py
3,208
3.546875
4
import re class pattern: def __init__(self, p): components = p.split("-", 2) self.min, self.max = int(components[0]), int(components[1]) def valid(self, value): return self.min <= value <= self.max def __str__(self): return "Min: %d Max: %d" % (self.min, self.max) de...
685a4f6c6fa8014754e1370df1d8cf15686b7b5d
LiorMahfoda/Mutable-Recursive-List
/HW3_302782233_201621141.py
8,697
4.09375
4
"Task 1" "-------------------------------------------------------" def make_date(year,month,day): ''' function returns date sections according to given message: year - the year in number month - from number to word day - the day in number str - string representation of the date ''' def dispatch(m): ...
98818efd3d2fe095b876daf4fc81ff662a879ab3
lvhuitailang/test2
/testHtmlParser/test2.py
98
3.796875
4
items = ['a','b','c','d'] items = [x for i,x in enumerate(items) if i<len(items)-1 ] print(items)
dbcff18c825ba74d85fd6644907660bfe77087e8
lvhuitailang/test2
/test15/2.py
1,793
3.5
4
import unittest import test15.HTMLTestRunner as HTMLTestRunner def add(a, b): return a+b def minus(a, b): return a-b def multi(a, b): return a*b def divide(a, b): return a/b class TestMathFunc(unittest.TestCase): # TestCase基类方法,所有case执行之前自动执行 @classmethod def setUpClass(cls): p...
dec12a9f3bb40e12b79920521c074f4d41adb13f
lvhuitailang/test2
/t6/learn.py
355
3.6875
4
class MyNumber: def __iter__(self): self.num = 1 return self def __next__(self): if self.num <= 20: self.res = self.num self.num += 1 return self.res else: raise StopIteration myClass = MyNumber() myiter = iter(myClass) print(n...
34b5ed48678b2a5df1cdda2d3112c008ef67329e
lvhuitailang/test2
/test1.py
848
3.875
4
import tkinter as tk global tk,canvas windows = tk.Tk() windows.title('ly') windows.geometry('355x275') windows.resizable(0,0) Label1=tk.Label(windows,text="username:") Label1.place(height = 48,width = 62,x = 26,y = 60) Label2=tk.Label(windows,text="username:") Label2.place(height = 48,width = 54,x = 24,y = 154) e1...
7596081646d96f0b75cb8ac08dd0da0b9187d05d
luhua187/leetcoding
/657_robot_return_to_origin.py
443
3.546875
4
class Solution(object): def judgeCircle(self, moves): """ :type moves: str :rtype: bool """ u=l=d=r=0 for i in moves: if i == 'U': u+=1 elif i == 'D': d+=1 elif i == 'R': r+=1 ...
6c296239c8d123a692c3575118435ba6d814ec31
vreuter/review
/networks/generate.py
916
3.890625
4
#!/usr/bin/env python3 # Description: Create random simple graphs of a given dimension # Author: Eric Leung # Date: 2016 Jun 22nd # Python: 3.5.1 import numpy as np # 1.11.0 def simple(size, weight=1): """ Generate a simple graph, specifically an undirected network, with neither se...
f3213933c26dc79928dfb3be5323cec7977b2884
dasdachs/smart
/08/python/to_lower.py
384
4.28125
4
#! /usr/bin/env python2 # -*- coding: utf-8 -*- """Return the input text in lower case.""" import argparse parser = argparse.ArgumentParser(description='Transforms text to lower case.') parser.add_argument('text', type=str, nargs="+", help='Text that will be transformed to lower case.') args = parser.parse_args() if...