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
65b0ea137da5b7ad22adec040eff5fd2464ea779
npkfrolov/Python_homework
/lesson2/homework2_4.py
650
3.8125
4
# coding=utf-8 # Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове. user_string = raw_input("Enter several words devided by spaces\n(words that are longer than 10 symbo...
d0437b0cf500d5747d45cc2e92fab00e40d8e1c7
npkfrolov/Python_homework
/lesson5/homework5_3.py
935
4.03125
4
"""Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов. Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников.""" with open("homework3.txt") as file: low_salary_list = [] ...
e50a950fd897fdcfc29212808db2d441d4708b29
npkfrolov/Python_homework
/lesson3/task_5.py
657
3.984375
4
# В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию (индекс) в массиве. import random array = [random.randint(-100, 100) for i in range(50)] index = -1 j = 0 number = 0 while j < len(array): if array[j] < 0 and index == -1: index = j elif array[j] < 0 and ar...
e13c74d6a9d436d496c7be43268c851e6211e86f
npkfrolov/Python_homework
/Основы_Python_Мария_Андреева/Lesson1/homework1_3.py
154
4.125
4
number_n = raw_input("Enter number: ") i = 1 text = number_n while True: i += 1 if i > 3: break text = text + number_n print (text)
4db34efb8c3cd3540da723ebaf8776420da4675d
ElisaMtz/Python_101
/Assignment Python 1-2.py
276
4.09375
4
x = int(input("Please enter first number: ")) y = int(input("Please enter second number: ")) if x > y: print("The first number is larger than the second") elif x < y: print("The second number is larger than the first") else: print("Both number are the same")
65231ca546c5e57c21722af52b372e03da2aa0fb
Yehia-Fahmy/Leetcode
/Valid Parentheses.py
1,544
3.875
4
def isValid(self, s): is_Valid = True index = 0 square = 0 curly = 0 normal = 0 for letter in s: if s[index] == "[": square += 1 if s[index] == "]": square -= 1 if s[index] == "{": curly += 1 if s[index] == "}": curl...
10cc09e0460550786458459884a400de41582648
DorotheaMueller/Cabo
/src/message.py
1,970
3.625
4
from helper import unknown class CardInfo(object): def __init__(self, public, player_index, card_index, card): self.public = public self.player_index = player_index self.card_index = card_index self.card = card def apply(self, knowledge_matrix, further_knowledge): know...
7dd91bc1d10d2cb639bf82cfa557b4d2f2021ccd
vinodh1988/pythonoops
/Inheritance.py
518
3.515625
4
class A: def __init__(self,a): self.a=a def show(self): print('a is ', self.a) class C: def __init__(self,c): self.c=c def show(self): print('c is' ,self.c) class B(A,C): def __init__(self,a,b,c): A.__init__(self,a) C.__init__(self,c) ...
81b9c82e02189d79761e3c59359c5a87a023cab2
superhg2012/cs208
/File-I-O/main.py
2,001
3.609375
4
from fst import FST ##### Creating an FST for minidictionary.txt ##### mini_dict = open('minidictionary.txt', 'r') fst_states = [] # source for generating list of chars http://snipplr.com/view/5058/ fst_in_alph = map(chr, range(97, 123)) fst_out_alph = map(chr, range(65, 91)) fst_out_alph.append(" ") fst_start = "s...
08c3dd83a5d3596793d034be0476e1dc7754a9a4
shounakwarde/competitive-programming
/binary_search_tree.py
2,169
3.890625
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None # def insert(root, key): # newNode = Node(key) # if root == None: # return newNode # else: # if root.data == key: # return root # elif key > root.data: ...
ee6e08c183fe4ee4624cc5e68044b9b19f506c07
ShanYouGuan/python
/others/Test_Class.py
1,003
4.21875
4
class people: name = "" age = 0 __weigt = 0 def __init__(self,a, n, w): self.name = n self.age = a self.__weight = w def speak1(self): print("{}说:我今年{}岁,我{}斤".format(self.name, self.age,self.__weight)) class student(people): grade = '' def __init__(self,n, a, ...
586c24efc4150425f2b560dc528a57f628e3aa9a
ShanYouGuan/python
/Algorithm/TreeNode.py
2,090
3.65625
4
class TreeNode(object): def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right tree = TreeNode(1, TreeNode(2, TreeNode(3, TreeNode(4)), TreeNode(5)), TreeNode(6, TreeNode(7), TreeNode(8))) def pre_order(root): if root == None: ret...
23bf9530dd207986443e8d3cc59b5ae37cc3b410
ShanYouGuan/python
/TEST/0005.py
424
4
4
def count_word(): file = open('English_txt', 'r') readfile = file.readlines() num_dict ={} for i in readfile: str_line = i for code in str_line: if code not in num_dict: num_dict['{}'.format(code)] = 1 else: num = 1 num_dict['{}'.format(c...
695355269bae1334c7370ee5b99c7d67aa1fc42b
ShanYouGuan/python
/Algorithm/bubble_sort.py
286
4.125
4
def bubble_sort(list): for i in range(0, len(list)): for j in range(len(list)-i-1): if list[j] > list[j+1]: list[j], list[j+1] = list[j+1], list[j] lista = [1, 3, 6, 5, 4, 2] bubble_sort(lista) for i in range(0, len(lista)): print(lista[i])
204900fa9b222ce9e9535caed70d381d32e4b7d2
kamyu104/LeetCode-Solutions
/Python/check-if-string-is-a-prefix-of-array.py
869
3.65625
4
# Time: O(n) # Space: O(1) class Solution(object): def isPrefixString(self, s, words): """ :type s: str :type words: List[str] :rtype: bool """ i = j = 0 for c in s: if i == len(words) or words[i][j] != c: return False ...
b495031e815497ea7bca31996dd4dd8d5f96d69a
kamyu104/LeetCode-Solutions
/Python/print-words-vertically.py
273
3.671875
4
# Time: O(n) # Space: O(n) import itertools class Solution(object): def printVertically(self, s): """ :type s: str :rtype: List[str] """ return ["".join(c).rstrip() for c in itertools.izip_longest(*s.split(), fillvalue=' ')]
226e165f5b988447cb0ef3d981c17eca28ef071d
kamyu104/LeetCode-Solutions
/Python/find-all-possible-recipes-from-given-supplies.py
990
3.5
4
# Time: O(|E|) # Space: O(|E|) import collections import itertools class Solution(object): def findAllRecipes(self, recipes, ingredients, supplies): """ :type recipes: List[str] :type ingredients: List[List[str]] :type supplies: List[str] :rtype: List[str] """ ...
da85b10959eec61589b36a6abe65f47f1099862c
kamyu104/LeetCode-Solutions
/Python/check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree.py
2,009
3.75
4
# Time: O(n) # Space: O(w) # Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # bfs solution class Solution(object): def isValidSequence(self, root, arr): """ ...
6e122976161ab494b6c4ccaf5c11b2324420129c
kamyu104/LeetCode-Solutions
/Python/maximum-product-of-three-numbers.py
741
3.5625
4
# Time: O(n) # Space: O(1) class Solution(object): def maximumProduct(self, nums): """ :type nums: List[int] :rtype: int """ min1, min2 = float("inf"), float("inf") max1, max2, max3 = float("-inf"), float("-inf"), float("-inf") for n in nums: if...
1b3b0fe8937a12bf610d776c2c398425507bdad4
kamyu104/LeetCode-Solutions
/Python/maximum-number-of-words-you-can-type.py
507
3.59375
4
# Time: O(n) # Space: O(1) class Solution(object): def canBeTypedWords(self, text, brokenLetters): """ :type text: str :type brokenLetters: str :rtype: int """ lookup = set(brokenLetters) result, broken = 0, False for c in text: if c == '...
9be41a1322d1c5a72a8fa1c69e8a3f5f33a47b95
kamyu104/LeetCode-Solutions
/Python/balanced-binary-tree.py
705
3.640625
4
# Time: O(n) # Space: O(h), h is height of binary tree class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): # @param root, a tree node # @return a boolean def isBalanced(self, root): def getHeight(root)...
9a526ba5fde772a24aa5f385f8fddd99a397dca6
kamyu104/LeetCode-Solutions
/Python/walking-robot-simulation.py
815
3.53125
4
# Time: O(n + k) # Space: O(k) class Solution(object): def robotSim(self, commands, obstacles): """ :type commands: List[int] :type obstacles: List[List[int]] :rtype: int """ directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] x, y, i = 0, 0, 0 lookup = ...
37ba52af72f235d8f575c6786c453e80a77e006f
kamyu104/LeetCode-Solutions
/Python/map-sum-pairs.py
1,133
3.671875
4
# Time: O(n), n is the length of key # Space: O(t), t is the number of nodes in trie import collections class MapSum(object): def __init__(self): """ Initialize your data structure here. """ _trie = lambda: collections.defaultdict(_trie) self.__root = _trie() def i...
ad8d359f5f179ba7e3fc11580c96b41f8dc34fb2
kamyu104/LeetCode-Solutions
/Python/odd-even-linked-list.py
520
3.640625
4
# Time: O(n) # Space: O(1) class Solution(object): def oddEvenList(self, head): """ :type head: ListNode :rtype: ListNode """ if head: odd_tail, cur = head, head.next while cur and cur.next: even_head = odd_tail.next o...
0212038840dbaf9a99412675007e6ea2c759aca5
kamyu104/LeetCode-Solutions
/Python/merge-sorted-array.py
626
3.625
4
# Time: O(n) # Space: O(1) class Solution(object): # @param A a list of integers # @param m an integer, length of A # @param B a list of integers # @param n an integer, length of B # @return nothing def merge(self, A, m, B, n): last, i, j = m + n - 1, m - 1, n - 1 while i ...
297ff7620da54b1c9ebd752947018bf34dec1ab7
kamyu104/LeetCode-Solutions
/Python/kth-largest-element-in-a-stream.py
550
3.59375
4
# Time: O(nlogk) # Space: O(k) import heapq class KthLargest(object): def __init__(self, k, nums): """ :type k: int :type nums: List[int] """ self.__k = k self.__min_heap = [] for n in nums: self.add(n) def add(self, val): ...
8f27a6dc4d7975c6450d12945fc5a18c92ae889a
kamyu104/LeetCode-Solutions
/Python/reach-a-number.py
662
3.515625
4
# Time: O(logn) # Space: O(1) import math class Solution(object): def reachNumber(self, target): """ :type target: int :rtype: int """ target = abs(target) k = int(math.ceil((-1+math.sqrt(1+8*target))/2)) target -= k*(k+1)/2 return k if target%2 ==...
5c8515dab57c5cc2835d823382ba8db2caca4b3f
kamyu104/LeetCode-Solutions
/Python/unique-word-abbreviation.py
851
3.75
4
# Time: ctor: O(n), n is number of words in the dictionary. # lookup: O(1) # Space: O(k), k is number of unique words. import collections class ValidWordAbbr(object): def __init__(self, dictionary): """ initialize your data structure here. :type dictionary: List[str] """...
040665f568922fde483a5276cb6b7143cacc618d
kamyu104/LeetCode-Solutions
/Python/basic-calculator.py
2,396
3.578125
4
# Time: O(n) # Space: O(n) import operator class Solution(object): def calculate(self, s): """ :type s: str :rtype: int """ def compute(operands, operators): right, left = operands.pop(), operands.pop() operands.append(ops[operators.pop()](left, ri...
431043828e580dfc9be6507ffaf438de70f9a72e
kamyu104/LeetCode-Solutions
/Python/distance-between-bus-stops.py
603
3.765625
4
# Time: O(n) # Space: O(1) import itertools class Solution(object): def distanceBetweenBusStops(self, distance, start, destination): """ :type distance: List[int] :type start: int :type destination: int :rtype: int """ if start > destination: s...
915c6a53e79c078493fcf919ef6c4835da4a55d8
kamyu104/LeetCode-Solutions
/Python/find-the-minimum-and-maximum-number-of-nodes-between-critical-points.py
872
3.6875
4
# Time: O(n) # Space: O(1) # Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def nodesBetweenCriticalPoints(self, head): """ :type head: Optional[ListNode] :rtype:...
d8b86391fb95ded3c227fdadff3a8873cb7b3ab0
kamyu104/LeetCode-Solutions
/Python/sum-of-nodes-with-even-valued-grandparent.py
669
3.640625
4
# Time: O(n) # Space: O(h) # 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 sumEvenGrandparent(self, root): """ :type root: TreeNode :rtype: int ...
da07ef939a5165355a975e00b2f4907eaba03a7e
kamyu104/LeetCode-Solutions
/Python/sort-array-by-increasing-frequency.py
293
3.625
4
# Time: O(nlogn) # Space: O(n) import collections class Solution(object): def frequencySort(self, nums): """ :type nums: List[int] :rtype: List[int] """ count = collections.Counter(nums) return sorted(nums, key=lambda x: (count[x], -x))
bacb6f1a56d0ba675cc81c7f9b5b58100f311b73
kamyu104/LeetCode-Solutions
/Python/data-stream-as-disjoint-intervals.py
1,353
3.609375
4
# Time: addNum: O(n), getIntervals: O(n), n is the number of disjoint intervals. # Space: O(n) class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e class SummaryRanges(object): def __init__(self): """ Initialize your data structure here. ...
57bdb2b823b2282d2fa1187ac391c402a0470c3e
kamyu104/LeetCode-Solutions
/Python/minimum-operations-to-remove-adjacent-ones-in-matrix.py
5,605
3.53125
4
# Time: O(E * sqrt(V)) = O(m * n * sqrt(m * n)) # Space: O(V) = O(m * n) from functools import partial # Time: O(E * sqrt(V)) # Space: O(V) # Source code from http://code.activestate.com/recipes/123641-hopcroft-karp-bipartite-matching/ # Hopcroft-Karp bipartite max-cardinality matching and max independent set # Dav...
0fdcedf6d85b76c2da18a2fa61f9254e16211d38
kamyu104/LeetCode-Solutions
/Python/nested-list-weight-sum.py
520
3.53125
4
# Time: O(n) # Space: O(h) class Solution(object): def depthSum(self, nestedList): """ :type nestedList: List[NestedInteger] :rtype: int """ def depthSumHelper(nestedList, depth): res = 0 for l in nestedList: if l.isInteger(): ...
411bada6779529c49677845d9b1740d875812a23
kamyu104/LeetCode-Solutions
/Python/vowels-of-all-substrings.py
277
3.53125
4
# Time: O(n) # Space: O(1) class Solution(object): def countVowels(self, word): """ :type word: str :rtype: int """ VOWELS = set("aeiou") return sum((i-0+1) * ((len(word)-1)-i+1) for i, c in enumerate(word) if c in VOWELS)
fa301ec6e071e5f7073cdafbc60ad55f75488c54
kamyu104/LeetCode-Solutions
/Python/check-completeness-of-a-binary-tree.py
1,356
3.8125
4
# Time: O(n) # Space: O(w) # 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 isCompleteTree(self, root): """ :type root: TreeNode :rtype: bool ...
6d8290b24afc57c298d691bdb36507eb2eb7db2b
kamyu104/LeetCode-Solutions
/Python/find-the-maximum-achievable-number.py
218
3.515625
4
# Time: O(1) # Space: O(1) # greedy class Solution(object): def theMaximumAchievableX(self, num, t): """ :type num: int :type t: int :rtype: int """ return num+2*t
e8e3fa3d879387e26790f39981b76e728b7235ad
kamyu104/LeetCode-Solutions
/Python/evaluate-boolean-binary-tree.py
1,679
3.703125
4
# Time: O(n) # Space: O(h) class TreeNode(object): def __init__(self, val=0, left=None, right=None): pass # dfs with stack class Solution(object): def evaluateTree(self, root): """ :type root: Optional[TreeNode] :rtype: bool """ INF = float("inf") OP =...
92342ecd2b1a8ba69cee732060f8701a51611cbe
kamyu104/LeetCode-Solutions
/Python/increasing-order-search-tree.py
613
3.609375
4
# Time: O(n) # Space: O(h) class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def increasingBST(self, root): """ :type root: TreeNode :rtype: TreeNode """ def increasingBSTHelp...
40b7e206b4a1f2834f3cb95d4c11487925fe7390
kamyu104/LeetCode-Solutions
/Python/powx-n.py
827
3.546875
4
# Time: O(logn) = O(1) # Space: O(1) class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ result = 1 abs_n = abs(n) while abs_n: if abs_n & 1: result *= x abs_n >>= 1...
c4313ddc7b764aff020c8e156f3d60e955b11cf5
kamyu104/LeetCode-Solutions
/Python/minimum-distance-to-type-a-word-using-two-fingers.py
1,253
3.625
4
# Time: O(26n) # Space: O(26) class Solution(object): def minimumDistance(self, word): """ :type word: str :rtype: int """ def distance(a, b): return abs(a//6 - b//6) + abs(a%6 - b%6) dp = [0]*26 for i in xrange(len(word)-1): b, c = ...
5b554e96ead1667742bc1c5169737a58cee4a22e
kamyu104/LeetCode-Solutions
/Python/kids-with-the-greatest-number-of-candies.py
316
3.578125
4
# Time: O(n) # Space: O(1) class Solution(object): def kidsWithCandies(self, candies, extraCandies): """ :type candies: List[int] :type extraCandies: int :rtype: List[bool] """ max_num = max(candies) return [x + extraCandies >= max_num for x in candies]
b8169f3ac601126ffcc33255fcbdd37013c828b6
kamyu104/LeetCode-Solutions
/Python/first-letter-to-appear-twice.py
303
3.515625
4
# Time: O(n) # Space: O(1) # hash table class Solution(object): def repeatedCharacter(self, s): """ :type s: str :rtype: str """ lookup = set() for c in s: if c in lookup: break lookup.add(c) return c
04a0204a85d9df8f2cc8b13d4d4e53d98455c15c
kamyu104/LeetCode-Solutions
/Python/binary-search-tree-to-greater-sum-tree.py
662
3.78125
4
# Time: O(n) # Space: O(h) # 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 bstToGst(self, root): """ :type root: TreeNode :rtype: TreeNode "...
5e2563502b9367687393b6e1ff7e998d0c7525a7
kamyu104/LeetCode-Solutions
/Python/sentence-screen-fitting.py
941
3.625
4
# Time: O(r + n * c) # Space: O(n) class Solution(object): def wordsTyping(self, sentence, rows, cols): """ :type sentence: List[str] :type rows: int :type cols: int :rtype: int """ def words_fit(sentence, start, cols): if len(sentence[start]) > ...
77fcf11144d809afab5b0579ea5e467c0e26a750
kamyu104/LeetCode-Solutions
/Python/cousins-in-binary-tree-ii.py
812
3.75
4
# Time: O(n) # Space: O(w) # Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): pass # bfs class Solution(object): def replaceValueInTree(self, root): """ :type root: Optional[TreeNode] :rtype: Optional[TreeNode] ...
34ae175b82b8468c50853a50c084572aff5d9854
kamyu104/LeetCode-Solutions
/Python/reorder-list.py
987
3.578125
4
# Time: O(n) # Space: O(1) class ListNode(object): def __init__(self, x): self.val = x self.next = None def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next)) class Solution(object): # @param head, a ListNode # @return nothing def reo...
e5973066f6f802399de193a83eb5056d4245631c
kamyu104/LeetCode-Solutions
/Python/count-substrings-that-differ-by-one-character.py
874
3.5625
4
# Time: O(m * n) # Space: O(1) class Solution(object): def countSubstrings(self, s, t): """ :type s: str :type t: str :rtype: int """ def count(i, j): # for each possible alignment, count the number of substrs that differ by 1 char result = left_cnt = r...
ec068e6bb3c94baa86d3809e7237d4ac7a4ec72a
kamyu104/LeetCode-Solutions
/Python/print-zero-even-odd.py
1,359
3.640625
4
# Time: O(n) # Space: O(1) import threading class ZeroEvenOdd(object): def __init__(self, n): self.__n = n self.__curr = 0 self.__cv = threading.Condition() # printNumber(x) outputs "x", where x is an integer. def zero(self, printNumber): """ :type printNumb...
83860fd6ded072ddcc73fcf39d24ff2d3cdcbf1f
kamyu104/LeetCode-Solutions
/Python/merge-two-2d-arrays-by-summing-values.py
843
3.796875
4
# Time: O(n) # Space: O(1) # two pointers class Solution(object): def mergeArrays(self, nums1, nums2): """ :type nums1: List[List[int]] :type nums2: List[List[int]] :rtype: List[List[int]] """ result = [] i = j = 0 while i < len(nums1) or j < len(num...
39536ec9a94004838219745cc47d1b004c98eca0
kamyu104/LeetCode-Solutions
/Python/move-sub-tree-of-n-ary-tree.py
6,316
3.609375
4
# Time: O(n) # Space: O(h) # Definition for a Node. class Node(object): def __init__(self, val=None, children=None): self.val = val self.children = children if children is not None else [] # one pass solution without recursion class Solution(object): def moveSubTree(self, root, p, q): ...
88572803620d2b6e2f2ba13d61baf4402991801b
kamyu104/LeetCode-Solutions
/Python/maximum-font-to-fit-a-sentence-in-a-screen.py
1,216
3.640625
4
# Time: O(n + logm), n is the length of text, m is the number of fonts # Space: O(1) import collections class FontInfo(object): def getWidth(self, fontSize, ch): """ :type fontSize: int :type ch: char :rtype int """ pass def getHeight(self, fontSize): ...
9b2e6440e62877f0710dcbcdfbdc4dcea66d9e80
kamyu104/LeetCode-Solutions
/Python/minimum-moves-to-convert-string.py
340
3.515625
4
# Time: O(n) # Space: O(1) class Solution(object): def minimumMoves(self, s): """ :type s: str :rtype: int """ result = i = 0 while i < len(s): if s[i] == 'X': result += 1 i += 3 else: i += 1 ...
e0004b0b6df60bd3030ff004ed0bbefc869e38b4
kamyu104/LeetCode-Solutions
/Python/minimum-string-length-after-removing-substrings.py
381
3.5
4
# Time: O(n) # Space: O(n) # stack class Solution(object): def minLength(self, s): """ :type s: str :rtype: int """ stk = [] for c in s: if stk and ((stk[-1] == 'A' and c == 'B') or (stk[-1] == 'C' and c == 'D')): stk.pop() ...
1f4c21dfe3e655d4249e34777b768ba19ea751e7
kamyu104/LeetCode-Solutions
/Python/count-of-range-sum.py
3,020
3.5625
4
# Time: O(nlogn) # Space: O(n) class Solution(object): def countRangeSum(self, nums, lower, upper): """ :type nums: List[int] :type lower: int :type upper: int :rtype: int """ def countAndMergeSort(sums, start, end, lower, upper): if end - start ...
2763e9893f474b4e73c1228a4a71783d7b248682
kamyu104/LeetCode-Solutions
/Python/closest-binary-search-tree-value.py
600
3.5625
4
# Time: O(h) # Space: O(1) class Solution(object): def closestValue(self, root, target): """ :type root: TreeNode :type target: float :rtype: int """ gap = float("inf") closest = float("inf") while root: if abs(root.val - target) < gap: ...
2c009566463ab7d80f6f987ade5ecb6b8ac7631f
kamyu104/LeetCode-Solutions
/Python/expressive-words.py
782
3.796875
4
# Time: O(n + s), n is the sum of all word lengths, s is the length of S # Space: O(l + s), l is the max word length import itertools class Solution(object): def expressiveWords(self, S, words): """ :type S: str :type words: List[str] :rtype: int """ # Run length ...
a1c7c538c8668f91928fe68d79c2c56766f9e868
kamyu104/LeetCode-Solutions
/Python/erect-the-fence-ii.py
2,025
4.03125
4
# Time: O(n) on average # Space: O(n) import random # reference: https://en.wikipedia.org/wiki/Smallest-circle_problem class Solution(object): def outerTrees(self, trees): """ :type trees: List[List[int]] :rtype: List[float] """ def dist(a, b): return ((a[0]-b...
c799bcaafc8263d15a2378b9e296830080309956
kamyu104/LeetCode-Solutions
/Python/non-decreasing-array.py
667
3.609375
4
# Time: O(n) # Space: O(1) class Solution(object): def checkPossibility(self, nums): """ :type nums: List[int] :rtype: bool """ modified, prev = False, nums[0] for i in xrange(1, len(nums)): if prev > nums[i]: if modified: ...
6fe2a3d8c3c4143db300b247321d914a7c033276
kamyu104/LeetCode-Solutions
/Python/check-if-move-is-legal.py
922
3.5625
4
# Time: O(8 * n) = O(1), grid is a n x n board and n = 8 # Space: O(1) class Solution(object): def checkMove(self, board, rMove, cMove, color): """ :type board: List[List[str]] :type rMove: int :type cMove: int :type color: str :rtype: bool """ def c...
f2bcf272558d65f7c0c73006ac8ecb4358d21089
kamyu104/LeetCode-Solutions
/Python/cousins-in-binary-tree.py
1,180
3.8125
4
# Time: O(n) # Space: O(h) # 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 isCousins(self, root, x, y): """ :type root: TreeNode :type x: int ...
66be67b280828e4bed8218fa21f891d0916a84a1
kamyu104/LeetCode-Solutions
/Python/minimum-time-to-visit-a-cell-in-a-grid.py
1,315
3.671875
4
# Time: O(m * n * log(m * n)) # Space: O(m * n) import heapq # dijkstra's algorithm class Solution(object): def minimumTime(self, grid): """ :type grid: List[List[int]] :rtype: int """ DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1)) def dijkstra(start, target): ...
fde42fe3960b83c42dff5e4f1dfd6da65df14463
kamyu104/LeetCode-Solutions
/Python/unique-number-of-occurrences.py
656
3.578125
4
# Time: O(n) # Space: O(n) import collections class Solution(object): def uniqueOccurrences(self, arr): """ :type arr: List[int] :rtype: bool """ count = collections.Counter(arr) lookup = set() for v in count.itervalues(): if v in lookup: ...
14fff64a851c1a5ae082dc3998579042b783a066
kamyu104/LeetCode-Solutions
/Python/two-sum-iii-data-structure-design.py
755
3.75
4
# Time: O(n) # Space: O(n) from collections import defaultdict class TwoSum(object): def __init__(self): """ initialize your data structure here """ self.lookup = defaultdict(int) def add(self, number): """ Add the number to an internal data structure. ...
2992c70023fcc17f419787f00129fcfaa0104b65
kamyu104/LeetCode-Solutions
/Python/friend-circles.py
953
3.546875
4
# Time: O(n^2) # Space: O(n) class Solution(object): def findCircleNum(self, M): """ :type M: List[List[int]] :rtype: int """ class UnionFind(object): def __init__(self, n): self.set = range(n) self.count = n def fin...
bdfc97b7e28b4819178760229343c1dd8fb11b84
kamyu104/LeetCode-Solutions
/Python/final-value-of-variable-after-performing-operations.py
253
3.5625
4
# Time: O(n) # Space: O(1) class Solution(object): def finalValueAfterOperations(self, operations): """ :type operations: List[str] :rtype: int """ return sum(1 if '+' == op[1] else -1 for op in operations)
c0dacc42565305947e1eb0fd7df5d78df8881b85
kamyu104/LeetCode-Solutions
/Python/egg-drop-with-2-eggs-and-n-floors.py
832
3.53125
4
# Time: O(1) # Space: O(1) import math # see the proof: https://www.geeksforgeeks.org/puzzle-set-35-2-eggs-and-100-floors/ class Solution(object): def twoEggDrop(self, n): """ :type n: int :rtype: int """ return int(math.ceil((-1+(1+8*n)**0.5)/2)) # Time: O(k * n^2...
c65ec9d201064cf4564965bd11e88f3daa1e47df
kamyu104/LeetCode-Solutions
/Python/number-of-employees-who-met-the-target.py
269
3.53125
4
# Time: O(n) # Space: O(1) # array class Solution(object): def numberOfEmployeesWhoMetTarget(self, hours, target): """ :type hours: List[int] :type target: int :rtype: int """ return sum(x >= target for x in hours)
576b1caa4e0a7ff0f3d3ab24276da397c2baad72
kamyu104/LeetCode-Solutions
/Python/distribute-candies.py
252
3.65625
4
# Time: O(n) # Space: O(n) class Solution(object): def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ lookup = set(candies) return min(len(lookup), len(candies)/2)
237facfcea0e413aa35caa28352d311eaeed8dba
kamyu104/LeetCode-Solutions
/Python/the-dining-philosophers.py
995
3.671875
4
# Time: O(n) # Space: O(1) import threading class DiningPhilosophers(object): def __init__(self): self._l = [threading.Lock() for _ in xrange(5)] # call the functions directly to execute, for example, eat() def wantsToEat(self, philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRigh...
27d9ef85920fb0fed81f9d25a68fa4df694e476c
kamyu104/LeetCode-Solutions
/Python/faulty-sensor.py
474
3.546875
4
# Time: O(n) # Space: O(1) class Solution(object): def badSensor(self, sensor1, sensor2): """ :type sensor1: List[int] :type sensor2: List[int] :rtype: int """ for i in xrange(len(sensor1)-1): if sensor1[i] == sensor2[i]: continue ...
a98e5b32b28cdb46d1c59b5608751e7e272938ec
kamyu104/LeetCode-Solutions
/Python/merge-bsts-to-create-single-bst.py
2,652
3.890625
4
# Time: O(n) # Space: O(n) # Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): pass class Solution(object): def canMerge(self, trees): """ :type trees: List[TreeNode] :rtype: TreeNode """ def find_leav...
5778684e493c6e2e6540079e6ba2c52c02a518c4
kamyu104/LeetCode-Solutions
/Python/balance-a-binary-search-tree.py
2,472
3.671875
4
# Time: O(n) # Space: O(h) # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None # dfs solution with stack class Solution(object): def balanceBST(self, root): """ :type root: TreeNode ...
7a48096cf6a8b677fc8b545ff1d4d3e14aa480a2
kamyu104/LeetCode-Solutions
/Python/adding-spaces-to-a-string.py
508
3.546875
4
# Time: O(n) # Space: O(1) # inplace solution class Solution(object): def addSpaces(self, s, spaces): """ :type s: str :type spaces: List[int] :rtype: str """ prev = len(s) s = list(s) s.extend([None]*len(spaces)) for i in reversed(xrange(len...
136a21ac44df57d0c1d49591d25a982a639f71f8
kamyu104/LeetCode-Solutions
/Python/max-stack.py
1,826
3.65625
4
# Time: push: O(1) # pop: O(n), there is no built-in SortedDict in python. If applied, it could be reduced to O(logn) # popMax: O(n) # top: O(1) # peekMax: O(1) # Space: O(n), n is the number of values in the current stack import collections class MaxStack(object): def _...
1615e74441d141f6576510e5b8385b10ca53581f
kamyu104/LeetCode-Solutions
/Python/solve-the-equation.py
566
3.765625
4
# Time: O(n) # Space: O(n) import re class Solution(object): def solveEquation(self, equation): """ :type equation: str :rtype: str """ a, b, side = 0, 0, 1 for eq, sign, num, isx in re.findall('(=)|([-+]?)(\d*)(x?)', equation): if eq: ...
9d599a8e40387a42340c58158b92ecf99747bc7d
kamyu104/LeetCode-Solutions
/Python/subtract-the-product-and-sum-of-digits-of-an-integer.py
579
3.5625
4
# Time: O(logn) # Space: O(1) class Solution(object): def subtractProductAndSum(self, n): """ :type n: int :rtype: int """ product, total = 1, 0 while n: n, r = divmod(n, 10) product *= r total += r return product-total ...
6b28b8bacd8bc5423352a0461cd7a0d05113a174
kamyu104/LeetCode-Solutions
/Python/three-divisors.py
330
3.640625
4
# Time: O(sqrt(n)) # Space: O(1) class Solution(object): def isThree(self, n): """ :type n: int :rtype: bool """ cnt = 0 i = 1 while i*i <= n and cnt <= 3: if n%i == 0: cnt += 1 if i*i == n else 2 i += 1 return...
a5b48124335e0982107ce37f2a5667f0dbe87ce6
kamyu104/LeetCode-Solutions
/Python/construct-binary-search-tree-from-preorder-traversal.py
916
3.859375
4
# Time: O(n) # Space: O(h) # 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 bstFromPreorder(self, preorder): """ :type preorder: List[int] :rtype: Tr...
08a27190e2210d7bedda769c93c6a9d710cb474e
BarDalal/Matrices--addition-and-multiplication
/AddMinPart.py
1,148
4.125
4
# -*- coding: utf-8 -*- """ Name: Bar Dalal Class: Ya4 The program adds the common parts of two matrices. The sum's size is as the common part's size. """ import numpy as np def MinAddition(a, b): """ The function gets two matrices. The function returns the sum of the common parts of the m...
5e77ee946bb1aea3260d6c3c1072aa546c0a5111
alexchou094/Python200804
/Day2-2.py
318
3.875
4
import random x = random.randint(1,20) while True: y = input("Guess a number : ") y = int(y) if y<1 or y>20: print("Not in range") else: if y>x: print("smaller") elif y<x: print("bigger") else: print("nice guess") break
5cdf8ed2fa1a67fa875daca598a6ef416e97042a
akashleo/django_start
/pythonrefresh.py
260
3.8125
4
class Dog: def __init__(self, name, age, furcolor): self.name = name self.age = age self.furcolor = furcolor def bark(self): print(" Bark !") mydog = Dog("Fido", 13, "Brown") mydog.bark() print(mydog.age)
2653be21d54d4e1bb97583730d8254ee13b471ac
BrydenFrancesca/frankie_adventure
/enemies.py
757
3.546875
4
#General enemy class class Enemy: def __init__(self): raise NotImplementedError ("Do not create raw enemy objects!") def __str__(self): return self.name #Is the enemy alive Function def is_alive(self): return self.hp > 0 #Enemies class Hoover(Enemy): def __init__(self): ...
afa5e2e385ff2086f25c471ac148c7032980d250
nighatm/W19A
/app.py
1,004
4.1875
4
import addition import subtraction import multiplication import divide print("Please choose an operation") print("1: Addition") print("2: Subtraction") print("3: Multiplication") print("4: Division") try: userChoice = int(input ("Enter Choice 1 or 2 or 3 or 4 : ")) except: print ('You have ent...
d2fa8db9bf50fac2ce99861c9f00565195c8e373
efgp26/ejercicios_python
/ciclos/solicitar_contraseña_while.py
765
4.03125
4
""" Escriba un programa que solicite una contraseña (el texto de la contraseña no es importante) y la vuelva a solicitar hasta que las dos contraseñas coincidan, con un límite de tres peticiones.""" primer_contraseña = input("digite su contraseña") segunda_contraseña = input("vuelva a introducir su contraseña") contad...
ad2df47d93658c2f4a041d42d17b6890e1473a9d
efgp26/ejercicios_python
/ejercicio_edad.py
117
3.796875
4
edad = int(input("escriba su edad: ")) if edad >= 18: print("es mayor de edad") else: print("es menor de edad")
fba786f4f81ed7e5850ba88162eef35d84f7b502
efgp26/ejercicios_python
/ejercicio_algoritmo_par_impar.py
133
3.9375
4
numero = int(input("por favor ingresar un numero: ")) modulo = numero %2 if modulo == 0: print("es par") else: print("es inpar")
32b868b8c4bd75d7c26ba86aadccbdd013798587
smarshy/py-scripts
/rhyming_word.py
858
3.828125
4
import sys import urllib2 import json #Example : python rhyming_word.py ajar #gets arguments from terminal def get_arguments(): if len(sys.argv) is 2: return sys.argv[1] else: print 'No argument given!' sys.exit() #gets url depending on arguments def get_url(): word = get_arguments() url = 'http://api.w...
7176e373f7b473162d007d6272102362b25c9c2c
ponjae/TriviaGame
/ui.py
2,299
3.53125
4
from tkinter import * from quiz_brain import QuizBrain THEME_COLOR = "#375362" class QuizInterface: def __init__(self, quiz_brain: QuizBrain): # Setting up the window self.quiz = quiz_brain self.window = Tk() self.window.title("My Own TP Game") self.window.config(padx=20,...
4d787cb6d923261f659fc4bed5bc060a4d691d83
vibhusharma101/data-structure-and-algorithms
/Data-Structures/tree/binary_tree.py
1,685
3.984375
4
class Node: def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right class Operation: def __init__(self): self.queue = [] self.list = [] def insert(self, root, data): if len(self.queue) == 0: roo...
e2225b38f457d41e9fbd875aec338a0f2d16aa10
thura747/file_download
/sqlite_db_connection.py
2,580
3.96875
4
""" -*- coding: utf-8 -*- @Time : 18/10/2021 19:00 PM @Author : Thu Ra @Email : thura747@gmail.com @File : sqlite.py @Software: PyCharm """ import sqlite3 from sqlite3 import Error class Database: def __init__(self): database = "test_db2.db" self.conn = None self.cur = "" ...
e602500c5834c6b453e7fa51f301a666fa5b10e4
melissarib/algoritmos-usp
/Processamento-de-imagens/5_filtros_espaciais.py
4,810
3.515625
4
import numpy as np import cv2 """ RESUMO TEORICO EM TÓPICOS SOBRE FILTROS ESPACIAIS - Diferença entre correlação e convolução espacial - O filtro espacial pode ser linear (ex: média) ou não-linear (ex: máximo) - Os filtros podem ser utilizados para suavização e aguçamento, por exemplo. - Os filtros...
f42709f744f78841ba115914bb6bdb5d2c1bb84d
DikranHachikyan/python-20201012
/ex38.py
306
3.90625
4
def get_squares(n): return [ v ** 2 for v in range(n + 1)] def generate_squares(n): for v in range(n + 1): yield v ** 2 if __name__ == '__main__': #1. for v in generate_squares(10): print(f'v = {v}') #2. lst = list(generate_squares(5)) print(f'lst = {lst}')
1d74f1cb3f86ac46517f6e63dbe7afc337f4e6a2
DikranHachikyan/python-20201012
/ex48.py
763
3.703125
4
if __name__ == '__main__': sq = lambda a: a**2 pw = lambda a: a ** 3 if a % 2 else a ** 2 # 1. # print(f'4^2={sq(4)}') # print(f'pw(3)={pw(3)}') # print(f'pw(6)={pw(6)}') items = [('A', 5, 7), ('D', 2, 6), ('B', 4, 6), ('D', 2, 5)] # 2. # items.sort() # print(f'in-place so...
496f29b34062cf8aadaefdc5498e0b49dbb36f50
DikranHachikyan/python-20201012
/ex39.py
311
3.6875
4
if __name__ == '__main__': squares = ( v for v in range(5,50,5)) print(f'1->{next(squares)}') print(f'2->{next(squares)}') print(f'3->{next(squares)}') print(f'4->{next(squares)}') lst1 = list(squares) print(f'lst1 = {lst1}') lst2 = list(squares) print(f'lst2 = {lst2}')
7fbaecd571e9f3d23f090044eb76418287332932
DikranHachikyan/python-20201012
/ex46.py
327
3.875
4
def sort_priority(values, group): def helper(item): if item in group: return (0, item) return (1,item) return values.sort(key = helper) if __name__ == '__main__': nums = [3, 2, 4, 7, 8, 9, 1, 5] group = {9, 8, 7} sort_priority(nums, group) print(f'nums:{...
51cc0c2b610846a0f4fcc8b0e4e2eb57d15d683a
DikranHachikyan/python-20201012
/ex58.py
1,068
4.25
4
# клас class Point(): #Променлива на класа (статична променлива) label = 'A' # Конструктор на класа - инициализация на данните на класа def __init__(self, x = 0, y = 0, *args, **kwargs): print('object constructor') # данни на класа self._x = x self._y = y # Метод на...
afc60f86a6e04b25047ea40348e9e1771f3e77cf
mrcruz117/algorithmPractice
/algoExpert/python/easy/twoNumSum.py
221
3.671875
4
def twoNumberSum(array, targetSum): for index1, num1 in enumerate(array): for index2, num2 in enumerate(array): if index1 == index2: continue if num1 + num2 == targetSum: return [num1, num2] return []