blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
dff3b9527e7286cd77bd3ba454ada88c879245bb
skeapskeap/algorithms
/recursion.py
1,290
3.640625
4
import random def countdown(i): print(i) if i>0: countdown(i-1) else: print('Booom') def summ(some_list): if some_list: return some_list.pop(0)+summ(some_list) else: return 0 def length(some_list): if some_list: some_list.pop(0) return 1 + l...
3a3cc9ee821bd750f3640b00a39fc8c3966f04d7
riteshc6/ctci
/concepts_and_algorithms/10_sorting_and_searching/count_sort.py
382
3.8125
4
from typing import List def counting_sort(a: List[int]) -> list: k = max(a) aux = [0] * (k + 1) for elem in a: aux[elem] += 1 sorted_a = [] for i in range(k + 1): while aux[i] > 0: sorted_a.append(i) aux[i] -= 1 return sorted_a if __name__ == "__main_...
aeded5ebea7f232f4044a29193e882aa06036f70
riteshc6/ctci
/data_structures/4_trees_and_graphs/3_list_of_depths.py
1,150
4.03125
4
from collections import deque from binary_search_tree import Node def list_of_depths(tree): """ Returns list of linked lists of all elements in each level of binary tree """ parents = [tree] depths = [] # Initialize depths list with root of tree level_ll = deque([tree.data]) depth...
fc8d3179c2b9845aedf2d005873777a2f78610d4
riteshc6/ctci
/concepts_and_algorithms/5_bit_manipulation/1_insertion.py
957
3.625
4
import unittest def get_mask_of_1s(j, i): """ Returns (j - i + 1) 1s """ return (1 << (j - i + 1)) - 1 def get_mask_of_0s_and_1s(mask_of_1s, i): """ Return series of 0s followed by i 1s """ return ~(mask_of_1s << i) def insertion(N, M, j, i): """ Inser M into N fr...
53bf524f07654fc395f388950ead809fdbb0183e
riteshc6/ctci
/concepts_and_algorithms/5_bit_manipulation/8_draw_line.py
1,299
3.515625
4
def draw_line(screen:list, w:int, x1:int, x2:int, y:int): bytes_per_row = w // 8 y_index = y * bytes_per_row if x1 == x2: x_index = y_index + (x2 // 8) mask = (1 << (8 - (x1 % 8))) screen[x_index] |= mask return screen x1_index = x1 // 8 x1_screen_index = y_ind...
be2350999e18aff477869768ca4d230cf4a12ed8
riteshc6/ctci
/concepts_and_algorithms/10_sorting_and_searching/3_search_rotated_array.py
1,050
3.5625
4
def search(a: list, x: int): return _search(a, 0, len(a) - 1, x) def _search(a: list, left: int, right: int, x: int): mid = (right + left) // 2 if x == a[mid]: return mid if right < left: return -1 if a[left] < a[mid]: if x >= a[left] and x < a[mid]: re...
4b14119f0de87a2cb34085ea784fda5475bc705d
riteshc6/ctci
/bigo/perm_tricky.py
361
3.890625
4
import sys # def permutation(string): # permutation(string, "") def permutation(string, prefix): if len(string) == 0: print(prefix) else: for i in range(len(string)): rem = string[0:i] + string[i+1:] permutation(rem, prefix + string[i]) string = "abc" permutati...
cf997b0c99762a040a4ae2c790ef68c0e7245eec
riteshc6/ctci
/concepts_and_algorithms/10_sorting_and_searching/bubble_sort.py
452
4.15625
4
from typing import List def bubble_sort(elems_list: List[int]): n = len(elems_list) for i in range(1, n): swapped = False for j in range(n - i): if elems_list[j] > elems_list[j + 1]: elems_list[j], elems_list[j + 1] = elems_list[j + 1], elems_list[j] ...
3f6372cfb12203e307e4244f95acf9e5f8189dd8
riteshc6/ctci
/data_structures/1_arrays_strings/check_perm.py
1,489
3.609375
4
import unittest def check_permutation(string1, string2): if len(string2): # Creating an array to keep track of all characters in string1 char_counter = [0] * 128 for c in string1: index = ord(c) char_counter[index] += 1 for c in string2: ...
d48b1fb9c09c0e5c45db0c0f5def6af32d72ff74
riteshc6/ctci
/data_structures/2_linked_lists/doubly_linkedlist.py
1,697
3.859375
4
class Node: def __init__(self, data, next_node = None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node def __str__(self): return str(self.data) class DoublyLinkedList: def __init__(self): self.head = None self.tail ...
34d0eb9ec47622ebedbb7e8d96bfdd81e99b543b
riteshc6/ctci
/concepts_and_algorithms/8_recursion_and_dp/5_multiply.py
518
4.09375
4
def multiply(num1: int, num2: int): bigger = num1 if num1 >= num2 else num2 smaller = num1 if num1 < num2 else num2 return _multiply(bigger, smaller) def _multiply(bigger: int, smaller: int): if smaller == 0: return 0 elif smaller == 1: return bigger # Divide smaller by 2 s...
b39773815a94f63c6d9741915f128e9c64796fa5
riteshc6/ctci
/data_structures/3_stacks_and_queues/4_queue_via_stacks.py
1,267
4.0625
4
from stack_ll import Stack class MyQueue: def __init__(self): self.s1 = Stack() self.s2 = Stack() def __str__(self): string = "S1 -> " cur1 = self.s1.top while cur1: string += str(cur1.data) + "," cur1 = cur1.next string += "--- S2 -...
391f4da6853ff60fcfff54438dbc8be89a1f3744
riteshc6/ctci
/concepts_and_algorithms/10_sorting_and_searching/5_sparse_search.py
1,218
3.953125
4
def sparse_search(A: list, word: str): start = 0 end = len(A) - 1 return binary_search(A, word, start, end) def binary_search(A: list, word: str, start: int, end: int): if start > end: return -1 mid = (start + end) // 2 if A[mid] == word: return mid if A[mid] == "": ...
c04fc9167d37db688d0e9932e61579547ab383a3
mab2400/FSMProject
/FSMProject/FSMProject.py
974
3.6875
4
import FSMModule, NodeModule # Construct a new FSM, given the starting node, a list of accepting # nodes, a list of intermediary nodes, and the input string. fsm = FSM(start, accepting, intermediary, inputStr) ''' Transition functions will be set in my test code Like this: add_transition(node1, node2, “c”) add_transi...
82d6cd5f0787d343217ff91bff391742ad4e8934
animeshmane95/Algorithms
/Divide-Conquer-MergeSort.py
1,219
4.15625
4
def merge(left, right): if len(left) == 0: return right elif len(right) == 0: return left i = 0 j = 0 sortedlist = [] while (len(sortedlist) < len(left) + len(right)): if left[i] < right[j]: sortedlist.append(left[i]) i += 1 else: ...
a9d0140ef7892f650a22b7e372d9ee0dc15329dc
Poojanavgurukul/python_all_programm
/python/others/table.py
168
3.625
4
user=input("enter a number\n") i=1 while i<=10: if user==24: print i*24 elif user==50: print i*50 elif user==29: print i*29 i+=1
64c9cd58a56dab59eaa826b3f7c4c10ee164d31e
Poojanavgurukul/python_all_programm
/python/books/book2/max_av_min.py
473
3.53125
4
i=1 sum=0 list_number=[] min=0 while i<=20: user=float(raw_input("enter a decimal numbers\n")) list_number.append(user) sum+=user i=i+1 average=sum/20.0 maxnum=list_number[0] minnum=list_number[0] for j in list_number: for k in list_number: if j>k and j>maxnum: ...
dcd2320a6d9d14898cbf334a2f92286cb2d78f57
Poojanavgurukul/python_all_programm
/python/saral_Ng/functions/calculator.py
1,100
4.1875
4
number_x=int(raw_input("enter a number\n")) number_y=int(raw_input("enter a number\n")) def calculator(number_x,number_y ,operation): if operation=="add": return "add",number_x+number_y elif operation=="multiply": return "multiply",number_x*number_y elif operation=="divide": return "...
956b2e71d9dffa0524ef9c10b3ee1a7a087adbf2
Poojanavgurukul/python_all_programm
/python/saral_Ng/request/example_ofjson_data.py
319
3.578125
4
book={} book['tom']={ 'name':'tom', 'address':'1 red street, NY', 'phone':989898989 } book['bob']={ 'name':'bob', 'address':'1 green street, NY', 'phone':20009101 } import json s=json.dumps(book) file=open("book.txt","w") file.write(s) file.close() book=json.loads(s)#String to json print (book)
b70586c8d575da47014aa00955ee86442c69e136
Poojanavgurukul/python_all_programm
/python/daily_challenge/negative_even.py
523
3.96875
4
list=[1,2,3,-1,-2,-3,4,5,-4,-5,9] positive_even=0 negative_even=0 positive_odd=0 negative_odd=0 counter=0 while counter<len(list): if list[counter]<0: if list[counter]%2==0: negative_even+=1 else: negative_odd+=1 else: if list[counter]%2==0: positive_e...
18fe301433f8e646c4bfc95d5388d378c0f71209
Poojanavgurukul/python_all_programm
/python/others/patterntnumber.py
101
3.671875
4
user=input("enter a number\n") i=user j=0 while i>=0: print j*" "+i*"10"+"1" i=i-1 j=j+1
c1ddbd9a4c1ed2ffe0e9f05498f560a3fd1587a1
Poojanavgurukul/python_all_programm
/python/saral_Ng/more_exercises/common.py
303
3.578125
4
def common_number(list1,list2): common_number_list=[] counter=0 while counter<len(list1): if list1[counter] in list2: common_number_list.append(list1[counter]) counter+=1 print common_number_list common_number([1, 342, 75, 23, 98],[75, 23, 98, 12, 78, 10, 1])
c7ad98092c6eac34c5522e773ef29a49953bcfd1
Poojanavgurukul/python_all_programm
/python/daily_challenge/reverse.py
290
4.1875
4
user_inpt=raw_input("enter a number\n")#taking string from user value=""#empty variable counter=0#initilize loop while counter<len(user_inpt):#itll the length of string that user gave value+=user_inpt[-counter-1]#it adding the vale in reverse in this variable counter+=1 print value
b38ca6d8bfb38321117010077753169c9004ff4e
Poojanavgurukul/python_all_programm
/python/books/book1/input_ifelse.py
139
3.921875
4
user=input("enter how many member you are??\n") if user>8: print "you have to wait for the table" else: print "your table is ready"
a7e2b84820603767a0136fd92413f95f3ecae393
Poojanavgurukul/python_all_programm
/python/saral_Ng/list/second_max.py
338
3.765625
4
numbers = [50, 40, 23, 70, 56, 12, 5, 10, 7] maxNumber=0 second_max=0 counter=0 while counter<len(numbers): if maxNumber<numbers[counter]: maxNumber=numbers[counter] if numbers[counter]<maxNumber and second_max<numbers[counter]: second_max=numbers[counter] counter+=1 print "Second max number...
f3bc31b3436e1043001d7e6a62287a647d90eb19
Poojanavgurukul/python_all_programm
/python/books/book1/if_else_ex2.py
290
3.9375
4
age=86 if age<2: print "You are baby" elif age>=2 and age<4: print "You are toddler" elif age >=4 and age<13: print "You are a kid" elif age >=13 and age<20: print "You are a teenager" elif age>=20 and age<65: print "You are adult" elif age>65: print "You are elder"
682692a8e9d65c0ca8b8722150e57d7e77c3a41e
Poojanavgurukul/python_all_programm
/python/saral_Ng/list/Report_card2.py
359
3.5
4
marks=[ [78,76,94,86,88], [91,71,98,65,76], [95,45,78,52,49] ] counter=0 while counter<len(marks): counter2=0 sum1=0 while counter2<len(marks[counter]): length=len(marks[counter]) sum1+=marks[counter][counter2] average=sum1/length counter...
a0b4ba950d2e18ec594fefaa20313479f48c2f95
sagarsetru/fiberviewCameraSimulation
/playground/tablemobilenumberes.py
188
3.5
4
table = {'Sagar': 9142756069, 'Suhas': 7185789224, 'Mom': 3472377887, 'Dad': 9176089335} for name, phone in table.items() print "Name: {0:10} ==> Mobile: {1:10d}".format(name, phone)
fb171c02185b76f221acb35cfae4b27e8a9d7a55
sagarsetru/fiberviewCameraSimulation
/playground/tablesquarescubes.py
222
3.953125
4
# Creates two tables of squares and cubes of numbers 1-10 for x in range(1,11): print str(x).rjust(2), str(x*x).rjust(3), str(x*x*x).rjust(4) for x in range(1,11): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)
e0b58ac465345900656b030fb3212bb28c192b01
sagarsetru/fiberviewCameraSimulation
/playground/test2.py
555
4
4
class Student: def __init__(self, name, grade, age): self.name = name self.grade = grade self.age = age def __repr__(self): return repr((self.name, self.grade, self.age)) student_objects = [ Student('john', 'A', 15), ...
41623d8bfa8f0eccbed98fe9b25074c41b82a420
HemabhKamboj/exercism-track-python
/reverse-string/reverse_string.py
155
4.375
4
def reverse(text): return text[::-1] text = str(input("Enter string to be reversed: ")) print (reverse(text))
6e7b690264f2185676e9e09c7ca293ca1c7c1cad
Callmich/Data-Structures
/doubly_linked_list/doubly_linked_list.py
7,580
3.71875
4
""" Each ListNode holds a reference to its previous node as well as its next node in the List. """ class ListNode: def __init__(self, value, prev=None, next=None): self.prev = prev self.value = value self.next = next def __del__(self): self.value = None # if both se...
0da9504b4c1fa0e5065863ae48761dda5255dad6
yuriyshapovalov/algorithms-python
/LinkedList.py
599
3.796875
4
# LinkedList # O(n) ~ class LinkedList: first = None # Method description # O(n) ~ def __init__(self): pass def __init__(self, value): first = Node(value) class Node: self.value = 0 self.next = None def __init__(self, value): self.value = value def add(self, x): if self.first is No...
ba06136b2f21bb771b7d7a58c9cbec51e7c998a0
Abdullah527382/First-codes-
/FORFUN.py
2,262
3.765625
4
#password identification excercise #Add a new user here everytime username = 'abdullah527382@gmail.com' password = 'abdullah123' username2 = 'harris82@gmail.com' password2 = 'harris123' LoL = 'a' CoD = 'b' FIFA ='c' #username = 'slifahh' #password = 'abdul123' user = raw_input("Enter your username\n") type...
54e389f6cac51a0e178c8cb41790991d535b0dfa
bblais/Classy
/debug/Debug NumpyNet MNIST.py
7,203
3.5
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #!/usr/bin/env python ''' Little example on how to use the Network class to create a model and perform a basic classification of the MNIST dataset ''' #from NumPyNet.layers.input_layer import Input_layer from NumPyNet.layers.connected_layer import Connected_layer fro...
91c095730177472f80a605d21241cc65e75dff12
PanagiotisGarris/PythonExercises
/askisi5.py
739
3.578125
4
imerominia=raw_input("Parakalw eisagete tin imerominia se morfh dd/mm/yyyy:") imerominia=imerominia.split("/") #kataxwrisi metavlitwn day=int(imerominia[0]) month=int(imerominia[1]) year=int(imerominia[2]) month = (month + 9) % 12 year = year - month/10 mera= 365*year + year/4 - year/100 + year/400 + (month*306...
0c7b613b168051d4853c85cdb2ee5e82a46e6f99
qoo/benchmarking_video_reading_python-1
/video_reading_benchmarks/multiproc/mulitprocreader.py
2,838
3.5
4
import time import cv2 class VideoCaptureHandler(): """Context Manager to safely create a cv2.video capture""" def __init__(self, filename): self.cap = cv2.VideoCapture(str(filename)) def __enter__(self): return self.cap def __exit__(self, *args): self.cap.release() def vide...
d76dea2eb0e3f0899adbfafab3eb95c650625e25
owavy27/Coursework
/algorithms_&_data_structures_cw (1).py
1,814
3.8125
4
# -*- coding: utf-8 -*- def minimum_value(a_list): #get first value in list smallest = a_list[0] smallest_index = 0 for i in range(1, len(a_list)): if(a_list[i] < smallest): smallest = a_list[i] smallest_index = i return smallest_index def selection_sort(old_list): ...
07c77bd86cea28c700b9f701dbbb78bfe825d134
myroom9/python-practice01
/02.py
331
3.84375
4
# 문제2. 키보드로 정수 수치를 입력 받아 짝수인지 홀수 인지 판별하는 코드를 작성하세요. str = input('수를 입력하세요: ') if str.isdigit() is False: print('정수가 아닙니다.') elif int(str)%2 == 0: print('짝수입니다.') elif int(str)%2 != 0: print('홀수입니다.')
44875252d43aaff0f1f490f99a58047a6c2d3dac
naslee2/python2_oop-exercises
/score.py
559
3.984375
4
import random def score(list): print "Scores and Grades" for i in range(0,10): x= random.randint(60, 100) if x > 89: print "Score: ", x,"; Your Grade is A" elif x <89 and x>79: print "Score: ", x,"; Your Grade is B" elif x <79 and x>69: print ...
12d65c8b0a0466b4050062b17b8fb412f94a84c5
naslee2/python2_oop-exercises
/checkerboard.py
113
3.75
4
char = "*" for count in range(0,8): if count % 2 !=0: print "",char*4 else: print char*4
ba69689be8ebbdb5ba0064c06152440f31dbd51c
naslee2/python2_oop-exercises
/Names.py
970
3.515625
4
def names(): users = { 'Students': [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ], 'Instructors': [ {'first_na...
9be740aa7ee738752e77913eb092256875c43faa
Amina1991/Gas-market-analysis
/Task 2 - Storage value assessment .py
3,420
4.21875
4
#!/usr/bin/env python # coding: utf-8 # # 2021 Refinitiv Natural Gas - Analyst Test # *Prepared by Amina Talipova.* # ## Below is my approach to solve the basic set of three problems: # 2. Evaluate natural gas storage; # # # ### I solve this task with the logic described in the "Task 2 explanation.xlsx" supporti...
cb623771fa15d3470293dd2e6a45fbad287c7a09
GeojePrince/GeojePrince
/test.py
621
3.640625
4
import random menu = '쫄면', '육계장', '비빔밥', '돈까스' #menu 출력 print(menu) #랜덤 출력 print(random.choice(menu)) a = '쫄면' b = '육계장' c = '비빔밥' d = '돈까스' menulist = ['쫄면', '육계장', '비빔밥', '돈까스'] print(len(menulist)) print("메뉴출력") print("메뉴 개수:",len(menulist)) for i in range(len(menulist)): print(menulist[i]) #print(menulist[0]...
a9255d1ebe2608fea37452d61b9d619062b55fac
kakru/puzzles
/leetcode/092_reverse_linked_lists_2.py
2,839
3.890625
4
#!/usr/bin/env python3 import unittest # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution: # 40 ms (35.40%) def reverseBetween(self, head: 'ListNode', m: 'int', n: 'int') -> 'ListNode': if not head or n-m <...
20472642ce3a277784689799210708870706b783
kakru/puzzles
/leetcode/067_add_binary.py
1,199
3.859375
4
#/usr/bin/env python3 import unittest class Solution: @staticmethod def bin2int(b): return sum([2**i * int(x) for i, x in enumerate(reversed(b))]) @staticmethod def int2bin(i): if i == 0: return "0" b = [] power = 0 while i > 0: bit = i&1 ...
bb5509315907b0f8e68da7c3a649390f9d35d726
kakru/puzzles
/leetcode/485_max_consecutive_ones.py
702
3.921875
4
#/usr/bin/env python3 import unittest class Solution(object): # 44 ms (faster than 96.40%) def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ now1 = max1 = 0 for n in nums: if n: now1 += 1 else: ...
70c2ca8f406a5553e450184c88cfa8bbed9abc34
kakru/puzzles
/leetcode/058_length_of_last_word.py
1,234
4.03125
4
#/usr/bin/env python3 import unittest class Solution: def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ if len(s) == 0: return 0 i = len(s) - 1 while i >= 0 and s[i] == ' ': i -= 1 counter = 0 while i >= 0...
6105004fe675da9a50039d6ad280cdc869a31d7e
kakru/puzzles
/other/07_01_merge_sorted_double_linked_lists.py
1,077
4.09375
4
#!/usr/bin/env python3 class ListNode: def __init__(self, value, pr=None, ne=None): self.value = value self.prev = pr self.next = ne def __repr__(self): return "<{}>".format(self.value) def merge(A, B): R = ListNode(None) p1, p2, r = A, B, R while p1 and p2: ...
66d29e6d57ad1cdbeee531b7f08449759068aadd
kakru/puzzles
/leetcode/462_minimum_moves_to_equal_array_elements_2.py
303
3.578125
4
#!/usr/bin/env python3 from typing import * class Solution: def minMoves2(self, nums: List[int]) -> int: # if len(nums) == 0: return 0 # no need to check, the input is a non-empty array nums.sort() median = nums[len(nums)//2] return sum(abs(median-x) for x in nums)
7b9fae50e726236639ff9fe380ffe191e869cc87
kakru/puzzles
/leetcode/509_fibonacci_number.py
868
3.734375
4
#/usr/bin/env python3 import unittest # class Solution: # def fib(self, N): # """ # :type N: int # :rtype: int # """ # fibs = [0, 1] # for i in range(2, 31): # fibs.append(fibs[i-1] + fibs[i-2]) # return fibs[N] class Solution: def fib(self, ...
1e4738acef5f3284e11b8140d832e11e3923488b
kakru/puzzles
/leetcode/890_find_and_replace_pattern.py
2,232
4.09375
4
#/usr/bin/env python3 import unittest """ You have a list of words and a pattern, and you want to know which words in words matches the pattern. A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word. (Recall that a...
42debfd169f33e43896651c072bff660385311f8
kakru/puzzles
/leetcode/999_available_captures_for_rook.py
4,064
4.34375
4
#/usr/bin/env python3 import unittest """ On an 8 x 8 chessboard, there is one white rook. There also may be empty squares, white bishops, and black pawns. These are given as characters 'R', '.', 'B', and 'p' respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces. ...
74378a3097646865beb4b786d03e1448b823aa12
kakru/puzzles
/leetcode/003_longest_substring_without_repeating_characters.py
2,055
3.71875
4
#/usr/bin/env python3 import unittest class Solution: def lengthOfLongestSubstring(self, s): # 84 ms (faster than 81.93%), mem: 12.5 MB (less than 0.99%) """ :type s: str :rtype: int """ size = len(s) if size == 0: return 0 longest_substring_at_pos = [1] * s...
cee010873a34a2727efcdbb1d0249666ee1cf572
kakru/puzzles
/leetcode/929_unique_email_addresses.py
781
3.859375
4
#/usr/bin/env python3 import unittest class Solution: def numUniqueEmails(self, emails): """ :type emails: List[str] :rtype: int """ mails = set() for m in emails: user, domain = m.split('@') if '+' in user: user = user.split('...
8a2ac569fa24da9bab605b28866ec8e384c69f56
kakru/puzzles
/leetcode/746_min_cost_climbing_stairs.py
1,386
3.75
4
#/usr/bin/env python3 import unittest from functools import lru_cache ## Recursive solution (84ms) # class Solution: # @lru_cache(maxsize=None) # def startingWith(self, i): # if i >= self.cost_len: return 0 # return self.cost[i] + min( # self.startingWith(i+1), # self.st...
c4df178170118d96409dcf281abd5db5391b3676
kakru/puzzles
/leetcode/459_repeated_substring_pattern.py
638
3.609375
4
#!/usr/bin/env python3 from typing import * class Solution: def repeatedSubstringPattern(self, s: str) -> bool: size = len(s) if size == 0: return True elif size == 1: return False for substr_size in range(size//2, 0, -1): if size % substr_size != 0: continue ...
5d55bd38d87e37f62e9dd03bcbfd0c58d5d45ea1
kakru/puzzles
/leetcode/744_find_smallest_letter_greateer_than_target.py
1,742
3.734375
4
#/usr/bin/env python3 import unittest class Solution: # O(N) # letters are sorted so it can be improved to O(log(N)) if needed def nextGreatestLetter(self, letters, target): """ :type letters: List[str] :type target: str :rtype: str """ for c in letters: ...
ce07ab93c73d9283a05cb2064e1d1f8d0d7c07cf
kakru/puzzles
/leetcode/378_kth_smallest_element_in_a_sorted_matrix.py
1,394
3.734375
4
#/usr/bin/env python3 import unittest from typing import * import heapq class Solution: # 72 ms (72.82%) def kthSmallest(self, matrix: List[List[int]], k: int) -> int: # looking for the k-th smallest element we can store the smallest # k elements, and then return the last element from the storage ...
a3e455baacd7ab3e205d7f233e3f424eaa27f86d
kakru/puzzles
/leetcode/023_merge_k_sorted_lists.py
2,937
3.921875
4
import unittest # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None # def __lt__(self, other): # return self.val < other.val # from heapq import heappop, heappush # class Solution: # def mergeKLists(self, lists: 'List[Li...
145609284fe08ec4c7daebefce6da25b63a4bf8e
kakru/puzzles
/leetcode/263_ugly_number.py
558
3.890625
4
#/usr/bin/env python3 import unittest class Solution: def isUgly(self, num: 'int') -> 'bool': if num <= 0: return False while num % 5 == 0: num /= 5 while num % 3 == 0: num /= 3 while num % 2 == 0: num /= 2 return num == 1 class BasicTest(unittest.TestCase): def test_a...
d20f422c97fd42543c945bf95973020e7ac8424b
kakru/puzzles
/leetcode/541_reverse_string_2.py
824
4.09375
4
#/usr/bin/env python3 import unittest class Solution: def reverseStr(self, s: 'str', k: 'int') -> 'str': size = len(s) if size < 2: return s S = list(s) # let's assume that strings are mutable (list of chars instead) for i in range(0, size, 2*k): S[i:i+k] = reversed(S[i...
454fcce54cee3c386411aebd27c285d51d0e1d82
kakru/puzzles
/leetcode/448_find_all_numbers_disappeared_in_an_array.py
1,959
3.84375
4
#/usr/bin/env python3 import unittest class Solution: def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ # with extra space - using sets: if not len(nums): return [] return list(set(range(1, max(max(nums), len(...
201f3db8df8cef9fc03c0937860f31b0e0afd618
kakru/puzzles
/leetcode/941_valid_mountain_array.py
1,711
3.75
4
#/usr/bin/env python3 import unittest # Very ugly solution... class Solution: def validMountainArray(self, A): """ :type A: List[int] :rtype: bool """ size = len(A) if size < 3: return False diff = [A[i]-A[i-1] for i in range(1, size)] if...
848dc47e915d65fe512e63fe82afee3e6a238be6
kakru/puzzles
/leetcode/748_shortest_completing_word.py
1,161
3.796875
4
import unittest from collections import Counter class Solution: # 68ms (faster than 64.74%) def shortestCompletingWord(self, licensePlate, words): """ :type licensePlate: str :type words: List[str] :rtype: str """ plate = Counter([x for x in licensePlate.lower() if ...
340180e6f30a350bf340bd2f673bfd422b79be72
nipsn/EjerciciosPythonLP
/e8h1.py
106
3.734375
4
def palindroma(palabra): str(palabra) if palabra == palabra[::-1]: print("si") palindroma("abba")
fffbcb0ed0821e4e924ae1c1097c89c59565c98f
alyferryhalo/test_tasks
/2021_biocadBackend/fib_cy.py
239
3.859375
4
# Данный вариант считает числа Фибоначчи циклом n = int(input()) fib1 = 1 fib2 = 1 i = 0 while i < n - 2: fib_sum = fib1 + fib2 fib1 = fib2 fib2 = fib_sum i = i + 1 print(fib_sum)
e74bf93bcec80c7ff138d67c2b379fb787b4e3b6
yayshine/pyQuick
/day1part1.py
882
4.0625
4
#!/usr/bin/python2.7.5 -tt # Copyright 2014 Yayshine. All Rights Reserved. import sys def Hello(name): if name == 'Yay' or name == 'Yayshin': print 'Oh my god you are here!' name = name + ' the awesome' else: print 'Else' DoesNotExist(name) name = name + '!!!!!!!' print 'Hello', name # when , is used to a...
6851bf6d88b3f3de069275df3262690cb8d1ab94
ronelvcabrera/leetcoding
/plus-one.py
1,882
3.984375
4
""" Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer. The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. You may assume the integer does not contain any leading zero, e...
6e64a9dec5ff9d2873cdd187d9579f06d46ece75
ronelvcabrera/leetcoding
/testing-recursion.py
649
3.90625
4
def recurse_def(num, data, printme=None): print('-----') if printme: print('printme', printme) if data.get(num): print('there is this number', num, data.get(num)) return data[num] if num > 5: return data else: num += 1 data[num] = num print('nu...
3f057909979f4f7bc2a1737f9b2562ac0f1fbbc1
ronelvcabrera/leetcoding
/remove-duplicates-from-sorted-array.py
962
3.96875
4
""" Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Clarification: Confused why the returned value is an integer...
bf6041a90a932b82b1afd5eee9195a26bcb94205
AlexMaximenko/Python_Review
/src/ai.py
2,913
3.6875
4
from typing import Optional from .boardstate import BoardState class PositionEvaluation: def __call__(self, board: BoardState, player) -> float: #todo evaluation = board.player_checks + 2 * board.player_queens evaluation -= (board.opponent_checks + 2 * board.opponent_queens) retur...
3e271f40e4ca9acabef94c6d39aa5cc3a1c26171
pointtonull/dotfiles
/user/bin/chances
584
3.90625
4
#!/usr/bin/env python #-*- coding: UTF-8 -*- """Devuelve verdadero o falso aleatoreamente de acuerdo a la probabilidad pasada como argumento, si se pasan dos argumentos se calculara la probabilidad como la razon del primero sobre el segundo""" import sys import random if __name__ == "__main__": if len(sys.argv) =...
d2755490410b8c84c9a1ec2ce3027b51a91b3ef1
IanGrimm/pdsnd_github
/bikeshare.py
7,091
4.125
4
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the...
ca5d28a6096c99df2c27c7c2efa43f02b66aa741
futuereprojects/gspread2
/gspread2/utils.py
1,172
3.75
4
def _get_column_letter(col_idx): """Convert a column number into a column letter (3 -> 'C') Right shift the column col_idx by 26 to find column letters in reverse order. These numbers are 1-based, and can be converted to ASCII ordinals by adding 64. """ # these indicies corrospond to A -> ZZ...
a6fa860af6452a0d462b92b857b954f9762f4eaf
sachin-101/NEAT
/Snake game (NEAT)/game.py
2,250
3.671875
4
import pygame import math import random import time from population import Population from snake import Snake import time import constants pygame.init() display_width = constants.display_width display_height = constants.display_height #colours white= constants.white black = constants.black red = constants.red blue =...
befd54188a1d64fc3f5c82ef361fddb5f6c7f9ac
ewarlock/ITEC-2905-80-Lab-08
/bitcoin_price_rate.py
1,511
3.671875
4
import requests # you can p print to see nice JSON. pretty print! def get_bitcoin_conversions(): try: response = requests.get('http://api.coindesk.com/v1/bpi/currentprice.json') # print(response.status_code) # 200 codes represent successful request response.raise_for_status() # raise an e...
fa356ef16e07e0b987db924134941a44e250810c
nagyrobert1990/python-practice
/test.py
200
3.515625
4
A = 0 B = 0 a = [5,6,7] b = [3,6,10] for i in range(0,len(a)): if a[i] > b[i]: A += 1 print("hozzáad Ahoz",A) elif b[i] > a[i]: B += 1 print("hozzáad Bhez",B)
8f61865257eaabaa031cf8f6ac88737dea9b2d95
CorradoLanera/PirplePythonIsEasy
/hw4-lists/main.py
3,755
3.953125
4
# -*- coding: utf-8 -*- """ main.py: Homework #4: Lists (Python Is Easy course by Pirple) Details: Create a global variable called myUniqueList. It should be an empty list to start. Next, create a function that allows you to add things to that list. Anything that's passed to this function should get added to myUniq...
95eb4d868ea6eb31575cf23f6f3025a90086244a
Freshnick71/Freshnick71
/pizza_pizza.py
4,065
3.546875
4
def counter(x,y,z): x = 5 y = 4 z = 1 count = int(x)+int(y)+int(z) print(count) return count counter(5,4,1) class Pizza: __slots__ = ['price', 'cheese', 'meats', 'veggies'] def __init__(self): # cheese, meats, veggies) self.price = 5.0 self.cheese = 'c' #cheese # ...
51a9d2426f909a5ba38c205761ad70d652df5634
Jae0143/Introduction-to-Computer-Science-and-Programming-Using-Python-MITX
/fixing_error.py
225
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 4 17:31:44 2018 @author: seongjaegyeong """ def f(n): """ n: integer, n >= 0. """ if n == 0: return 1 else: return n * f(n-1)
1807acde482f8391d2453e6cb44c5dabccb18ae7
Jae0143/Introduction-to-Computer-Science-and-Programming-Using-Python-MITX
/polygon.py
381
3.921875
4
from math import * def polygon_work (n,s): """ Input: n - number of sides, s - length of each side Returns the sum of area of polygon and square of the perimiter of polygon """ area_polygon = (0.25 * n * s ** 2) / tan(pi / n) perimeter_polygon_squared = (n * s) ** 2 sum_result = area_polygo...
e1818c64fdce8da0dee6444b6ad7ffcff7731e2a
PhD-Strange/infa_2020_PhD_Strange
/lab2_1/turtle_12.py
276
3.96875
4
import turtle turtle.shape('turtle') turtle.color('red') turtle.penup() turtle.goto(-300, 0) turtle.pendown() turtle.left(90) def round(n): for i in range(n): turtle.forward(3) turtle.right(180/n) k = 10#число витков for g in range(k): round(50) round(10)
b5d0d7271ea6e5b4cb4e1879370da1814b86ca65
Hyvjan/sql
/sqla2.py
363
4.03125
4
# Create a SQLite3 database and table # import the sqLite3 library import sqlite3 # Create a new database if the database doesn't already exist conn=sqlite3.connect("cars.db") # get cursor cursor=conn.cursor() # create a table cursor.execute("""CREATE TABLE inventory (Make TEXT, Model INT, Quantity INT) """) #...
c7eff044c1d21ec134f41361a9353905e5cb6cec
kyu9610/coding_practice
/31.py
589
3.671875
4
number = 1 turn = 1 while(number != 31): # computer 4*turn - 2 까지만 부른다. print("computer : ",end='') for i in range(number,4*turn-1): print(number,end=' ') number += 1 print('') turn += 1 user_number = list(map(int,input("user : ").split())) for j in user_number: if...
85938a535e778c97456aa84e769f4f9d5d969639
graywh/ccsc-se-contest
/2000/5/7-5.py
915
3.515625
4
#!/usr/bin/env python import sys class Point: def __init__(self): self.x = 0.0 self.y = 0.0 def distance(a, b): return ((a.x - b.x) ** 2 + (a.y - b.y) ** 2) ** 0.5 cnt = 1 while True: line = sys.stdin.readline() if line == "": break ships = line.split() ships = int(sh...
3285bad94f9b6ad49f32823313d73eb40cae3bb7
UpOut/UpOutDF
/upoutdf/duration.py
906
3.578125
4
# coding: utf-8 import math class Duration(object): #Should be unix timestamps in UTC start = None end = None def __init__(self,start,end): self.start = start self.end = end @property def seconds(self): return self.end - self.start @property def minutes(self...
de28fa55b67d6665c64acc08f949cd218811a847
SnehaThakkallapally/June252019
/Second_Method.py
182
3.65625
4
s = 'ABCDEFGEFAEFG' sb = 'EFG' results = 0 sub_len = len(sb) for i in range(len(s)): if s[i:i+sub_len] == sb: results += 1 print("Occurrence of sub string: ",results)
593bcbf47427cb04cbdc7cb4481ac305914cbe11
millyhx/module2
/ch13_oop_project/MovingShapes.py
2,707
3.796875
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 06 17:36:10 2019 @author: Milly """ from Shapes import * from pylab import random as r class MovingShape: def __init__(self, frame, shape, diameter): self.shape = shape self.diameter = diameter self.figure = Shape(shape, diameter) ...
afec077951a10350ff30ef07ed5d4dea12cc2b59
millyhx/module2
/ch02_operations_strings_variables/ch02_melisa.py
1,409
4.4375
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 19 11:16:41 2018 @author: milly """ #----------------------------- #SIMPLE OPERATIONS WITH PYTHON #----------------------------- 5 - 6 8 * 9 6 / 2 5 / 2 5.0 / 2 5 % 2 2 * (10 + 3) 2 ** 4 #------------------------- #PRACTISING WITH VARIABLES #------------------------- ...
fab7392b18655935a54ccbab64f80c572d61ee42
millyhx/module2
/ch01_introduction/ch1_name.py
858
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Thu Nov 29 10:15:17 2018 @author: milly """ #------------------ #STRING INPUT #------------------ #NAMING A VARIABLE AND ASSIGN THE VARIABLE OF INPUT name = input("What is your name? ") print("Hello!, Your name is " + name.upper()) age = input("How old are...
5dd0169a93b1d4a504c30328afb84666f0d2e6f0
millyhx/module2
/ch05_inheritance_association/ch05_practice/inheritance_food.py
932
3.84375
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 5 13:49:03 2018 @author: milly """ #Inheritance Practice class FavouriteFood(): def __init__(self, name, age=0): self.name = name def eat(self): print('yum') class Food(FavouriteFood): def __init__(self, name, age=0,foodN...
57d5c5768df29f1a4bbdb4dda776831bdc668d19
millyhx/module2
/ch16_flask/app.py
1,203
3.609375
4
from flask import Flask, render_template, request app = Flask("FormApp") #HERE WE ARE IMPORTING THE MODULES WE NEED FROM THE PYTHON LIBRARIES #THEN WE ARE NAMING THE FLASK APP THAT WE WANT TO CREATE ########### #TASK 5 ########### @app.route("/about") def about(): return render_template("about.html", title="abou...
37ed0729229029d3ec037044d03708bc4fa9c1c1
Dmkk01/Small-Python-Projects
/Covid Statistics/covid_statistics.py
2,561
3.5
4
import pandas as pd import datetime def get_date_format(dates): DATE_FORMATS = ["%Y-%m-%d", "%d.%m.%Y", "%d.%m.%y", "%d-%m-%Y", "%d/%m/%Y", "%m/%d/%Y"] for date_format in DATE_FORMATS: reject_format = False for date in dates: try: datetime.datetime.strptime(date, da...
2f02dd0ff83d88f0912e5a1f41651fd1cfff8955
Dmkk01/Small-Python-Projects
/RobotWorld/spinbot.py
667
3.734375
4
from direction import Direction from robot_brain import RobotBrain class Spinbot(RobotBrain): """ The class C{Spinbot} represents the "brains" (or AI) of very simple, boring robots that stand still and merely spin clockwise. """ def move_body(self): """ Moves the given "body"...
c05bc131cb77ec61cefd77f3f1cca91975f86f21
menglingshu/Python_Exercises
/exercise_matplotlib.py
353
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 24 22:00:59 2018 @author: Lingshu """ import matplotlib.pyplot as plt import numpy as np x = np.linspace(-1, 1, 50) y1 = 2 * x + 1 y2 = x ** 2 plt.figure() plt.plot(x, y1) plt.figure() plt.plot(x, y2) plt.plot(x, y1, color = 'red', linewidth = 1...
f92c8f797285bd6f692ec1dd17b6c73240b777ac
jmccardle/AdventOfCode2020
/puzzle2.py
1,944
4.0625
4
#Advent of Code Puzzle #1 ## The Elves in accounting are thankful for your help; one of them even offers ## you a starfish coin they had left over from a past vacation. They offer you ## a second one if you can find three numbers in your expense report that meet ## the same criteria. ## ## Using the above example agai...
3f39315f8297633165b708b262a793d4e6d42b28
jmccardle/AdventOfCode2020
/puzzle14.py
5,907
3.578125
4
##--- Part Two --- ## ##It's getting pretty expensive to fly these days - not because of ticket ##prices, but because of the ridiculous number of bags you need to buy! ## ##Consider again your shiny gold bag and the rules from the above example: ## ## faded blue bags contain 0 other bags. ## dotted black bags con...
c27f602de7910f9e45fd3b1d2ea3f373f0813696
wipegup/Capstone
/BokehInteractive/AggregationTree.py
2,625
3.5
4
class TreeNode(object): def __init__(self, df, parent = 'head', value = ('',None), name = 'head'): self.parent = parent self.df = df self.value = value # tuple of (name, groupbyVal) self.name = name self.table = None self.children = [] self.opts = None ...
d217bb37143ed427746cd750992e8eb61832fb06
AIHackerTest/Hansoluo_Py101-004
/Chap1/project/weather.py
1,536
3.6875
4
# -*- coding:utf-8 -*- import os weather_dic = {} history_dic = {} # 读取本地文件,分割字符,将内容存入字典 root_dir = os.path.dirname(os.getcwd()) rel_dir = os.path.join(root_dir, 'resource', 'weather_info.txt') with open(rel_dir, 'r', encoding = 'utf8') as w: for info in w.readlines(): info = info.strip() # 去掉尾部的换行符号 ...