partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
lcs
The length of longest common subsequence among the two given strings s1 and s2
algorithms/strings/min_distance.py
def lcs(s1, s2, i, j): """ The length of longest common subsequence among the two given strings s1 and s2 """ if i == 0 or j == 0: return 0 elif s1[i - 1] == s2[j - 1]: return 1 + lcs(s1, s2, i - 1, j - 1) else: return max(lcs(s1, s2, i - 1, j), lcs(s1, s2, i, j - 1))
def lcs(s1, s2, i, j): """ The length of longest common subsequence among the two given strings s1 and s2 """ if i == 0 or j == 0: return 0 elif s1[i - 1] == s2[j - 1]: return 1 + lcs(s1, s2, i - 1, j - 1) else: return max(lcs(s1, s2, i - 1, j), lcs(s1, s2, i, j - 1))
[ "The", "length", "of", "longest", "common", "subsequence", "among", "the", "two", "given", "strings", "s1", "and", "s2" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/min_distance.py#L17-L26
[ "def", "lcs", "(", "s1", ",", "s2", ",", "i", ",", "j", ")", ":", "if", "i", "==", "0", "or", "j", "==", "0", ":", "return", "0", "elif", "s1", "[", "i", "-", "1", "]", "==", "s2", "[", "j", "-", "1", "]", ":", "return", "1", "+", "lc...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
lca
:type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode
algorithms/tree/lowest_common_ancestor.py
def lca(root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if root is None or root is p or root is q: return root left = lca(root.left, p, q) right = lca(root.right, p, q) if left is not None and right is not None: retur...
def lca(root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if root is None or root is p or root is q: return root left = lca(root.left, p, q) right = lca(root.right, p, q) if left is not None and right is not None: retur...
[ ":", "type", "root", ":", "TreeNode", ":", "type", "p", ":", "TreeNode", ":", "type", "q", ":", "TreeNode", ":", "rtype", ":", "TreeNode" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/lowest_common_ancestor.py#L24-L37
[ "def", "lca", "(", "root", ",", "p", ",", "q", ")", ":", "if", "root", "is", "None", "or", "root", "is", "p", "or", "root", "is", "q", ":", "return", "root", "left", "=", "lca", "(", "root", ".", "left", ",", "p", ",", "q", ")", "right", "=...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
lowest_common_ancestor
:type root: Node :type p: Node :type q: Node :rtype: Node
algorithms/tree/bst/lowest_common_ancestor.py
def lowest_common_ancestor(root, p, q): """ :type root: Node :type p: Node :type q: Node :rtype: Node """ while root: if p.val > root.val < q.val: root = root.right elif p.val < root.val > q.val: root = root.left else: return root
def lowest_common_ancestor(root, p, q): """ :type root: Node :type p: Node :type q: Node :rtype: Node """ while root: if p.val > root.val < q.val: root = root.right elif p.val < root.val > q.val: root = root.left else: return root
[ ":", "type", "root", ":", "Node", ":", "type", "p", ":", "Node", ":", "type", "q", ":", "Node", ":", "rtype", ":", "Node" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/bst/lowest_common_ancestor.py#L24-L37
[ "def", "lowest_common_ancestor", "(", "root", ",", "p", ",", "q", ")", ":", "while", "root", ":", "if", "p", ".", "val", ">", "root", ".", "val", "<", "q", ".", "val", ":", "root", "=", "root", ".", "right", "elif", "p", ".", "val", "<", "root"...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
climb_stairs
:type n: int :rtype: int
algorithms/dp/climbing_stairs.py
def climb_stairs(n): """ :type n: int :rtype: int """ arr = [1, 1] for _ in range(1, n): arr.append(arr[-1] + arr[-2]) return arr[-1]
def climb_stairs(n): """ :type n: int :rtype: int """ arr = [1, 1] for _ in range(1, n): arr.append(arr[-1] + arr[-2]) return arr[-1]
[ ":", "type", "n", ":", "int", ":", "rtype", ":", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/climbing_stairs.py#L14-L22
[ "def", "climb_stairs", "(", "n", ")", ":", "arr", "=", "[", "1", ",", "1", "]", "for", "_", "in", "range", "(", "1", ",", "n", ")", ":", "arr", ".", "append", "(", "arr", "[", "-", "1", "]", "+", "arr", "[", "-", "2", "]", ")", "return", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
find_nth_digit
find the nth digit of given number. 1. find the length of the number where the nth digit is from. 2. find the actual number where the nth digit is from 3. find the nth digit and return
algorithms/maths/nth_digit.py
def find_nth_digit(n): """find the nth digit of given number. 1. find the length of the number where the nth digit is from. 2. find the actual number where the nth digit is from 3. find the nth digit and return """ length = 1 count = 9 start = 1 while n > length * count: n -=...
def find_nth_digit(n): """find the nth digit of given number. 1. find the length of the number where the nth digit is from. 2. find the actual number where the nth digit is from 3. find the nth digit and return """ length = 1 count = 9 start = 1 while n > length * count: n -=...
[ "find", "the", "nth", "digit", "of", "given", "number", ".", "1", ".", "find", "the", "length", "of", "the", "number", "where", "the", "nth", "digit", "is", "from", ".", "2", ".", "find", "the", "actual", "number", "where", "the", "nth", "digit", "is...
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/nth_digit.py#L1-L17
[ "def", "find_nth_digit", "(", "n", ")", ":", "length", "=", "1", "count", "=", "9", "start", "=", "1", "while", "n", ">", "length", "*", "count", ":", "n", "-=", "length", "*", "count", "length", "+=", "1", "count", "*=", "10", "start", "*=", "10...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
hailstone
Return the 'hailstone sequence' from n to 1 n: The starting point of the hailstone sequence
algorithms/maths/hailstone.py
def hailstone(n): """Return the 'hailstone sequence' from n to 1 n: The starting point of the hailstone sequence """ sequence = [n] while n > 1: if n%2 != 0: n = 3*n + 1 else: n = int(n/2) sequence.append(n) return sequence
def hailstone(n): """Return the 'hailstone sequence' from n to 1 n: The starting point of the hailstone sequence """ sequence = [n] while n > 1: if n%2 != 0: n = 3*n + 1 else: n = int(n/2) sequence.append(n) return sequence
[ "Return", "the", "hailstone", "sequence", "from", "n", "to", "1", "n", ":", "The", "starting", "point", "of", "the", "hailstone", "sequence" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/hailstone.py#L1-L13
[ "def", "hailstone", "(", "n", ")", ":", "sequence", "=", "[", "n", "]", "while", "n", ">", "1", ":", "if", "n", "%", "2", "!=", "0", ":", "n", "=", "3", "*", "n", "+", "1", "else", ":", "n", "=", "int", "(", "n", "/", "2", ")", "sequenc...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
word_break
:type s: str :type word_dict: Set[str] :rtype: bool
algorithms/dp/word_break.py
def word_break(s, word_dict): """ :type s: str :type word_dict: Set[str] :rtype: bool """ dp = [False] * (len(s)+1) dp[0] = True for i in range(1, len(s)+1): for j in range(0, i): if dp[j] and s[j:i] in word_dict: dp[i] = True break ...
def word_break(s, word_dict): """ :type s: str :type word_dict: Set[str] :rtype: bool """ dp = [False] * (len(s)+1) dp[0] = True for i in range(1, len(s)+1): for j in range(0, i): if dp[j] and s[j:i] in word_dict: dp[i] = True break ...
[ ":", "type", "s", ":", "str", ":", "type", "word_dict", ":", "Set", "[", "str", "]", ":", "rtype", ":", "bool" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/word_break.py#L24-L37
[ "def", "word_break", "(", "s", ",", "word_dict", ")", ":", "dp", "=", "[", "False", "]", "*", "(", "len", "(", "s", ")", "+", "1", ")", "dp", "[", "0", "]", "=", "True", "for", "i", "in", "range", "(", "1", ",", "len", "(", "s", ")", "+",...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
prime_check
Return True if n is a prime number Else return False.
algorithms/maths/prime_check.py
def prime_check(n): """Return True if n is a prime number Else return False. """ if n <= 1: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False j = 5 while j * j <= n: if n % j == 0 or n % (j + 2) == 0: retu...
def prime_check(n): """Return True if n is a prime number Else return False. """ if n <= 1: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False j = 5 while j * j <= n: if n % j == 0 or n % (j + 2) == 0: retu...
[ "Return", "True", "if", "n", "is", "a", "prime", "number", "Else", "return", "False", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/prime_check.py#L1-L17
[ "def", "prime_check", "(", "n", ")", ":", "if", "n", "<=", "1", ":", "return", "False", "if", "n", "==", "2", "or", "n", "==", "3", ":", "return", "True", "if", "n", "%", "2", "==", "0", "or", "n", "%", "3", "==", "0", ":", "return", "False...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
longest_non_repeat_v1
Find the length of the longest substring without repeating characters.
algorithms/arrays/longest_non_repeat.py
def longest_non_repeat_v1(string): """ Find the length of the longest substring without repeating characters. """ if string is None: return 0 dict = {} max_length = 0 j = 0 for i in range(len(string)): if string[i] in dict: j = max(dict[string[i]], j) ...
def longest_non_repeat_v1(string): """ Find the length of the longest substring without repeating characters. """ if string is None: return 0 dict = {} max_length = 0 j = 0 for i in range(len(string)): if string[i] in dict: j = max(dict[string[i]], j) ...
[ "Find", "the", "length", "of", "the", "longest", "substring", "without", "repeating", "characters", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/longest_non_repeat.py#L14-L29
[ "def", "longest_non_repeat_v1", "(", "string", ")", ":", "if", "string", "is", "None", ":", "return", "0", "dict", "=", "{", "}", "max_length", "=", "0", "j", "=", "0", "for", "i", "in", "range", "(", "len", "(", "string", ")", ")", ":", "if", "s...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
longest_non_repeat_v2
Find the length of the longest substring without repeating characters. Uses alternative algorithm.
algorithms/arrays/longest_non_repeat.py
def longest_non_repeat_v2(string): """ Find the length of the longest substring without repeating characters. Uses alternative algorithm. """ if string is None: return 0 start, max_len = 0, 0 used_char = {} for index, char in enumerate(string): if char in used_char an...
def longest_non_repeat_v2(string): """ Find the length of the longest substring without repeating characters. Uses alternative algorithm. """ if string is None: return 0 start, max_len = 0, 0 used_char = {} for index, char in enumerate(string): if char in used_char an...
[ "Find", "the", "length", "of", "the", "longest", "substring", "without", "repeating", "characters", ".", "Uses", "alternative", "algorithm", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/longest_non_repeat.py#L31-L47
[ "def", "longest_non_repeat_v2", "(", "string", ")", ":", "if", "string", "is", "None", ":", "return", "0", "start", ",", "max_len", "=", "0", ",", "0", "used_char", "=", "{", "}", "for", "index", ",", "char", "in", "enumerate", "(", "string", ")", ":...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
get_longest_non_repeat_v1
Find the length of the longest substring without repeating characters. Return max_len and the substring as a tuple
algorithms/arrays/longest_non_repeat.py
def get_longest_non_repeat_v1(string): """ Find the length of the longest substring without repeating characters. Return max_len and the substring as a tuple """ if string is None: return 0, '' sub_string = '' dict = {} max_length = 0 j = 0 for i in range(len(string))...
def get_longest_non_repeat_v1(string): """ Find the length of the longest substring without repeating characters. Return max_len and the substring as a tuple """ if string is None: return 0, '' sub_string = '' dict = {} max_length = 0 j = 0 for i in range(len(string))...
[ "Find", "the", "length", "of", "the", "longest", "substring", "without", "repeating", "characters", ".", "Return", "max_len", "and", "the", "substring", "as", "a", "tuple" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/longest_non_repeat.py#L50-L69
[ "def", "get_longest_non_repeat_v1", "(", "string", ")", ":", "if", "string", "is", "None", ":", "return", "0", ",", "''", "sub_string", "=", "''", "dict", "=", "{", "}", "max_length", "=", "0", "j", "=", "0", "for", "i", "in", "range", "(", "len", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
get_longest_non_repeat_v2
Find the length of the longest substring without repeating characters. Uses alternative algorithm. Return max_len and the substring as a tuple
algorithms/arrays/longest_non_repeat.py
def get_longest_non_repeat_v2(string): """ Find the length of the longest substring without repeating characters. Uses alternative algorithm. Return max_len and the substring as a tuple """ if string is None: return 0, '' sub_string = '' start, max_len = 0, 0 used_char = ...
def get_longest_non_repeat_v2(string): """ Find the length of the longest substring without repeating characters. Uses alternative algorithm. Return max_len and the substring as a tuple """ if string is None: return 0, '' sub_string = '' start, max_len = 0, 0 used_char = ...
[ "Find", "the", "length", "of", "the", "longest", "substring", "without", "repeating", "characters", ".", "Uses", "alternative", "algorithm", ".", "Return", "max_len", "and", "the", "substring", "as", "a", "tuple" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/longest_non_repeat.py#L71-L91
[ "def", "get_longest_non_repeat_v2", "(", "string", ")", ":", "if", "string", "is", "None", ":", "return", "0", ",", "''", "sub_string", "=", "''", "start", ",", "max_len", "=", "0", ",", "0", "used_char", "=", "{", "}", "for", "index", ",", "char", "...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
PriorityQueue.push
Push the item in the priority queue. if priority is not given, priority is set to the value of item.
algorithms/queues/priority_queue.py
def push(self, item, priority=None): """Push the item in the priority queue. if priority is not given, priority is set to the value of item. """ priority = item if priority is None else priority node = PriorityQueueNode(item, priority) for index, current in enumerate(self...
def push(self, item, priority=None): """Push the item in the priority queue. if priority is not given, priority is set to the value of item. """ priority = item if priority is None else priority node = PriorityQueueNode(item, priority) for index, current in enumerate(self...
[ "Push", "the", "item", "in", "the", "priority", "queue", ".", "if", "priority", "is", "not", "given", "priority", "is", "set", "to", "the", "value", "of", "item", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/queues/priority_queue.py#L38-L49
[ "def", "push", "(", "self", ",", "item", ",", "priority", "=", "None", ")", ":", "priority", "=", "item", "if", "priority", "is", "None", "else", "priority", "node", "=", "PriorityQueueNode", "(", "item", ",", "priority", ")", "for", "index", ",", "cur...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
factorial
Calculates factorial iteratively. If mod is not None, then return (n! % mod) Time Complexity - O(n)
algorithms/maths/factorial.py
def factorial(n, mod=None): """Calculates factorial iteratively. If mod is not None, then return (n! % mod) Time Complexity - O(n)""" if not (isinstance(n, int) and n >= 0): raise ValueError("'n' must be a non-negative integer.") if mod is not None and not (isinstance(mod, int) and mod > 0):...
def factorial(n, mod=None): """Calculates factorial iteratively. If mod is not None, then return (n! % mod) Time Complexity - O(n)""" if not (isinstance(n, int) and n >= 0): raise ValueError("'n' must be a non-negative integer.") if mod is not None and not (isinstance(mod, int) and mod > 0):...
[ "Calculates", "factorial", "iteratively", ".", "If", "mod", "is", "not", "None", "then", "return", "(", "n!", "%", "mod", ")", "Time", "Complexity", "-", "O", "(", "n", ")" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/factorial.py#L1-L16
[ "def", "factorial", "(", "n", ",", "mod", "=", "None", ")", ":", "if", "not", "(", "isinstance", "(", "n", ",", "int", ")", "and", "n", ">=", "0", ")", ":", "raise", "ValueError", "(", "\"'n' must be a non-negative integer.\"", ")", "if", "mod", "is", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
factorial_recur
Calculates factorial recursively. If mod is not None, then return (n! % mod) Time Complexity - O(n)
algorithms/maths/factorial.py
def factorial_recur(n, mod=None): """Calculates factorial recursively. If mod is not None, then return (n! % mod) Time Complexity - O(n)""" if not (isinstance(n, int) and n >= 0): raise ValueError("'n' must be a non-negative integer.") if mod is not None and not (isinstance(mod, int) and mod...
def factorial_recur(n, mod=None): """Calculates factorial recursively. If mod is not None, then return (n! % mod) Time Complexity - O(n)""" if not (isinstance(n, int) and n >= 0): raise ValueError("'n' must be a non-negative integer.") if mod is not None and not (isinstance(mod, int) and mod...
[ "Calculates", "factorial", "recursively", ".", "If", "mod", "is", "not", "None", "then", "return", "(", "n!", "%", "mod", ")", "Time", "Complexity", "-", "O", "(", "n", ")" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/factorial.py#L19-L32
[ "def", "factorial_recur", "(", "n", ",", "mod", "=", "None", ")", ":", "if", "not", "(", "isinstance", "(", "n", ",", "int", ")", "and", "n", ">=", "0", ")", ":", "raise", "ValueError", "(", "\"'n' must be a non-negative integer.\"", ")", "if", "mod", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
selection_sort
Selection Sort Complexity: O(n^2)
algorithms/sort/selection_sort.py
def selection_sort(arr, simulation=False): """ Selection Sort Complexity: O(n^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr)): minimum = i for j in range(i + 1, len(arr)): # "Select" the ...
def selection_sort(arr, simulation=False): """ Selection Sort Complexity: O(n^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr)): minimum = i for j in range(i + 1, len(arr)): # "Select" the ...
[ "Selection", "Sort", "Complexity", ":", "O", "(", "n^2", ")" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/selection_sort.py#L1-L23
[ "def", "selection_sort", "(", "arr", ",", "simulation", "=", "False", ")", ":", "iteration", "=", "0", "if", "simulation", ":", "print", "(", "\"iteration\"", ",", "iteration", ",", "\":\"", ",", "*", "arr", ")", "for", "i", "in", "range", "(", "len", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
remove_dups
Time Complexity: O(N) Space Complexity: O(N)
algorithms/linkedlist/remove_duplicates.py
def remove_dups(head): """ Time Complexity: O(N) Space Complexity: O(N) """ hashset = set() prev = Node() while head: if head.val in hashset: prev.next = head.next else: hashset.add(head.val) prev = head head = head.next
def remove_dups(head): """ Time Complexity: O(N) Space Complexity: O(N) """ hashset = set() prev = Node() while head: if head.val in hashset: prev.next = head.next else: hashset.add(head.val) prev = head head = head.next
[ "Time", "Complexity", ":", "O", "(", "N", ")", "Space", "Complexity", ":", "O", "(", "N", ")" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/remove_duplicates.py#L6-L19
[ "def", "remove_dups", "(", "head", ")", ":", "hashset", "=", "set", "(", ")", "prev", "=", "Node", "(", ")", "while", "head", ":", "if", "head", ".", "val", "in", "hashset", ":", "prev", ".", "next", "=", "head", ".", "next", "else", ":", "hashse...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
remove_dups_wothout_set
Time Complexity: O(N^2) Space Complexity: O(1)
algorithms/linkedlist/remove_duplicates.py
def remove_dups_wothout_set(head): """ Time Complexity: O(N^2) Space Complexity: O(1) """ current = head while current: runner = current while runner.next: if runner.next.val == current.val: runner.next = runner.next.next else: ...
def remove_dups_wothout_set(head): """ Time Complexity: O(N^2) Space Complexity: O(1) """ current = head while current: runner = current while runner.next: if runner.next.val == current.val: runner.next = runner.next.next else: ...
[ "Time", "Complexity", ":", "O", "(", "N^2", ")", "Space", "Complexity", ":", "O", "(", "1", ")" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/remove_duplicates.py#L21-L34
[ "def", "remove_dups_wothout_set", "(", "head", ")", ":", "current", "=", "head", "while", "current", ":", "runner", "=", "current", "while", "runner", ".", "next", ":", "if", "runner", ".", "next", ".", "val", "==", "current", ".", "val", ":", "runner", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
RBTree.transplant
replace u with v :param node_u: replaced node :param node_v: :return: None
algorithms/tree/red_black_tree/red_black_tree.py
def transplant(self, node_u, node_v): """ replace u with v :param node_u: replaced node :param node_v: :return: None """ if node_u.parent is None: self.root = node_v elif node_u is node_u.parent.left: node_u.parent.left = node_v ...
def transplant(self, node_u, node_v): """ replace u with v :param node_u: replaced node :param node_v: :return: None """ if node_u.parent is None: self.root = node_v elif node_u is node_u.parent.left: node_u.parent.left = node_v ...
[ "replace", "u", "with", "v", ":", "param", "node_u", ":", "replaced", "node", ":", "param", "node_v", ":", ":", "return", ":", "None" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/red_black_tree/red_black_tree.py#L143-L158
[ "def", "transplant", "(", "self", ",", "node_u", ",", "node_v", ")", ":", "if", "node_u", ".", "parent", "is", "None", ":", "self", ".", "root", "=", "node_v", "elif", "node_u", "is", "node_u", ".", "parent", ".", "left", ":", "node_u", ".", "parent"...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
RBTree.maximum
find the max node when node regard as a root node :param node: :return: max node
algorithms/tree/red_black_tree/red_black_tree.py
def maximum(self, node): """ find the max node when node regard as a root node :param node: :return: max node """ temp_node = node while temp_node.right is not None: temp_node = temp_node.right return temp_node
def maximum(self, node): """ find the max node when node regard as a root node :param node: :return: max node """ temp_node = node while temp_node.right is not None: temp_node = temp_node.right return temp_node
[ "find", "the", "max", "node", "when", "node", "regard", "as", "a", "root", "node", ":", "param", "node", ":", ":", "return", ":", "max", "node" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/red_black_tree/red_black_tree.py#L160-L169
[ "def", "maximum", "(", "self", ",", "node", ")", ":", "temp_node", "=", "node", "while", "temp_node", ".", "right", "is", "not", "None", ":", "temp_node", "=", "temp_node", ".", "right", "return", "temp_node" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
RBTree.minimum
find the minimum node when node regard as a root node :param node: :return: minimum node
algorithms/tree/red_black_tree/red_black_tree.py
def minimum(self, node): """ find the minimum node when node regard as a root node :param node: :return: minimum node """ temp_node = node while temp_node.left: temp_node = temp_node.left return temp_node
def minimum(self, node): """ find the minimum node when node regard as a root node :param node: :return: minimum node """ temp_node = node while temp_node.left: temp_node = temp_node.left return temp_node
[ "find", "the", "minimum", "node", "when", "node", "regard", "as", "a", "root", "node", ":", "param", "node", ":", ":", "return", ":", "minimum", "node" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/red_black_tree/red_black_tree.py#L171-L180
[ "def", "minimum", "(", "self", ",", "node", ")", ":", "temp_node", "=", "node", "while", "temp_node", ".", "left", ":", "temp_node", "=", "temp_node", ".", "left", "return", "temp_node" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
modular_exponential
Computes (base ^ exponent) % mod. Time complexity - O(log n) Use similar to Python in-built function pow.
algorithms/maths/modular_exponential.py
def modular_exponential(base, exponent, mod): """Computes (base ^ exponent) % mod. Time complexity - O(log n) Use similar to Python in-built function pow.""" if exponent < 0: raise ValueError("Exponent must be positive.") base %= mod result = 1 while exponent > 0: # If the l...
def modular_exponential(base, exponent, mod): """Computes (base ^ exponent) % mod. Time complexity - O(log n) Use similar to Python in-built function pow.""" if exponent < 0: raise ValueError("Exponent must be positive.") base %= mod result = 1 while exponent > 0: # If the l...
[ "Computes", "(", "base", "^", "exponent", ")", "%", "mod", ".", "Time", "complexity", "-", "O", "(", "log", "n", ")", "Use", "similar", "to", "Python", "in", "-", "built", "function", "pow", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/modular_exponential.py#L1-L18
[ "def", "modular_exponential", "(", "base", ",", "exponent", ",", "mod", ")", ":", "if", "exponent", "<", "0", ":", "raise", "ValueError", "(", "\"Exponent must be positive.\"", ")", "base", "%=", "mod", "result", "=", "1", "while", "exponent", ">", "0", ":...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
can_attend_meetings
:type intervals: List[Interval] :rtype: bool
algorithms/sort/meeting_rooms.py
def can_attend_meetings(intervals): """ :type intervals: List[Interval] :rtype: bool """ intervals = sorted(intervals, key=lambda x: x.start) for i in range(1, len(intervals)): if intervals[i].start < intervals[i - 1].end: return False return True
def can_attend_meetings(intervals): """ :type intervals: List[Interval] :rtype: bool """ intervals = sorted(intervals, key=lambda x: x.start) for i in range(1, len(intervals)): if intervals[i].start < intervals[i - 1].end: return False return True
[ ":", "type", "intervals", ":", "List", "[", "Interval", "]", ":", "rtype", ":", "bool" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/meeting_rooms.py#L12-L21
[ "def", "can_attend_meetings", "(", "intervals", ")", ":", "intervals", "=", "sorted", "(", "intervals", ",", "key", "=", "lambda", "x", ":", "x", ".", "start", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "intervals", ")", ")", ":", "...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
Solution.delete_node
:type root: TreeNode :type key: int :rtype: TreeNode
algorithms/tree/bst/delete_node.py
def delete_node(self, root, key): """ :type root: TreeNode :type key: int :rtype: TreeNode """ if not root: return None if root.val == key: if root.left: # Find the right most leaf of the left sub-tree left_right_most =...
def delete_node(self, root, key): """ :type root: TreeNode :type key: int :rtype: TreeNode """ if not root: return None if root.val == key: if root.left: # Find the right most leaf of the left sub-tree left_right_most =...
[ ":", "type", "root", ":", "TreeNode", ":", "type", "key", ":", "int", ":", "rtype", ":", "TreeNode" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/bst/delete_node.py#L41-L66
[ "def", "delete_node", "(", "self", ",", "root", ",", "key", ")", ":", "if", "not", "root", ":", "return", "None", "if", "root", ".", "val", "==", "key", ":", "if", "root", ".", "left", ":", "# Find the right most leaf of the left sub-tree", "left_right_most"...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
simplify_path
:type path: str :rtype: str
algorithms/stack/simplify_path.py
def simplify_path(path): """ :type path: str :rtype: str """ skip = {'..', '.', ''} stack = [] paths = path.split('/') for tok in paths: if tok == '..': if stack: stack.pop() elif tok not in skip: stack.append(tok) return '/' + ...
def simplify_path(path): """ :type path: str :rtype: str """ skip = {'..', '.', ''} stack = [] paths = path.split('/') for tok in paths: if tok == '..': if stack: stack.pop() elif tok not in skip: stack.append(tok) return '/' + ...
[ ":", "type", "path", ":", "str", ":", "rtype", ":", "str" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/stack/simplify_path.py#L13-L27
[ "def", "simplify_path", "(", "path", ")", ":", "skip", "=", "{", "'..'", ",", "'.'", ",", "''", "}", "stack", "=", "[", "]", "paths", "=", "path", ".", "split", "(", "'/'", ")", "for", "tok", "in", "paths", ":", "if", "tok", "==", "'..'", ":", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
subsets
O(2**n)
algorithms/backtrack/subsets.py
def subsets(nums): """ O(2**n) """ def backtrack(res, nums, stack, pos): if pos == len(nums): res.append(list(stack)) else: # take nums[pos] stack.append(nums[pos]) backtrack(res, nums, stack, pos+1) stack.pop() # do...
def subsets(nums): """ O(2**n) """ def backtrack(res, nums, stack, pos): if pos == len(nums): res.append(list(stack)) else: # take nums[pos] stack.append(nums[pos]) backtrack(res, nums, stack, pos+1) stack.pop() # do...
[ "O", "(", "2", "**", "n", ")" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/backtrack/subsets.py#L22-L39
[ "def", "subsets", "(", "nums", ")", ":", "def", "backtrack", "(", "res", ",", "nums", ",", "stack", ",", "pos", ")", ":", "if", "pos", "==", "len", "(", "nums", ")", ":", "res", ".", "append", "(", "list", "(", "stack", ")", ")", "else", ":", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
jump_search
Jump Search Worst-case Complexity: O(√n) (root(n)) All items in list must be sorted like binary search Find block that contains target value and search it linearly in that block It returns a first target value in array reference: https://en.wikipedia.org/wiki/Jump_search
algorithms/search/jump_search.py
def jump_search(arr,target): """Jump Search Worst-case Complexity: O(√n) (root(n)) All items in list must be sorted like binary search Find block that contains target value and search it linearly in that block It returns a first target value in array reference: https://en.w...
def jump_search(arr,target): """Jump Search Worst-case Complexity: O(√n) (root(n)) All items in list must be sorted like binary search Find block that contains target value and search it linearly in that block It returns a first target value in array reference: https://en.w...
[ "Jump", "Search", "Worst", "-", "case", "Complexity", ":", "O", "(", "√n", ")", "(", "root", "(", "n", "))", "All", "items", "in", "list", "must", "be", "sorted", "like", "binary", "search" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/search/jump_search.py#L3-L40
[ "def", "jump_search", "(", "arr", ",", "target", ")", ":", "n", "=", "len", "(", "arr", ")", "block_size", "=", "int", "(", "math", ".", "sqrt", "(", "n", ")", ")", "block_prev", "=", "0", "block", "=", "block_size", "# return -1 means that array doesn't...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
flatten_iter
Takes as input multi dimensional iterable and returns generator which produces one dimensional output.
algorithms/arrays/flatten.py
def flatten_iter(iterable): """ Takes as input multi dimensional iterable and returns generator which produces one dimensional output. """ for element in iterable: if isinstance(element, Iterable): yield from flatten_iter(element) else: yield element
def flatten_iter(iterable): """ Takes as input multi dimensional iterable and returns generator which produces one dimensional output. """ for element in iterable: if isinstance(element, Iterable): yield from flatten_iter(element) else: yield element
[ "Takes", "as", "input", "multi", "dimensional", "iterable", "and", "returns", "generator", "which", "produces", "one", "dimensional", "output", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/flatten.py#L22-L31
[ "def", "flatten_iter", "(", "iterable", ")", ":", "for", "element", "in", "iterable", ":", "if", "isinstance", "(", "element", ",", "Iterable", ")", ":", "yield", "from", "flatten_iter", "(", "element", ")", "else", ":", "yield", "element" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
ladder_length
Bidirectional BFS!!! :type begin_word: str :type end_word: str :type word_list: Set[str] :rtype: int
algorithms/bfs/word_ladder.py
def ladder_length(begin_word, end_word, word_list): """ Bidirectional BFS!!! :type begin_word: str :type end_word: str :type word_list: Set[str] :rtype: int """ if len(begin_word) != len(end_word): return -1 # not possible if begin_word == end_word: return 0 #...
def ladder_length(begin_word, end_word, word_list): """ Bidirectional BFS!!! :type begin_word: str :type end_word: str :type word_list: Set[str] :rtype: int """ if len(begin_word) != len(end_word): return -1 # not possible if begin_word == end_word: return 0 #...
[ "Bidirectional", "BFS!!!", ":", "type", "begin_word", ":", "str", ":", "type", "end_word", ":", "str", ":", "type", "word_list", ":", "Set", "[", "str", "]", ":", "rtype", ":", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/bfs/word_ladder.py#L24-L64
[ "def", "ladder_length", "(", "begin_word", ",", "end_word", ",", "word_list", ")", ":", "if", "len", "(", "begin_word", ")", "!=", "len", "(", "end_word", ")", ":", "return", "-", "1", "# not possible", "if", "begin_word", "==", "end_word", ":", "return", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
convolved
Iterable to get every convolution window per loop iteration. For example: `convolved([1, 2, 3, 4], kernel_size=2)` will produce the following result: `[[1, 2], [2, 3], [3, 4]]`. `convolved([1, 2, 3], kernel_size=2, stride=1, padding=2, default_value=42)` will pro...
algorithms/iterables/convolved.py
def convolved(iterable, kernel_size=1, stride=1, padding=0, default_value=None): """Iterable to get every convolution window per loop iteration. For example: `convolved([1, 2, 3, 4], kernel_size=2)` will produce the following result: `[[1, 2], [2, 3], [3, 4]]`. `convolve...
def convolved(iterable, kernel_size=1, stride=1, padding=0, default_value=None): """Iterable to get every convolution window per loop iteration. For example: `convolved([1, 2, 3, 4], kernel_size=2)` will produce the following result: `[[1, 2], [2, 3], [3, 4]]`. `convolve...
[ "Iterable", "to", "get", "every", "convolution", "window", "per", "loop", "iteration", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/iterables/convolved.py#L28-L94
[ "def", "convolved", "(", "iterable", ",", "kernel_size", "=", "1", ",", "stride", "=", "1", ",", "padding", "=", "0", ",", "default_value", "=", "None", ")", ":", "# Input validation and error messages", "if", "not", "hasattr", "(", "iterable", ",", "'__iter...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
convolved_1d
1D Iterable to get every convolution window per loop iteration. For more information, refer to: - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py - https://github.com/guillaume-chevalier/python-conv-lib - MIT License, Copyright (c) 2018 Guillaume Chevalier
algorithms/iterables/convolved.py
def convolved_1d(iterable, kernel_size=1, stride=1, padding=0, default_value=None): """1D Iterable to get every convolution window per loop iteration. For more information, refer to: - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py - https://github.com/guillaume-chevali...
def convolved_1d(iterable, kernel_size=1, stride=1, padding=0, default_value=None): """1D Iterable to get every convolution window per loop iteration. For more information, refer to: - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py - https://github.com/guillaume-chevali...
[ "1D", "Iterable", "to", "get", "every", "convolution", "window", "per", "loop", "iteration", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/iterables/convolved.py#L96-L104
[ "def", "convolved_1d", "(", "iterable", ",", "kernel_size", "=", "1", ",", "stride", "=", "1", ",", "padding", "=", "0", ",", "default_value", "=", "None", ")", ":", "return", "convolved", "(", "iterable", ",", "kernel_size", ",", "stride", ",", "padding...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
convolved_2d
2D Iterable to get every convolution window per loop iteration. For more information, refer to: - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py - https://github.com/guillaume-chevalier/python-conv-lib - MIT License, Copyright (c) 2018 Guillaume Chevalier
algorithms/iterables/convolved.py
def convolved_2d(iterable, kernel_size=1, stride=1, padding=0, default_value=None): """2D Iterable to get every convolution window per loop iteration. For more information, refer to: - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py - https://github.com/guillaume-chevali...
def convolved_2d(iterable, kernel_size=1, stride=1, padding=0, default_value=None): """2D Iterable to get every convolution window per loop iteration. For more information, refer to: - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py - https://github.com/guillaume-chevali...
[ "2D", "Iterable", "to", "get", "every", "convolution", "window", "per", "loop", "iteration", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/iterables/convolved.py#L107-L128
[ "def", "convolved_2d", "(", "iterable", ",", "kernel_size", "=", "1", ",", "stride", "=", "1", ",", "padding", "=", "0", ",", "default_value", "=", "None", ")", ":", "kernel_size", "=", "dimensionize", "(", "kernel_size", ",", "nd", "=", "2", ")", "str...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
dimensionize
Convert integers to a list of integers to fit the number of dimensions if the argument is not already a list. For example: `dimensionize(3, nd=2)` will produce the following result: `(3, 3)`. `dimensionize([3, 1], nd=2)` will produce the following result: `[3, 1]`. ...
algorithms/iterables/convolved.py
def dimensionize(maybe_a_list, nd=2): """Convert integers to a list of integers to fit the number of dimensions if the argument is not already a list. For example: `dimensionize(3, nd=2)` will produce the following result: `(3, 3)`. `dimensionize([3, 1], nd=2)` will produce ...
def dimensionize(maybe_a_list, nd=2): """Convert integers to a list of integers to fit the number of dimensions if the argument is not already a list. For example: `dimensionize(3, nd=2)` will produce the following result: `(3, 3)`. `dimensionize([3, 1], nd=2)` will produce ...
[ "Convert", "integers", "to", "a", "list", "of", "integers", "to", "fit", "the", "number", "of", "dimensions", "if", "the", "argument", "is", "not", "already", "a", "list", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/iterables/convolved.py#L131-L154
[ "def", "dimensionize", "(", "maybe_a_list", ",", "nd", "=", "2", ")", ":", "if", "not", "hasattr", "(", "maybe_a_list", ",", "'__iter__'", ")", ":", "# Argument is probably an integer so we map it to a list of size `nd`.", "now_a_list", "=", "[", "maybe_a_list", "]", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
max_sliding_window
:type nums: List[int] :type k: int :rtype: List[int]
algorithms/heap/sliding_window_max.py
def max_sliding_window(nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ if not nums: return nums queue = collections.deque() res = [] for num in nums: if len(queue) < k: queue.append(num) else: res.append(max(queue...
def max_sliding_window(nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ if not nums: return nums queue = collections.deque() res = [] for num in nums: if len(queue) < k: queue.append(num) else: res.append(max(queue...
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "type", "k", ":", "int", ":", "rtype", ":", "List", "[", "int", "]" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/heap/sliding_window_max.py#L23-L41
[ "def", "max_sliding_window", "(", "nums", ",", "k", ")", ":", "if", "not", "nums", ":", "return", "nums", "queue", "=", "collections", ".", "deque", "(", ")", "res", "=", "[", "]", "for", "num", "in", "nums", ":", "if", "len", "(", "queue", ")", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
merge_intervals
Merge intervals in the form of a list.
algorithms/arrays/merge_intervals.py
def merge_intervals(intervals): """ Merge intervals in the form of a list. """ if intervals is None: return None intervals.sort(key=lambda i: i[0]) out = [intervals.pop(0)] for i in intervals: if out[-1][-1] >= i[0]: out[-1][-1] = max(out[-1][-1], i[-1]) else: ...
def merge_intervals(intervals): """ Merge intervals in the form of a list. """ if intervals is None: return None intervals.sort(key=lambda i: i[0]) out = [intervals.pop(0)] for i in intervals: if out[-1][-1] >= i[0]: out[-1][-1] = max(out[-1][-1], i[-1]) else: ...
[ "Merge", "intervals", "in", "the", "form", "of", "a", "list", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/merge_intervals.py#L66-L77
[ "def", "merge_intervals", "(", "intervals", ")", ":", "if", "intervals", "is", "None", ":", "return", "None", "intervals", ".", "sort", "(", "key", "=", "lambda", "i", ":", "i", "[", "0", "]", ")", "out", "=", "[", "intervals", ".", "pop", "(", "0"...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
Interval.merge
Merge two intervals into one.
algorithms/arrays/merge_intervals.py
def merge(intervals): """ Merge two intervals into one. """ out = [] for i in sorted(intervals, key=lambda i: i.start): if out and i.start <= out[-1].end: out[-1].end = max(out[-1].end, i.end) else: out += i, return out
def merge(intervals): """ Merge two intervals into one. """ out = [] for i in sorted(intervals, key=lambda i: i.start): if out and i.start <= out[-1].end: out[-1].end = max(out[-1].end, i.end) else: out += i, return out
[ "Merge", "two", "intervals", "into", "one", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/merge_intervals.py#L47-L55
[ "def", "merge", "(", "intervals", ")", ":", "out", "=", "[", "]", "for", "i", "in", "sorted", "(", "intervals", ",", "key", "=", "lambda", "i", ":", "i", ".", "start", ")", ":", "if", "out", "and", "i", ".", "start", "<=", "out", "[", "-", "1...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
Interval.print_intervals
Print out the intervals.
algorithms/arrays/merge_intervals.py
def print_intervals(intervals): """ Print out the intervals. """ res = [] for i in intervals: res.append(repr(i)) print("".join(res))
def print_intervals(intervals): """ Print out the intervals. """ res = [] for i in intervals: res.append(repr(i)) print("".join(res))
[ "Print", "out", "the", "intervals", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/merge_intervals.py#L58-L63
[ "def", "print_intervals", "(", "intervals", ")", ":", "res", "=", "[", "]", "for", "i", "in", "intervals", ":", "res", ".", "append", "(", "repr", "(", "i", ")", ")", "print", "(", "\"\"", ".", "join", "(", "res", ")", ")" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
rotate_v1
Rotate the entire array 'k' times T(n)- O(nk) :type array: List[int] :type k: int :rtype: void Do not return anything, modify array in-place instead.
algorithms/arrays/rotate.py
def rotate_v1(array, k): """ Rotate the entire array 'k' times T(n)- O(nk) :type array: List[int] :type k: int :rtype: void Do not return anything, modify array in-place instead. """ array = array[:] n = len(array) for i in range(k): # unused variable is not a problem ...
def rotate_v1(array, k): """ Rotate the entire array 'k' times T(n)- O(nk) :type array: List[int] :type k: int :rtype: void Do not return anything, modify array in-place instead. """ array = array[:] n = len(array) for i in range(k): # unused variable is not a problem ...
[ "Rotate", "the", "entire", "array", "k", "times", "T", "(", "n", ")", "-", "O", "(", "nk", ")" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/rotate.py#L13-L29
[ "def", "rotate_v1", "(", "array", ",", "k", ")", ":", "array", "=", "array", "[", ":", "]", "n", "=", "len", "(", "array", ")", "for", "i", "in", "range", "(", "k", ")", ":", "# unused variable is not a problem", "temp", "=", "array", "[", "n", "-"...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
rotate_v2
Reverse segments of the array, followed by the entire array T(n)- O(n) :type array: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
algorithms/arrays/rotate.py
def rotate_v2(array, k): """ Reverse segments of the array, followed by the entire array T(n)- O(n) :type array: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ array = array[:] def reverse(arr, a, b): while a < b: ar...
def rotate_v2(array, k): """ Reverse segments of the array, followed by the entire array T(n)- O(n) :type array: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ array = array[:] def reverse(arr, a, b): while a < b: ar...
[ "Reverse", "segments", "of", "the", "array", "followed", "by", "the", "entire", "array", "T", "(", "n", ")", "-", "O", "(", "n", ")", ":", "type", "array", ":", "List", "[", "int", "]", ":", "type", "k", ":", "int", ":", "rtype", ":", "void", "...
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/rotate.py#L32-L53
[ "def", "rotate_v2", "(", "array", ",", "k", ")", ":", "array", "=", "array", "[", ":", "]", "def", "reverse", "(", "arr", ",", "a", ",", "b", ")", ":", "while", "a", "<", "b", ":", "arr", "[", "a", "]", ",", "arr", "[", "b", "]", "=", "ar...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
pacific_atlantic
:type matrix: List[List[int]] :rtype: List[List[int]]
algorithms/dfs/pacific_atlantic.py
def pacific_atlantic(matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ n = len(matrix) if not n: return [] m = len(matrix[0]) if not m: return [] res = [] atlantic = [[False for _ in range (n)] for _ in range(m)] pacific = [[False for _ in range (n)] for...
def pacific_atlantic(matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ n = len(matrix) if not n: return [] m = len(matrix[0]) if not m: return [] res = [] atlantic = [[False for _ in range (n)] for _ in range(m)] pacific = [[False for _ in range (n)] for...
[ ":", "type", "matrix", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "List", "[", "List", "[", "int", "]]" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dfs/pacific_atlantic.py#L32-L54
[ "def", "pacific_atlantic", "(", "matrix", ")", ":", "n", "=", "len", "(", "matrix", ")", "if", "not", "n", ":", "return", "[", "]", "m", "=", "len", "(", "matrix", "[", "0", "]", ")", "if", "not", "m", ":", "return", "[", "]", "res", "=", "["...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
quick_sort
Quick sort Complexity: best O(n log(n)) avg O(n log(n)), worst O(N^2)
algorithms/sort/quick_sort.py
def quick_sort(arr, simulation=False): """ Quick sort Complexity: best O(n log(n)) avg O(n log(n)), worst O(N^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) arr, _ = quick_sort_recur(arr, 0, len(arr) - 1, iteration, simulation) return arr
def quick_sort(arr, simulation=False): """ Quick sort Complexity: best O(n log(n)) avg O(n log(n)), worst O(N^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) arr, _ = quick_sort_recur(arr, 0, len(arr) - 1, iteration, simulation) return arr
[ "Quick", "sort", "Complexity", ":", "best", "O", "(", "n", "log", "(", "n", "))", "avg", "O", "(", "n", "log", "(", "n", "))", "worst", "O", "(", "N^2", ")" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/quick_sort.py#L1-L10
[ "def", "quick_sort", "(", "arr", ",", "simulation", "=", "False", ")", ":", "iteration", "=", "0", "if", "simulation", ":", "print", "(", "\"iteration\"", ",", "iteration", ",", "\":\"", ",", "*", "arr", ")", "arr", ",", "_", "=", "quick_sort_recur", "...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
is_palindrome
:type s: str :rtype: bool
algorithms/strings/is_palindrome.py
def is_palindrome(s): """ :type s: str :rtype: bool """ i = 0 j = len(s)-1 while i < j: while i < j and not s[i].isalnum(): i += 1 while i < j and not s[j].isalnum(): j -= 1 if s[i].lower() != s[j].lower(): return False i, j...
def is_palindrome(s): """ :type s: str :rtype: bool """ i = 0 j = len(s)-1 while i < j: while i < j and not s[i].isalnum(): i += 1 while i < j and not s[j].isalnum(): j -= 1 if s[i].lower() != s[j].lower(): return False i, j...
[ ":", "type", "s", ":", "str", ":", "rtype", ":", "bool" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/is_palindrome.py#L16-L31
[ "def", "is_palindrome", "(", "s", ")", ":", "i", "=", "0", "j", "=", "len", "(", "s", ")", "-", "1", "while", "i", "<", "j", ":", "while", "i", "<", "j", "and", "not", "s", "[", "i", "]", ".", "isalnum", "(", ")", ":", "i", "+=", "1", "...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
plus_one_v1
:type digits: List[int] :rtype: List[int]
algorithms/arrays/plus_one.py
def plus_one_v1(digits): """ :type digits: List[int] :rtype: List[int] """ digits[-1] = digits[-1] + 1 res = [] ten = 0 i = len(digits)-1 while i >= 0 or ten == 1: summ = 0 if i >= 0: summ += digits[i] if ten: summ += 1 res.appe...
def plus_one_v1(digits): """ :type digits: List[int] :rtype: List[int] """ digits[-1] = digits[-1] + 1 res = [] ten = 0 i = len(digits)-1 while i >= 0 or ten == 1: summ = 0 if i >= 0: summ += digits[i] if ten: summ += 1 res.appe...
[ ":", "type", "digits", ":", "List", "[", "int", "]", ":", "rtype", ":", "List", "[", "int", "]" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/plus_one.py#L10-L28
[ "def", "plus_one_v1", "(", "digits", ")", ":", "digits", "[", "-", "1", "]", "=", "digits", "[", "-", "1", "]", "+", "1", "res", "=", "[", "]", "ten", "=", "0", "i", "=", "len", "(", "digits", ")", "-", "1", "while", "i", ">=", "0", "or", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
rotate_right
:type head: ListNode :type k: int :rtype: ListNode
algorithms/linkedlist/rotate_list.py
def rotate_right(head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head or not head.next: return head current = head length = 1 # count length of the list while current.next: current = current.next length += 1 # make it circul...
def rotate_right(head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head or not head.next: return head current = head length = 1 # count length of the list while current.next: current = current.next length += 1 # make it circul...
[ ":", "type", "head", ":", "ListNode", ":", "type", "k", ":", "int", ":", "rtype", ":", "ListNode" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/rotate_list.py#L17-L39
[ "def", "rotate_right", "(", "head", ",", "k", ")", ":", "if", "not", "head", "or", "not", "head", ".", "next", ":", "return", "head", "current", "=", "head", "length", "=", "1", "# count length of the list", "while", "current", ".", "next", ":", "current...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
num_decodings
:type s: str :rtype: int
algorithms/dp/num_decodings.py
def num_decodings(s): """ :type s: str :rtype: int """ if not s or s[0] == "0": return 0 wo_last, wo_last_two = 1, 1 for i in range(1, len(s)): x = wo_last if s[i] != "0" else 0 y = wo_last_two if int(s[i-1:i+1]) < 27 and s[i-1] != "0" else 0 wo_last_two = wo_...
def num_decodings(s): """ :type s: str :rtype: int """ if not s or s[0] == "0": return 0 wo_last, wo_last_two = 1, 1 for i in range(1, len(s)): x = wo_last if s[i] != "0" else 0 y = wo_last_two if int(s[i-1:i+1]) < 27 and s[i-1] != "0" else 0 wo_last_two = wo_...
[ ":", "type", "s", ":", "str", ":", "rtype", ":", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/num_decodings.py#L20-L33
[ "def", "num_decodings", "(", "s", ")", ":", "if", "not", "s", "or", "s", "[", "0", "]", "==", "\"0\"", ":", "return", "0", "wo_last", ",", "wo_last_two", "=", "1", ",", "1", "for", "i", "in", "range", "(", "1", ",", "len", "(", "s", ")", ")",...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
search_range
:type nums: List[int] :type target: int :rtype: List[int]
algorithms/search/search_range.py
def search_range(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ low = 0 high = len(nums) - 1 while low <= high: mid = low + (high - low) // 2 if target < nums[mid]: high = mid - 1 elif target > nums[mid]: l...
def search_range(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ low = 0 high = len(nums) - 1 while low <= high: mid = low + (high - low) // 2 if target < nums[mid]: high = mid - 1 elif target > nums[mid]: l...
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "type", "target", ":", "int", ":", "rtype", ":", "List", "[", "int", "]" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/search/search_range.py#L12-L33
[ "def", "search_range", "(", "nums", ",", "target", ")", ":", "low", "=", "0", "high", "=", "len", "(", "nums", ")", "-", "1", "while", "low", "<=", "high", ":", "mid", "=", "low", "+", "(", "high", "-", "low", ")", "//", "2", "if", "target", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
first_cyclic_node
:type head: Node :rtype: Node
algorithms/linkedlist/first_cyclic_node.py
def first_cyclic_node(head): """ :type head: Node :rtype: Node """ runner = walker = head while runner and runner.next: runner = runner.next.next walker = walker.next if runner is walker: break if runner is None or runner.next is None: return None...
def first_cyclic_node(head): """ :type head: Node :rtype: Node """ runner = walker = head while runner and runner.next: runner = runner.next.next walker = walker.next if runner is walker: break if runner is None or runner.next is None: return None...
[ ":", "type", "head", ":", "Node", ":", "rtype", ":", "Node" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/first_cyclic_node.py#L19-L37
[ "def", "first_cyclic_node", "(", "head", ")", ":", "runner", "=", "walker", "=", "head", "while", "runner", "and", "runner", ".", "next", ":", "runner", "=", "runner", ".", "next", ".", "next", "walker", "=", "walker", ".", "next", "if", "runner", "is"...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
max_heap_sort
Heap Sort that uses a max heap to sort an array in ascending order Complexity: O(n log(n))
algorithms/sort/heap_sort.py
def max_heap_sort(arr, simulation=False): """ Heap Sort that uses a max heap to sort an array in ascending order Complexity: O(n log(n)) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr) - 1, 0, -1): iteration = max_heapif...
def max_heap_sort(arr, simulation=False): """ Heap Sort that uses a max heap to sort an array in ascending order Complexity: O(n log(n)) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr) - 1, 0, -1): iteration = max_heapif...
[ "Heap", "Sort", "that", "uses", "a", "max", "heap", "to", "sort", "an", "array", "in", "ascending", "order", "Complexity", ":", "O", "(", "n", "log", "(", "n", "))" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/heap_sort.py#L1-L15
[ "def", "max_heap_sort", "(", "arr", ",", "simulation", "=", "False", ")", ":", "iteration", "=", "0", "if", "simulation", ":", "print", "(", "\"iteration\"", ",", "iteration", ",", "\":\"", ",", "*", "arr", ")", "for", "i", "in", "range", "(", "len", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
max_heapify
Max heapify helper for max_heap_sort
algorithms/sort/heap_sort.py
def max_heapify(arr, end, simulation, iteration): """ Max heapify helper for max_heap_sort """ last_parent = (end - 1) // 2 # Iterate from last parent to first for parent in range(last_parent, -1, -1): current_parent = parent # Iterate from current_parent to last_parent whi...
def max_heapify(arr, end, simulation, iteration): """ Max heapify helper for max_heap_sort """ last_parent = (end - 1) // 2 # Iterate from last parent to first for parent in range(last_parent, -1, -1): current_parent = parent # Iterate from current_parent to last_parent whi...
[ "Max", "heapify", "helper", "for", "max_heap_sort" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/heap_sort.py#L18-L45
[ "def", "max_heapify", "(", "arr", ",", "end", ",", "simulation", ",", "iteration", ")", ":", "last_parent", "=", "(", "end", "-", "1", ")", "//", "2", "# Iterate from last parent to first", "for", "parent", "in", "range", "(", "last_parent", ",", "-", "1",...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
min_heap_sort
Heap Sort that uses a min heap to sort an array in ascending order Complexity: O(n log(n))
algorithms/sort/heap_sort.py
def min_heap_sort(arr, simulation=False): """ Heap Sort that uses a min heap to sort an array in ascending order Complexity: O(n log(n)) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(0, len(arr) - 1): iteration = min_heapify(ar...
def min_heap_sort(arr, simulation=False): """ Heap Sort that uses a min heap to sort an array in ascending order Complexity: O(n log(n)) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(0, len(arr) - 1): iteration = min_heapify(ar...
[ "Heap", "Sort", "that", "uses", "a", "min", "heap", "to", "sort", "an", "array", "in", "ascending", "order", "Complexity", ":", "O", "(", "n", "log", "(", "n", "))" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/heap_sort.py#L47-L58
[ "def", "min_heap_sort", "(", "arr", ",", "simulation", "=", "False", ")", ":", "iteration", "=", "0", "if", "simulation", ":", "print", "(", "\"iteration\"", ",", "iteration", ",", "\":\"", ",", "*", "arr", ")", "for", "i", "in", "range", "(", "0", "...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
min_heapify
Min heapify helper for min_heap_sort
algorithms/sort/heap_sort.py
def min_heapify(arr, start, simulation, iteration): """ Min heapify helper for min_heap_sort """ # Offset last_parent by the start (last_parent calculated as if start index was 0) # All array accesses need to be offset by start end = len(arr) - 1 last_parent = (end - start - 1) // 2 # Itera...
def min_heapify(arr, start, simulation, iteration): """ Min heapify helper for min_heap_sort """ # Offset last_parent by the start (last_parent calculated as if start index was 0) # All array accesses need to be offset by start end = len(arr) - 1 last_parent = (end - start - 1) // 2 # Itera...
[ "Min", "heapify", "helper", "for", "min_heap_sort" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/heap_sort.py#L61-L92
[ "def", "min_heapify", "(", "arr", ",", "start", ",", "simulation", ",", "iteration", ")", ":", "# Offset last_parent by the start (last_parent calculated as if start index was 0)", "# All array accesses need to be offset by start", "end", "=", "len", "(", "arr", ")", "-", "...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
generate_key
the RSA key generating algorithm k is the number of bits in n
algorithms/maths/rsa.py
def generate_key(k, seed=None): """ the RSA key generating algorithm k is the number of bits in n """ def modinv(a, m): """calculate the inverse of a mod m that is, find b such that (a * b) % m == 1""" b = 1 while not (a * b) % m == 1: b += 1 retu...
def generate_key(k, seed=None): """ the RSA key generating algorithm k is the number of bits in n """ def modinv(a, m): """calculate the inverse of a mod m that is, find b such that (a * b) % m == 1""" b = 1 while not (a * b) % m == 1: b += 1 retu...
[ "the", "RSA", "key", "generating", "algorithm", "k", "is", "the", "number", "of", "bits", "in", "n" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/rsa.py#L27-L78
[ "def", "generate_key", "(", "k", ",", "seed", "=", "None", ")", ":", "def", "modinv", "(", "a", ",", "m", ")", ":", "\"\"\"calculate the inverse of a mod m\n that is, find b such that (a * b) % m == 1\"\"\"", "b", "=", "1", "while", "not", "(", "a", "*", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
square_root
Return square root of n, with maximum absolute error epsilon
algorithms/maths/sqrt_precision_factor.py
def square_root(n, epsilon=0.001): """Return square root of n, with maximum absolute error epsilon""" guess = n / 2 while abs(guess * guess - n) > epsilon: guess = (guess + (n / guess)) / 2 return guess
def square_root(n, epsilon=0.001): """Return square root of n, with maximum absolute error epsilon""" guess = n / 2 while abs(guess * guess - n) > epsilon: guess = (guess + (n / guess)) / 2 return guess
[ "Return", "square", "root", "of", "n", "with", "maximum", "absolute", "error", "epsilon" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/sqrt_precision_factor.py#L12-L19
[ "def", "square_root", "(", "n", ",", "epsilon", "=", "0.001", ")", ":", "guess", "=", "n", "/", "2", "while", "abs", "(", "guess", "*", "guess", "-", "n", ")", ">", "epsilon", ":", "guess", "=", "(", "guess", "+", "(", "n", "/", "guess", ")", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
counting_sort
Counting_sort Sorting a array which has no element greater than k Creating a new temp_arr,where temp_arr[i] contain the number of element less than or equal to i in the arr Then placing the number i into a correct position in the result_arr return the result_arr Complexity: 0(n)
algorithms/sort/counting_sort.py
def counting_sort(arr): """ Counting_sort Sorting a array which has no element greater than k Creating a new temp_arr,where temp_arr[i] contain the number of element less than or equal to i in the arr Then placing the number i into a correct position in the result_arr return the result_arr ...
def counting_sort(arr): """ Counting_sort Sorting a array which has no element greater than k Creating a new temp_arr,where temp_arr[i] contain the number of element less than or equal to i in the arr Then placing the number i into a correct position in the result_arr return the result_arr ...
[ "Counting_sort", "Sorting", "a", "array", "which", "has", "no", "element", "greater", "than", "k", "Creating", "a", "new", "temp_arr", "where", "temp_arr", "[", "i", "]", "contain", "the", "number", "of", "element", "less", "than", "or", "equal", "to", "i"...
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/counting_sort.py#L1-L36
[ "def", "counting_sort", "(", "arr", ")", ":", "m", "=", "min", "(", "arr", ")", "# in case there are negative elements, change the array to all positive element", "different", "=", "0", "if", "m", "<", "0", ":", "# save the change, so that we can convert the array back to a...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
powerset
Calculate the powerset of any iterable. For a range of integers up to the length of the given list, make all possible combinations and chain them together as one object. From https://docs.python.org/3/library/itertools.html#itertools-recipes
algorithms/set/set_covering.py
def powerset(iterable): """Calculate the powerset of any iterable. For a range of integers up to the length of the given list, make all possible combinations and chain them together as one object. From https://docs.python.org/3/library/itertools.html#itertools-recipes """ "list(powerset([1,2,3]...
def powerset(iterable): """Calculate the powerset of any iterable. For a range of integers up to the length of the given list, make all possible combinations and chain them together as one object. From https://docs.python.org/3/library/itertools.html#itertools-recipes """ "list(powerset([1,2,3]...
[ "Calculate", "the", "powerset", "of", "any", "iterable", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/set/set_covering.py#L25-L34
[ "def", "powerset", "(", "iterable", ")", ":", "\"list(powerset([1,2,3])) --> [(), (1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3)]\"", "s", "=", "list", "(", "iterable", ")", "return", "chain", ".", "from_iterable", "(", "combinations", "(", "s", ",", "r", ")", "for", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
optimal_set_cover
Optimal algorithm - DONT USE ON BIG INPUTS - O(2^n) complexity! Finds the minimum cost subcollection os S that covers all elements of U Args: universe (list): Universe of elements subsets (dict): Subsets of U {S1:elements,S2:elements} costs (dict): Costs of each subset in S - {S1:cost, ...
algorithms/set/set_covering.py
def optimal_set_cover(universe, subsets, costs): """ Optimal algorithm - DONT USE ON BIG INPUTS - O(2^n) complexity! Finds the minimum cost subcollection os S that covers all elements of U Args: universe (list): Universe of elements subsets (dict): Subsets of U {S1:elements,S2:elements} ...
def optimal_set_cover(universe, subsets, costs): """ Optimal algorithm - DONT USE ON BIG INPUTS - O(2^n) complexity! Finds the minimum cost subcollection os S that covers all elements of U Args: universe (list): Universe of elements subsets (dict): Subsets of U {S1:elements,S2:elements} ...
[ "Optimal", "algorithm", "-", "DONT", "USE", "ON", "BIG", "INPUTS", "-", "O", "(", "2^n", ")", "complexity!", "Finds", "the", "minimum", "cost", "subcollection", "os", "S", "that", "covers", "all", "elements", "of", "U" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/set/set_covering.py#L37-L58
[ "def", "optimal_set_cover", "(", "universe", ",", "subsets", ",", "costs", ")", ":", "pset", "=", "powerset", "(", "subsets", ".", "keys", "(", ")", ")", "best_set", "=", "None", "best_cost", "=", "float", "(", "\"inf\"", ")", "for", "subset", "in", "p...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
greedy_set_cover
Approximate greedy algorithm for set-covering. Can be used on large inputs - though not an optimal solution. Args: universe (list): Universe of elements subsets (dict): Subsets of U {S1:elements,S2:elements} costs (dict): Costs of each subset in S - {S1:cost, S2:cost...}
algorithms/set/set_covering.py
def greedy_set_cover(universe, subsets, costs): """Approximate greedy algorithm for set-covering. Can be used on large inputs - though not an optimal solution. Args: universe (list): Universe of elements subsets (dict): Subsets of U {S1:elements,S2:elements} costs (dict): Costs of e...
def greedy_set_cover(universe, subsets, costs): """Approximate greedy algorithm for set-covering. Can be used on large inputs - though not an optimal solution. Args: universe (list): Universe of elements subsets (dict): Subsets of U {S1:elements,S2:elements} costs (dict): Costs of e...
[ "Approximate", "greedy", "algorithm", "for", "set", "-", "covering", ".", "Can", "be", "used", "on", "large", "inputs", "-", "though", "not", "an", "optimal", "solution", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/set/set_covering.py#L61-L95
[ "def", "greedy_set_cover", "(", "universe", ",", "subsets", ",", "costs", ")", ":", "elements", "=", "set", "(", "e", "for", "s", "in", "subsets", ".", "keys", "(", ")", "for", "e", "in", "subsets", "[", "s", "]", ")", "# elements don't cover universe ->...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
num_trees
:type n: int :rtype: int
algorithms/tree/bst/unique_bst.py
def num_trees(n): """ :type n: int :rtype: int """ dp = [0] * (n+1) dp[0] = 1 dp[1] = 1 for i in range(2, n+1): for j in range(i+1): dp[i] += dp[i-j] * dp[j-1] return dp[-1]
def num_trees(n): """ :type n: int :rtype: int """ dp = [0] * (n+1) dp[0] = 1 dp[1] = 1 for i in range(2, n+1): for j in range(i+1): dp[i] += dp[i-j] * dp[j-1] return dp[-1]
[ ":", "type", "n", ":", "int", ":", "rtype", ":", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/bst/unique_bst.py#L29-L40
[ "def", "num_trees", "(", "n", ")", ":", "dp", "=", "[", "0", "]", "*", "(", "n", "+", "1", ")", "dp", "[", "0", "]", "=", "1", "dp", "[", "1", "]", "=", "1", "for", "i", "in", "range", "(", "2", ",", "n", "+", "1", ")", ":", "for", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
MovingAverage.next
:type val: int :rtype: float
algorithms/queues/moving_average.py
def next(self, val): """ :type val: int :rtype: float """ self.queue.append(val) return sum(self.queue) / len(self.queue)
def next(self, val): """ :type val: int :rtype: float """ self.queue.append(val) return sum(self.queue) / len(self.queue)
[ ":", "type", "val", ":", "int", ":", "rtype", ":", "float" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/queues/moving_average.py#L13-L19
[ "def", "next", "(", "self", ",", "val", ")", ":", "self", ".", "queue", ".", "append", "(", "val", ")", "return", "sum", "(", "self", ".", "queue", ")", "/", "len", "(", "self", ".", "queue", ")" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
n_sum
n: int nums: list[object] target: object sum_closure: function, optional Given two elements of nums, return sum of both. compare_closure: function, optional Given one object of nums and target, return -1, 1, or 0. same_closure: function, optional Given two object of nums, ret...
algorithms/arrays/n_sum.py
def n_sum(n, nums, target, **kv): """ n: int nums: list[object] target: object sum_closure: function, optional Given two elements of nums, return sum of both. compare_closure: function, optional Given one object of nums and target, return -1, 1, or 0. same_closure: function, ...
def n_sum(n, nums, target, **kv): """ n: int nums: list[object] target: object sum_closure: function, optional Given two elements of nums, return sum of both. compare_closure: function, optional Given one object of nums and target, return -1, 1, or 0. same_closure: function, ...
[ "n", ":", "int", "nums", ":", "list", "[", "object", "]", "target", ":", "object", "sum_closure", ":", "function", "optional", "Given", "two", "elements", "of", "nums", "return", "sum", "of", "both", ".", "compare_closure", ":", "function", "optional", "Gi...
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/n_sum.py#L34-L140
[ "def", "n_sum", "(", "n", ",", "nums", ",", "target", ",", "*", "*", "kv", ")", ":", "def", "sum_closure_default", "(", "a", ",", "b", ")", ":", "return", "a", "+", "b", "def", "compare_closure_default", "(", "num", ",", "target", ")", ":", "\"\"\"...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
pattern_match
:type pattern: str :type string: str :rtype: bool
algorithms/backtrack/pattern_match.py
def pattern_match(pattern, string): """ :type pattern: str :type string: str :rtype: bool """ def backtrack(pattern, string, dic): if len(pattern) == 0 and len(string) > 0: return False if len(pattern) == len(string) == 0: return True for end in...
def pattern_match(pattern, string): """ :type pattern: str :type string: str :rtype: bool """ def backtrack(pattern, string, dic): if len(pattern) == 0 and len(string) > 0: return False if len(pattern) == len(string) == 0: return True for end in...
[ ":", "type", "pattern", ":", "str", ":", "type", "string", ":", "str", ":", "rtype", ":", "bool" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/backtrack/pattern_match.py#L17-L42
[ "def", "pattern_match", "(", "pattern", ",", "string", ")", ":", "def", "backtrack", "(", "pattern", ",", "string", ",", "dic", ")", ":", "if", "len", "(", "pattern", ")", "==", "0", "and", "len", "(", "string", ")", ">", "0", ":", "return", "False...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
bogo_sort
Bogo Sort Best Case Complexity: O(n) Worst Case Complexity: O(∞) Average Case Complexity: O(n(n-1)!)
algorithms/sort/bogo_sort.py
def bogo_sort(arr, simulation=False): """Bogo Sort Best Case Complexity: O(n) Worst Case Complexity: O(∞) Average Case Complexity: O(n(n-1)!) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) def is_sorted(arr): #check the array ...
def bogo_sort(arr, simulation=False): """Bogo Sort Best Case Complexity: O(n) Worst Case Complexity: O(∞) Average Case Complexity: O(n(n-1)!) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) def is_sorted(arr): #check the array ...
[ "Bogo", "Sort", "Best", "Case", "Complexity", ":", "O", "(", "n", ")", "Worst", "Case", "Complexity", ":", "O", "(", "∞", ")", "Average", "Case", "Complexity", ":", "O", "(", "n", "(", "n", "-", "1", ")", "!", ")" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/bogo_sort.py#L3-L32
[ "def", "bogo_sort", "(", "arr", ",", "simulation", "=", "False", ")", ":", "iteration", "=", "0", "if", "simulation", ":", "print", "(", "\"iteration\"", ",", "iteration", ",", "\":\"", ",", "*", "arr", ")", "def", "is_sorted", "(", "arr", ")", ":", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
AvlTree.insert
Insert new key into node
algorithms/tree/avl/avl.py
def insert(self, key): """ Insert new key into node """ # Create new node n = TreeNode(key) if not self.node: self.node = n self.node.left = AvlTree() self.node.right = AvlTree() elif key < self.node.val: self.node.l...
def insert(self, key): """ Insert new key into node """ # Create new node n = TreeNode(key) if not self.node: self.node = n self.node.left = AvlTree() self.node.right = AvlTree() elif key < self.node.val: self.node.l...
[ "Insert", "new", "key", "into", "node" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/avl/avl.py#L15-L29
[ "def", "insert", "(", "self", ",", "key", ")", ":", "# Create new node", "n", "=", "TreeNode", "(", "key", ")", "if", "not", "self", ".", "node", ":", "self", ".", "node", "=", "n", "self", ".", "node", ".", "left", "=", "AvlTree", "(", ")", "sel...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
AvlTree.re_balance
Re balance tree. After inserting or deleting a node,
algorithms/tree/avl/avl.py
def re_balance(self): """ Re balance tree. After inserting or deleting a node, """ self.update_heights(recursive=False) self.update_balances(False) while self.balance < -1 or self.balance > 1: if self.balance > 1: if self.node.left.balance < 0...
def re_balance(self): """ Re balance tree. After inserting or deleting a node, """ self.update_heights(recursive=False) self.update_balances(False) while self.balance < -1 or self.balance > 1: if self.balance > 1: if self.node.left.balance < 0...
[ "Re", "balance", "tree", ".", "After", "inserting", "or", "deleting", "a", "node" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/avl/avl.py#L31-L55
[ "def", "re_balance", "(", "self", ")", ":", "self", ".", "update_heights", "(", "recursive", "=", "False", ")", "self", ".", "update_balances", "(", "False", ")", "while", "self", ".", "balance", "<", "-", "1", "or", "self", ".", "balance", ">", "1", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
AvlTree.update_heights
Update tree height
algorithms/tree/avl/avl.py
def update_heights(self, recursive=True): """ Update tree height """ if self.node: if recursive: if self.node.left: self.node.left.update_heights() if self.node.right: self.node.right.update_heights() ...
def update_heights(self, recursive=True): """ Update tree height """ if self.node: if recursive: if self.node.left: self.node.left.update_heights() if self.node.right: self.node.right.update_heights() ...
[ "Update", "tree", "height" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/avl/avl.py#L57-L70
[ "def", "update_heights", "(", "self", ",", "recursive", "=", "True", ")", ":", "if", "self", ".", "node", ":", "if", "recursive", ":", "if", "self", ".", "node", ".", "left", ":", "self", ".", "node", ".", "left", ".", "update_heights", "(", ")", "...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
AvlTree.update_balances
Calculate tree balance factor
algorithms/tree/avl/avl.py
def update_balances(self, recursive=True): """ Calculate tree balance factor """ if self.node: if recursive: if self.node.left: self.node.left.update_balances() if self.node.right: self.node.right.update...
def update_balances(self, recursive=True): """ Calculate tree balance factor """ if self.node: if recursive: if self.node.left: self.node.left.update_balances() if self.node.right: self.node.right.update...
[ "Calculate", "tree", "balance", "factor" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/avl/avl.py#L72-L86
[ "def", "update_balances", "(", "self", ",", "recursive", "=", "True", ")", ":", "if", "self", ".", "node", ":", "if", "recursive", ":", "if", "self", ".", "node", ".", "left", ":", "self", ".", "node", ".", "left", ".", "update_balances", "(", ")", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
AvlTree.rotate_right
Right rotation
algorithms/tree/avl/avl.py
def rotate_right(self): """ Right rotation """ new_root = self.node.left.node new_left_sub = new_root.right.node old_root = self.node self.node = new_root old_root.left.node = new_left_sub new_root.right.node = old_root
def rotate_right(self): """ Right rotation """ new_root = self.node.left.node new_left_sub = new_root.right.node old_root = self.node self.node = new_root old_root.left.node = new_left_sub new_root.right.node = old_root
[ "Right", "rotation" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/avl/avl.py#L88-L98
[ "def", "rotate_right", "(", "self", ")", ":", "new_root", "=", "self", ".", "node", ".", "left", ".", "node", "new_left_sub", "=", "new_root", ".", "right", ".", "node", "old_root", "=", "self", ".", "node", "self", ".", "node", "=", "new_root", "old_r...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
AvlTree.rotate_left
Left rotation
algorithms/tree/avl/avl.py
def rotate_left(self): """ Left rotation """ new_root = self.node.right.node new_left_sub = new_root.left.node old_root = self.node self.node = new_root old_root.right.node = new_left_sub new_root.left.node = old_root
def rotate_left(self): """ Left rotation """ new_root = self.node.right.node new_left_sub = new_root.left.node old_root = self.node self.node = new_root old_root.right.node = new_left_sub new_root.left.node = old_root
[ "Left", "rotation" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/avl/avl.py#L100-L110
[ "def", "rotate_left", "(", "self", ")", ":", "new_root", "=", "self", ".", "node", ".", "right", ".", "node", "new_left_sub", "=", "new_root", ".", "left", ".", "node", "old_root", "=", "self", ".", "node", "self", ".", "node", "=", "new_root", "old_ro...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
AvlTree.in_order_traverse
In-order traversal of the tree
algorithms/tree/avl/avl.py
def in_order_traverse(self): """ In-order traversal of the tree """ result = [] if not self.node: return result result.extend(self.node.left.in_order_traverse()) result.append(self.node.key) result.extend(self.node.right.in_order_traverse()) ...
def in_order_traverse(self): """ In-order traversal of the tree """ result = [] if not self.node: return result result.extend(self.node.left.in_order_traverse()) result.append(self.node.key) result.extend(self.node.right.in_order_traverse()) ...
[ "In", "-", "order", "traversal", "of", "the", "tree" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/avl/avl.py#L112-L124
[ "def", "in_order_traverse", "(", "self", ")", ":", "result", "=", "[", "]", "if", "not", "self", ".", "node", ":", "return", "result", "result", ".", "extend", "(", "self", ".", "node", ".", "left", ".", "in_order_traverse", "(", ")", ")", "result", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
strobogrammatic_in_range
:type low: str :type high: str :rtype: int
algorithms/maths/generate_strobogrammtic.py
def strobogrammatic_in_range(low, high): """ :type low: str :type high: str :rtype: int """ res = [] count = 0 low_len = len(low) high_len = len(high) for i in range(low_len, high_len + 1): res.extend(helper2(i, i)) for perm in res: if len(perm) == low_len and...
def strobogrammatic_in_range(low, high): """ :type low: str :type high: str :rtype: int """ res = [] count = 0 low_len = len(low) high_len = len(high) for i in range(low_len, high_len + 1): res.extend(helper2(i, i)) for perm in res: if len(perm) == low_len and...
[ ":", "type", "low", ":", "str", ":", "type", "high", ":", "str", ":", "rtype", ":", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/generate_strobogrammtic.py#L37-L56
[ "def", "strobogrammatic_in_range", "(", "low", ",", "high", ")", ":", "res", "=", "[", "]", "count", "=", "0", "low_len", "=", "len", "(", "low", ")", "high_len", "=", "len", "(", "high", ")", "for", "i", "in", "range", "(", "low_len", ",", "high_l...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
find_keyboard_row
:type words: List[str] :rtype: List[str]
algorithms/set/find_keyboard_row.py
def find_keyboard_row(words): """ :type words: List[str] :rtype: List[str] """ keyboard = [ set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm'), ] result = [] for word in words: for key in keyboard: if set(word.lower()).issubset(key): ...
def find_keyboard_row(words): """ :type words: List[str] :rtype: List[str] """ keyboard = [ set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm'), ] result = [] for word in words: for key in keyboard: if set(word.lower()).issubset(key): ...
[ ":", "type", "words", ":", "List", "[", "str", "]", ":", "rtype", ":", "List", "[", "str", "]" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/set/find_keyboard_row.py#L11-L26
[ "def", "find_keyboard_row", "(", "words", ")", ":", "keyboard", "=", "[", "set", "(", "'qwertyuiop'", ")", ",", "set", "(", "'asdfghjkl'", ")", ",", "set", "(", "'zxcvbnm'", ")", ",", "]", "result", "=", "[", "]", "for", "word", "in", "words", ":", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
kth_to_last_eval
This is a suboptimal, hacky method using eval(), which is not safe for user input. We guard against danger by ensuring k in an int
algorithms/linkedlist/kth_to_last.py
def kth_to_last_eval(head, k): """ This is a suboptimal, hacky method using eval(), which is not safe for user input. We guard against danger by ensuring k in an int """ if not isinstance(k, int) or not head.val: return False nexts = '.'.join(['next' for n in range(1, k+1)]) seeker...
def kth_to_last_eval(head, k): """ This is a suboptimal, hacky method using eval(), which is not safe for user input. We guard against danger by ensuring k in an int """ if not isinstance(k, int) or not head.val: return False nexts = '.'.join(['next' for n in range(1, k+1)]) seeker...
[ "This", "is", "a", "suboptimal", "hacky", "method", "using", "eval", "()", "which", "is", "not", "safe", "for", "user", "input", ".", "We", "guard", "against", "danger", "by", "ensuring", "k", "in", "an", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/kth_to_last.py#L7-L24
[ "def", "kth_to_last_eval", "(", "head", ",", "k", ")", ":", "if", "not", "isinstance", "(", "k", ",", "int", ")", "or", "not", "head", ".", "val", ":", "return", "False", "nexts", "=", "'.'", ".", "join", "(", "[", "'next'", "for", "n", "in", "ra...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
kth_to_last_dict
This is a brute force method where we keep a dict the size of the list Then we check it for the value we need. If the key is not in the dict, our and statement will short circuit and return False
algorithms/linkedlist/kth_to_last.py
def kth_to_last_dict(head, k): """ This is a brute force method where we keep a dict the size of the list Then we check it for the value we need. If the key is not in the dict, our and statement will short circuit and return False """ if not (head and k > -1): return False d = dict()...
def kth_to_last_dict(head, k): """ This is a brute force method where we keep a dict the size of the list Then we check it for the value we need. If the key is not in the dict, our and statement will short circuit and return False """ if not (head and k > -1): return False d = dict()...
[ "This", "is", "a", "brute", "force", "method", "where", "we", "keep", "a", "dict", "the", "size", "of", "the", "list", "Then", "we", "check", "it", "for", "the", "value", "we", "need", ".", "If", "the", "key", "is", "not", "in", "the", "dict", "our...
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/kth_to_last.py#L27-L41
[ "def", "kth_to_last_dict", "(", "head", ",", "k", ")", ":", "if", "not", "(", "head", "and", "k", ">", "-", "1", ")", ":", "return", "False", "d", "=", "dict", "(", ")", "count", "=", "0", "while", "head", ":", "d", "[", "count", "]", "=", "h...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
kth_to_last
This is an optimal method using iteration. We move p1 k steps ahead into the list. Then we move p1 and p2 together until p1 hits the end.
algorithms/linkedlist/kth_to_last.py
def kth_to_last(head, k): """ This is an optimal method using iteration. We move p1 k steps ahead into the list. Then we move p1 and p2 together until p1 hits the end. """ if not (head or k > -1): return False p1 = head p2 = head for i in range(1, k+1): if p1 is None:...
def kth_to_last(head, k): """ This is an optimal method using iteration. We move p1 k steps ahead into the list. Then we move p1 and p2 together until p1 hits the end. """ if not (head or k > -1): return False p1 = head p2 = head for i in range(1, k+1): if p1 is None:...
[ "This", "is", "an", "optimal", "method", "using", "iteration", ".", "We", "move", "p1", "k", "steps", "ahead", "into", "the", "list", ".", "Then", "we", "move", "p1", "and", "p2", "together", "until", "p1", "hits", "the", "end", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/kth_to_last.py#L44-L62
[ "def", "kth_to_last", "(", "head", ",", "k", ")", ":", "if", "not", "(", "head", "or", "k", ">", "-", "1", ")", ":", "return", "False", "p1", "=", "head", "p2", "=", "head", "for", "i", "in", "range", "(", "1", ",", "k", "+", "1", ")", ":",...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
get_skyline
Wortst Time Complexity: O(NlogN) :type buildings: List[List[int]] :rtype: List[List[int]]
algorithms/heap/skyline.py
def get_skyline(lrh): """ Wortst Time Complexity: O(NlogN) :type buildings: List[List[int]] :rtype: List[List[int]] """ skyline, live = [], [] i, n = 0, len(lrh) while i < n or live: if not live or i < n and lrh[i][0] <= -live[0][1]: x = lrh[i][0] while i ...
def get_skyline(lrh): """ Wortst Time Complexity: O(NlogN) :type buildings: List[List[int]] :rtype: List[List[int]] """ skyline, live = [], [] i, n = 0, len(lrh) while i < n or live: if not live or i < n and lrh[i][0] <= -live[0][1]: x = lrh[i][0] while i ...
[ "Wortst", "Time", "Complexity", ":", "O", "(", "NlogN", ")", ":", "type", "buildings", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "List", "[", "List", "[", "int", "]]" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/heap/skyline.py#L39-L60
[ "def", "get_skyline", "(", "lrh", ")", ":", "skyline", ",", "live", "=", "[", "]", ",", "[", "]", "i", ",", "n", "=", "0", ",", "len", "(", "lrh", ")", "while", "i", "<", "n", "or", "live", ":", "if", "not", "live", "or", "i", "<", "n", "...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
summarize_ranges
:type array: List[int] :rtype: List[]
algorithms/arrays/summarize_ranges.py
def summarize_ranges(array): """ :type array: List[int] :rtype: List[] """ res = [] if len(array) == 1: return [str(array[0])] i = 0 while i < len(array): num = array[i] while i + 1 < len(array) and array[i + 1] - array[i] == 1: i += 1 if array...
def summarize_ranges(array): """ :type array: List[int] :rtype: List[] """ res = [] if len(array) == 1: return [str(array[0])] i = 0 while i < len(array): num = array[i] while i + 1 < len(array) and array[i + 1] - array[i] == 1: i += 1 if array...
[ ":", "type", "array", ":", "List", "[", "int", "]", ":", "rtype", ":", "List", "[]" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/summarize_ranges.py#L9-L27
[ "def", "summarize_ranges", "(", "array", ")", ":", "res", "=", "[", "]", "if", "len", "(", "array", ")", "==", "1", ":", "return", "[", "str", "(", "array", "[", "0", "]", ")", "]", "i", "=", "0", "while", "i", "<", "len", "(", "array", ")", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
encode
Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
algorithms/strings/encode_decode.py
def encode(strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ res = '' for string in strs.split(): res += str(len(string)) + ":" + string return res
def encode(strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ res = '' for string in strs.split(): res += str(len(string)) + ":" + string return res
[ "Encodes", "a", "list", "of", "strings", "to", "a", "single", "string", ".", ":", "type", "strs", ":", "List", "[", "str", "]", ":", "rtype", ":", "str" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/encode_decode.py#L8-L16
[ "def", "encode", "(", "strs", ")", ":", "res", "=", "''", "for", "string", "in", "strs", ".", "split", "(", ")", ":", "res", "+=", "str", "(", "len", "(", "string", ")", ")", "+", "\":\"", "+", "string", "return", "res" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
decode
Decodes a single string to a list of strings. :type s: str :rtype: List[str]
algorithms/strings/encode_decode.py
def decode(s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ strs = [] i = 0 while i < len(s): index = s.find(":", i) size = int(s[i:index]) strs.append(s[index+1: index+1+size]) i = index+1+size return strs
def decode(s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ strs = [] i = 0 while i < len(s): index = s.find(":", i) size = int(s[i:index]) strs.append(s[index+1: index+1+size]) i = index+1+size return strs
[ "Decodes", "a", "single", "string", "to", "a", "list", "of", "strings", ".", ":", "type", "s", ":", "str", ":", "rtype", ":", "List", "[", "str", "]" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/encode_decode.py#L18-L30
[ "def", "decode", "(", "s", ")", ":", "strs", "=", "[", "]", "i", "=", "0", "while", "i", "<", "len", "(", "s", ")", ":", "index", "=", "s", ".", "find", "(", "\":\"", ",", "i", ")", "size", "=", "int", "(", "s", "[", "i", ":", "index", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
multiply
:type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
algorithms/matrix/multiply.py
def multiply(multiplicand: list, multiplier: list) -> list: """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ multiplicand_row, multiplicand_col = len( multiplicand), len(multiplicand[0]) multiplier_row, multiplier_col = len(multiplier), len(multiplier...
def multiply(multiplicand: list, multiplier: list) -> list: """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ multiplicand_row, multiplicand_col = len( multiplicand), len(multiplicand[0]) multiplier_row, multiplier_col = len(multiplier), len(multiplier...
[ ":", "type", "A", ":", "List", "[", "List", "[", "int", "]]", ":", "type", "B", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "List", "[", "List", "[", "int", "]]" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/matrix/multiply.py#L10-L28
[ "def", "multiply", "(", "multiplicand", ":", "list", ",", "multiplier", ":", "list", ")", "->", "list", ":", "multiplicand_row", ",", "multiplicand_col", "=", "len", "(", "multiplicand", ")", ",", "len", "(", "multiplicand", "[", "0", "]", ")", "multiplier...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
combination
This function calculates nCr.
algorithms/maths/combination.py
def combination(n, r): """This function calculates nCr.""" if n == r or r == 0: return 1 else: return combination(n-1, r-1) + combination(n-1, r)
def combination(n, r): """This function calculates nCr.""" if n == r or r == 0: return 1 else: return combination(n-1, r-1) + combination(n-1, r)
[ "This", "function", "calculates", "nCr", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/combination.py#L1-L6
[ "def", "combination", "(", "n", ",", "r", ")", ":", "if", "n", "==", "r", "or", "r", "==", "0", ":", "return", "1", "else", ":", "return", "combination", "(", "n", "-", "1", ",", "r", "-", "1", ")", "+", "combination", "(", "n", "-", "1", "...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
combination_memo
This function calculates nCr using memoization method.
algorithms/maths/combination.py
def combination_memo(n, r): """This function calculates nCr using memoization method.""" memo = {} def recur(n, r): if n == r or r == 0: return 1 if (n, r) not in memo: memo[(n, r)] = recur(n - 1, r - 1) + recur(n - 1, r) return memo[(n, r)] return recur(n...
def combination_memo(n, r): """This function calculates nCr using memoization method.""" memo = {} def recur(n, r): if n == r or r == 0: return 1 if (n, r) not in memo: memo[(n, r)] = recur(n - 1, r - 1) + recur(n - 1, r) return memo[(n, r)] return recur(n...
[ "This", "function", "calculates", "nCr", "using", "memoization", "method", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/combination.py#L8-L17
[ "def", "combination_memo", "(", "n", ",", "r", ")", ":", "memo", "=", "{", "}", "def", "recur", "(", "n", ",", "r", ")", ":", "if", "n", "==", "r", "or", "r", "==", "0", ":", "return", "1", "if", "(", "n", ",", "r", ")", "not", "in", "mem...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
is_anagram
:type s: str :type t: str :rtype: bool
algorithms/map/is_anagram.py
def is_anagram(s, t): """ :type s: str :type t: str :rtype: bool """ maps = {} mapt = {} for i in s: maps[i] = maps.get(i, 0) + 1 for i in t: mapt[i] = mapt.get(i, 0) + 1 return maps == mapt
def is_anagram(s, t): """ :type s: str :type t: str :rtype: bool """ maps = {} mapt = {} for i in s: maps[i] = maps.get(i, 0) + 1 for i in t: mapt[i] = mapt.get(i, 0) + 1 return maps == mapt
[ ":", "type", "s", ":", "str", ":", "type", "t", ":", "str", ":", "rtype", ":", "bool" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/map/is_anagram.py#L17-L29
[ "def", "is_anagram", "(", "s", ",", "t", ")", ":", "maps", "=", "{", "}", "mapt", "=", "{", "}", "for", "i", "in", "s", ":", "maps", "[", "i", "]", "=", "maps", ".", "get", "(", "i", ",", "0", ")", "+", "1", "for", "i", "in", "t", ":", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
pancake_sort
Pancake_sort Sorting a given array mutation of selection sort reference: https://www.geeksforgeeks.org/pancake-sorting/ Overall time complexity : O(N^2)
algorithms/sort/pancake_sort.py
def pancake_sort(arr): """ Pancake_sort Sorting a given array mutation of selection sort reference: https://www.geeksforgeeks.org/pancake-sorting/ Overall time complexity : O(N^2) """ len_arr = len(arr) if len_arr <= 1: return arr for cur in range(len(arr), 1, -1):...
def pancake_sort(arr): """ Pancake_sort Sorting a given array mutation of selection sort reference: https://www.geeksforgeeks.org/pancake-sorting/ Overall time complexity : O(N^2) """ len_arr = len(arr) if len_arr <= 1: return arr for cur in range(len(arr), 1, -1):...
[ "Pancake_sort", "Sorting", "a", "given", "array", "mutation", "of", "selection", "sort" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/pancake_sort.py#L1-L25
[ "def", "pancake_sort", "(", "arr", ")", ":", "len_arr", "=", "len", "(", "arr", ")", "if", "len_arr", "<=", "1", ":", "return", "arr", "for", "cur", "in", "range", "(", "len", "(", "arr", ")", ",", "1", ",", "-", "1", ")", ":", "#Finding index of...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
ZigZagIterator.next
:rtype: int
algorithms/queues/zigzagiterator.py
def next(self): """ :rtype: int """ v=self.queue.pop(0) ret=v.pop(0) if v: self.queue.append(v) return ret
def next(self): """ :rtype: int """ v=self.queue.pop(0) ret=v.pop(0) if v: self.queue.append(v) return ret
[ ":", "rtype", ":", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/queues/zigzagiterator.py#L11-L18
[ "def", "next", "(", "self", ")", ":", "v", "=", "self", ".", "queue", ".", "pop", "(", "0", ")", "ret", "=", "v", ".", "pop", "(", "0", ")", "if", "v", ":", "self", ".", "queue", ".", "append", "(", "v", ")", "return", "ret" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
max_profit_naive
:type prices: List[int] :rtype: int
algorithms/dp/buy_sell_stock.py
def max_profit_naive(prices): """ :type prices: List[int] :rtype: int """ max_so_far = 0 for i in range(0, len(prices) - 1): for j in range(i + 1, len(prices)): max_so_far = max(max_so_far, prices[j] - prices[i]) return max_so_far
def max_profit_naive(prices): """ :type prices: List[int] :rtype: int """ max_so_far = 0 for i in range(0, len(prices) - 1): for j in range(i + 1, len(prices)): max_so_far = max(max_so_far, prices[j] - prices[i]) return max_so_far
[ ":", "type", "prices", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/buy_sell_stock.py#L24-L33
[ "def", "max_profit_naive", "(", "prices", ")", ":", "max_so_far", "=", "0", "for", "i", "in", "range", "(", "0", ",", "len", "(", "prices", ")", "-", "1", ")", ":", "for", "j", "in", "range", "(", "i", "+", "1", ",", "len", "(", "prices", ")", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
max_profit_optimized
input: [7, 1, 5, 3, 6, 4] diff : [X, -6, 4, -2, 3, -2] :type prices: List[int] :rtype: int
algorithms/dp/buy_sell_stock.py
def max_profit_optimized(prices): """ input: [7, 1, 5, 3, 6, 4] diff : [X, -6, 4, -2, 3, -2] :type prices: List[int] :rtype: int """ cur_max, max_so_far = 0, 0 for i in range(1, len(prices)): cur_max = max(0, cur_max + prices[i] - prices[i-1]) max_so_far = max(max_so_far,...
def max_profit_optimized(prices): """ input: [7, 1, 5, 3, 6, 4] diff : [X, -6, 4, -2, 3, -2] :type prices: List[int] :rtype: int """ cur_max, max_so_far = 0, 0 for i in range(1, len(prices)): cur_max = max(0, cur_max + prices[i] - prices[i-1]) max_so_far = max(max_so_far,...
[ "input", ":", "[", "7", "1", "5", "3", "6", "4", "]", "diff", ":", "[", "X", "-", "6", "4", "-", "2", "3", "-", "2", "]", ":", "type", "prices", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/buy_sell_stock.py#L37-L48
[ "def", "max_profit_optimized", "(", "prices", ")", ":", "cur_max", ",", "max_so_far", "=", "0", ",", "0", "for", "i", "in", "range", "(", "1", ",", "len", "(", "prices", ")", ")", ":", "cur_max", "=", "max", "(", "0", ",", "cur_max", "+", "prices",...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
first_unique_char
:type s: str :rtype: int
algorithms/strings/first_unique_char.py
def first_unique_char(s): """ :type s: str :rtype: int """ if (len(s) == 1): return 0 ban = [] for i in range(len(s)): if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban: return i else: ban.append(s[i]) return -1
def first_unique_char(s): """ :type s: str :rtype: int """ if (len(s) == 1): return 0 ban = [] for i in range(len(s)): if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban: return i else: ban.append(s[i]) return -1
[ ":", "type", "s", ":", "str", ":", "rtype", ":", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/first_unique_char.py#L14-L27
[ "def", "first_unique_char", "(", "s", ")", ":", "if", "(", "len", "(", "s", ")", "==", "1", ")", ":", "return", "0", "ban", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "s", ")", ")", ":", "if", "all", "(", "s", "[", "i", "]...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
Solution.kth_smallest
:type root: TreeNode :type k: int :rtype: int
algorithms/tree/bst/kth_smallest.py
def kth_smallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ count = [] self.helper(root, count) return count[k-1]
def kth_smallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ count = [] self.helper(root, count) return count[k-1]
[ ":", "type", "root", ":", "TreeNode", ":", "type", "k", ":", "int", ":", "rtype", ":", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/bst/kth_smallest.py#L24-L32
[ "def", "kth_smallest", "(", "self", ",", "root", ",", "k", ")", ":", "count", "=", "[", "]", "self", ".", "helper", "(", "root", ",", "count", ")", "return", "count", "[", "k", "-", "1", "]" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
int_to_roman
:type num: int :rtype: str
algorithms/strings/int_to_roman.py
def int_to_roman(num): """ :type num: int :rtype: str """ m = ["", "M", "MM", "MMM"]; c = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]; x = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]; i = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]; ...
def int_to_roman(num): """ :type num: int :rtype: str """ m = ["", "M", "MM", "MMM"]; c = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]; x = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]; i = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]; ...
[ ":", "type", "num", ":", "int", ":", "rtype", ":", "str" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/int_to_roman.py#L6-L15
[ "def", "int_to_roman", "(", "num", ")", ":", "m", "=", "[", "\"\"", ",", "\"M\"", ",", "\"MM\"", ",", "\"MMM\"", "]", "c", "=", "[", "\"\"", ",", "\"C\"", ",", "\"CC\"", ",", "\"CCC\"", ",", "\"CD\"", ",", "\"D\"", ",", "\"DC\"", ",", "\"DCC\"", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
length_longest_path
:type input: str :rtype: int
algorithms/stack/longest_abs_path.py
def length_longest_path(input): """ :type input: str :rtype: int """ curr_len, max_len = 0, 0 # running length and max length stack = [] # keep track of the name length for s in input.split('\n'): print("---------") print("<path>:", s) depth = s.count('\t') #...
def length_longest_path(input): """ :type input: str :rtype: int """ curr_len, max_len = 0, 0 # running length and max length stack = [] # keep track of the name length for s in input.split('\n'): print("---------") print("<path>:", s) depth = s.count('\t') #...
[ ":", "type", "input", ":", "str", ":", "rtype", ":", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/stack/longest_abs_path.py#L36-L58
[ "def", "length_longest_path", "(", "input", ")", ":", "curr_len", ",", "max_len", "=", "0", ",", "0", "# running length and max length", "stack", "=", "[", "]", "# keep track of the name length", "for", "s", "in", "input", ".", "split", "(", "'\\n'", ")", ":",...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
multiply
:type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
algorithms/matrix/sparse_mul.py
def multiply(self, a, b): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ if a is None or b is None: return None m, n, l = len(a), len(b[0]), len(b[0]) if len(b) != n: raise Exception("A's column number must be equal to B's row number.") c = ...
def multiply(self, a, b): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ if a is None or b is None: return None m, n, l = len(a), len(b[0]), len(b[0]) if len(b) != n: raise Exception("A's column number must be equal to B's row number.") c = ...
[ ":", "type", "A", ":", "List", "[", "List", "[", "int", "]]", ":", "type", "B", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "List", "[", "List", "[", "int", "]]" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/matrix/sparse_mul.py#L27-L43
[ "def", "multiply", "(", "self", ",", "a", ",", "b", ")", ":", "if", "a", "is", "None", "or", "b", "is", "None", ":", "return", "None", "m", ",", "n", ",", "l", "=", "len", "(", "a", ")", ",", "len", "(", "b", "[", "0", "]", ")", ",", "l...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
multiply
:type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
algorithms/matrix/sparse_mul.py
def multiply(self, a, b): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ if a is None or b is None: return None m, n = len(a), len(b[0]) if len(b) != n: raise Exception("A's column number must be equal to B's row number.") l = len(b[0]) ...
def multiply(self, a, b): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ if a is None or b is None: return None m, n = len(a), len(b[0]) if len(b) != n: raise Exception("A's column number must be equal to B's row number.") l = len(b[0]) ...
[ ":", "type", "A", ":", "List", "[", "List", "[", "int", "]]", ":", "type", "B", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "List", "[", "List", "[", "int", "]]" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/matrix/sparse_mul.py#L71-L99
[ "def", "multiply", "(", "self", ",", "a", ",", "b", ")", ":", "if", "a", "is", "None", "or", "b", "is", "None", ":", "return", "None", "m", ",", "n", "=", "len", "(", "a", ")", ",", "len", "(", "b", "[", "0", "]", ")", "if", "len", "(", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
bitonic_sort
bitonic sort is sorting algorithm to use multiple process, but this code not containing parallel process It can sort only array that sizes power of 2 It can sort array in both increasing order and decreasing order by giving argument true(increasing) and false(decreasing) Worst-case in parallel: O(log(n...
algorithms/sort/bitonic_sort.py
def bitonic_sort(arr, reverse=False): """ bitonic sort is sorting algorithm to use multiple process, but this code not containing parallel process It can sort only array that sizes power of 2 It can sort array in both increasing order and decreasing order by giving argument true(increasing) and false(de...
def bitonic_sort(arr, reverse=False): """ bitonic sort is sorting algorithm to use multiple process, but this code not containing parallel process It can sort only array that sizes power of 2 It can sort array in both increasing order and decreasing order by giving argument true(increasing) and false(de...
[ "bitonic", "sort", "is", "sorting", "algorithm", "to", "use", "multiple", "process", "but", "this", "code", "not", "containing", "parallel", "process", "It", "can", "sort", "only", "array", "that", "sizes", "power", "of", "2", "It", "can", "sort", "array", ...
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/bitonic_sort.py#L1-L43
[ "def", "bitonic_sort", "(", "arr", ",", "reverse", "=", "False", ")", ":", "def", "compare", "(", "arr", ",", "reverse", ")", ":", "n", "=", "len", "(", "arr", ")", "//", "2", "for", "i", "in", "range", "(", "n", ")", ":", "if", "reverse", "!="...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
scc
Computes the strongly connected components of a graph
algorithms/graph/satisfiability.py
def scc(graph): ''' Computes the strongly connected components of a graph ''' order = [] vis = {vertex: False for vertex in graph} graph_transposed = {vertex: [] for vertex in graph} for (v, neighbours) in graph.iteritems(): for u in neighbours: add_edge(graph_transposed, u, v)...
def scc(graph): ''' Computes the strongly connected components of a graph ''' order = [] vis = {vertex: False for vertex in graph} graph_transposed = {vertex: [] for vertex in graph} for (v, neighbours) in graph.iteritems(): for u in neighbours: add_edge(graph_transposed, u, v)...
[ "Computes", "the", "strongly", "connected", "components", "of", "a", "graph" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/graph/satisfiability.py#L49-L74
[ "def", "scc", "(", "graph", ")", ":", "order", "=", "[", "]", "vis", "=", "{", "vertex", ":", "False", "for", "vertex", "in", "graph", "}", "graph_transposed", "=", "{", "vertex", ":", "[", "]", "for", "vertex", "in", "graph", "}", "for", "(", "v...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
build_graph
Builds the implication graph from the formula
algorithms/graph/satisfiability.py
def build_graph(formula): ''' Builds the implication graph from the formula ''' graph = {} for clause in formula: for (lit, _) in clause: for neg in [False, True]: graph[(lit, neg)] = [] for ((a_lit, a_neg), (b_lit, b_neg)) in formula: add_edge(graph, (a_lit...
def build_graph(formula): ''' Builds the implication graph from the formula ''' graph = {} for clause in formula: for (lit, _) in clause: for neg in [False, True]: graph[(lit, neg)] = [] for ((a_lit, a_neg), (b_lit, b_neg)) in formula: add_edge(graph, (a_lit...
[ "Builds", "the", "implication", "graph", "from", "the", "formula" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/graph/satisfiability.py#L77-L90
[ "def", "build_graph", "(", "formula", ")", ":", "graph", "=", "{", "}", "for", "clause", "in", "formula", ":", "for", "(", "lit", ",", "_", ")", "in", "clause", ":", "for", "neg", "in", "[", "False", ",", "True", "]", ":", "graph", "[", "(", "l...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
unique_array_sum_combinations
1. Sort all the arrays - a,b,c. - This improves average time complexity. 2. If c[i] < Sum, then look for Sum - c[i] in array a and b. When pair found, insert c[i], a[j] & b[k] into the result list. This can be done in O(n). 3. Keep on doing the above procedure while going through complete c array....
algorithms/backtrack/array_sum_combinations.py
def unique_array_sum_combinations(A, B, C, target): """ 1. Sort all the arrays - a,b,c. - This improves average time complexity. 2. If c[i] < Sum, then look for Sum - c[i] in array a and b. When pair found, insert c[i], a[j] & b[k] into the result list. This can be done in O(n). 3. Keep on...
def unique_array_sum_combinations(A, B, C, target): """ 1. Sort all the arrays - a,b,c. - This improves average time complexity. 2. If c[i] < Sum, then look for Sum - c[i] in array a and b. When pair found, insert c[i], a[j] & b[k] into the result list. This can be done in O(n). 3. Keep on...
[ "1", ".", "Sort", "all", "the", "arrays", "-", "a", "b", "c", ".", "-", "This", "improves", "average", "time", "complexity", ".", "2", ".", "If", "c", "[", "i", "]", "<", "Sum", "then", "look", "for", "Sum", "-", "c", "[", "i", "]", "in", "ar...
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/backtrack/array_sum_combinations.py#L59-L84
[ "def", "unique_array_sum_combinations", "(", "A", ",", "B", ",", "C", ",", "target", ")", ":", "def", "check_sum", "(", "n", ",", "*", "nums", ")", ":", "if", "sum", "(", "x", "for", "x", "in", "nums", ")", "==", "n", ":", "return", "(", "True", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
is_bst
:type root: TreeNode :rtype: bool
algorithms/tree/bst/is_bst.py
def is_bst(root): """ :type root: TreeNode :rtype: bool """ stack = [] pre = None while root or stack: while root: stack.append(root) root = root.left root = stack.pop() if pre and root.val <= pre.val: return False pre...
def is_bst(root): """ :type root: TreeNode :rtype: bool """ stack = [] pre = None while root or stack: while root: stack.append(root) root = root.left root = stack.pop() if pre and root.val <= pre.val: return False pre...
[ ":", "type", "root", ":", "TreeNode", ":", "rtype", ":", "bool" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/bst/is_bst.py#L23-L42
[ "def", "is_bst", "(", "root", ")", ":", "stack", "=", "[", "]", "pre", "=", "None", "while", "root", "or", "stack", ":", "while", "root", ":", "stack", ".", "append", "(", "root", ")", "root", "=", "root", ".", "left", "root", "=", "stack", ".", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
__get_depth
return 0 if unbalanced else depth + 1
algorithms/tree/is_balanced.py
def __get_depth(root): """ return 0 if unbalanced else depth + 1 """ if root is None: return 0 left = __get_depth(root.left) right = __get_depth(root.right) if abs(left-right) > 1 or -1 in [left, right]: return -1 return 1 + max(left, right)
def __get_depth(root): """ return 0 if unbalanced else depth + 1 """ if root is None: return 0 left = __get_depth(root.left) right = __get_depth(root.right) if abs(left-right) > 1 or -1 in [left, right]: return -1 return 1 + max(left, right)
[ "return", "0", "if", "unbalanced", "else", "depth", "+", "1" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/is_balanced.py#L12-L22
[ "def", "__get_depth", "(", "root", ")", ":", "if", "root", "is", "None", ":", "return", "0", "left", "=", "__get_depth", "(", "root", ".", "left", ")", "right", "=", "__get_depth", "(", "root", ".", "right", ")", "if", "abs", "(", "left", "-", "rig...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
copy_random_pointer_v1
:type head: RandomListNode :rtype: RandomListNode
algorithms/linkedlist/copy_random_pointer.py
def copy_random_pointer_v1(head): """ :type head: RandomListNode :rtype: RandomListNode """ dic = dict() m = n = head while m: dic[m] = RandomListNode(m.label) m = m.next while n: dic[n].next = dic.get(n.next) dic[n].random = dic.get(n.random) n = ...
def copy_random_pointer_v1(head): """ :type head: RandomListNode :rtype: RandomListNode """ dic = dict() m = n = head while m: dic[m] = RandomListNode(m.label) m = m.next while n: dic[n].next = dic.get(n.next) dic[n].random = dic.get(n.random) n = ...
[ ":", "type", "head", ":", "RandomListNode", ":", "rtype", ":", "RandomListNode" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/copy_random_pointer.py#L17-L31
[ "def", "copy_random_pointer_v1", "(", "head", ")", ":", "dic", "=", "dict", "(", ")", "m", "=", "n", "=", "head", "while", "m", ":", "dic", "[", "m", "]", "=", "RandomListNode", "(", "m", ".", "label", ")", "m", "=", "m", ".", "next", "while", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
copy_random_pointer_v2
:type head: RandomListNode :rtype: RandomListNode
algorithms/linkedlist/copy_random_pointer.py
def copy_random_pointer_v2(head): """ :type head: RandomListNode :rtype: RandomListNode """ copy = defaultdict(lambda: RandomListNode(0)) copy[None] = None node = head while node: copy[node].label = node.label copy[node].next = copy[node.next] copy[node].random = ...
def copy_random_pointer_v2(head): """ :type head: RandomListNode :rtype: RandomListNode """ copy = defaultdict(lambda: RandomListNode(0)) copy[None] = None node = head while node: copy[node].label = node.label copy[node].next = copy[node.next] copy[node].random = ...
[ ":", "type", "head", ":", "RandomListNode", ":", "rtype", ":", "RandomListNode" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/copy_random_pointer.py#L35-L48
[ "def", "copy_random_pointer_v2", "(", "head", ")", ":", "copy", "=", "defaultdict", "(", "lambda", ":", "RandomListNode", "(", "0", ")", ")", "copy", "[", "None", "]", "=", "None", "node", "=", "head", "while", "node", ":", "copy", "[", "node", "]", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3