Code
stringlengths
103
85.9k
Summary
sequencelengths
0
94
Please provide a description of the function:def cocktail_shaker_sort(arr): def swap(i, j): arr[i], arr[j] = arr[j], arr[i] n = len(arr) swapped = True while swapped: swapped = False for i in range(1, n): if arr[i - 1] > arr[i]: swap(i - 1, i) swapped = True if swapped == False: return arr swapped = False for i in range(n-1,0,-1): if arr[i - 1] > arr[i]: swap(i - 1, i) swapped = True return arr
[ "\n Cocktail_shaker_sort\n Sorting a given array\n mutation of bubble sort\n\n reference: https://en.wikipedia.org/wiki/Cocktail_shaker_sort\n \n Worst-case performance: O(N^2)\n " ]
Please provide a description of the function:def reconstruct_queue(people): queue = [] people.sort(key=lambda x: (-x[0], x[1])) for h, k in people: queue.insert(k, [h, k]) return queue
[ "\n :type people: List[List[int]]\n :rtype: List[List[int]]\n " ]
Please provide a description of the function:def min_depth(self, root): if root is None: return 0 if root.left is not None or root.right is not None: return max(self.minDepth(root.left), self.minDepth(root.right))+1 return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
[ "\n :type root: TreeNode\n :rtype: int\n " ]
Please provide a description of the function:def is_one_edit(s, t): if len(s) > len(t): return is_one_edit(t, s) if len(t) - len(s) > 1 or t == s: return False for i in range(len(s)): if s[i] != t[i]: return s[i+1:] == t[i+1:] or s[i:] == t[i+1:] return True
[ "\n :type s: str\n :type t: str\n :rtype: bool\n " ]
Please provide a description of the function:def shell_sort(arr): ''' Shell Sort Complexity: O(n^2) ''' n = len(arr) # Initialize size of the gap gap = n//2 while gap > 0: y_index = gap while y_index < len(arr): y = arr[y_index] x_index = y_index - gap while x_index >= 0 and y < arr[x_index]: arr[x_index + gap] = arr[x_index] x_index = x_index - gap arr[x_index + gap] = y y_index = y_index + 1 gap = gap//2 return arr
[]
Please provide a description of the function:def common_prefix(s1, s2): "Return prefix common of 2 strings" if not s1 or not s2: return "" k = 0 while s1[k] == s2[k]: k = k + 1 if k >= len(s1) or k >= len(s2): return s1[0:k] return s1[0:k]
[]
Please provide a description of the function:def euler_totient(n): result = n; for i in range(2, int(n ** 0.5) + 1): if n % i == 0: while n % i == 0: n //= i result -= result // i if n > 1: result -= result // n; return result;
[ "Euler's totient function or Phi function.\n Time Complexity: O(sqrt(n))." ]
Please provide a description of the function:def is_palindrome_dict(head): if not head or not head.next: return True d = {} pos = 0 while head: if head.val in d.keys(): d[head.val].append(pos) else: d[head.val] = [pos] head = head.next pos += 1 checksum = pos - 1 middle = 0 for v in d.values(): if len(v) % 2 != 0: middle += 1 else: step = 0 for i in range(0, len(v)): if v[i] + v[len(v) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
[ "\n This function builds up a dictionary where the keys are the values of the list,\n and the values are the positions at which these values occur in the list.\n We then iterate over the dict and if there is more than one key with an odd\n number of occurrences, bail out and return False.\n Otherwise, we want to ensure that the positions of occurrence sum to the\n value of the length of the list - 1, working from the outside of the list inward.\n For example:\n Input: 1 -> 1 -> 2 -> 3 -> 2 -> 1 -> 1\n d = {1: [0,1,5,6], 2: [2,4], 3: [3]}\n '3' is the middle outlier, 2+4=6, 0+6=6 and 5+1=6 so we have a palindrome.\n " ]
Please provide a description of the function:def fib_list(n): # precondition assert n >= 0, 'n must be a positive integer' list_results = [0, 1] for i in range(2, n+1): list_results.append(list_results[i-1] + list_results[i-2]) return list_results[n]
[ "[summary]\n This algorithm computes the n-th fibbonacci number\n very quick. approximate O(n)\n The algorithm use dynamic programming.\n \n Arguments:\n n {[int]} -- [description]\n \n Returns:\n [int] -- [description]\n " ]
Please provide a description of the function:def fib_iter(n): # precondition assert n >= 0, 'n must be positive integer' fib_1 = 0 fib_2 = 1 sum = 0 if n <= 1: return n for _ in range(n-1): sum = fib_1 + fib_2 fib_1 = fib_2 fib_2 = sum return sum
[ "[summary]\n Works iterative approximate O(n)\n\n Arguments:\n n {[int]} -- [description]\n \n Returns:\n [int] -- [description]\n " ]
Please provide a description of the function:def subsets(nums): n = len(nums) total = 1 << n res = set() for i in range(total): subset = tuple(num for j, num in enumerate(nums) if i & 1 << j) res.add(subset) return res
[ "\n :param nums: List[int]\n :return: Set[tuple]\n " ]
Please provide a description of the function:def lcs(s1, s2, i, j): 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))
[ "\n The length of longest common subsequence among the two given strings s1 and s2\n " ]
Please provide a description of the function: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 = lca(root.right, p, q) if left is not None and right is not None: return root return left if left else right
[ "\n :type root: TreeNode\n :type p: TreeNode\n :type q: TreeNode\n :rtype: TreeNode\n " ]
Please provide a description of the function:def lowest_common_ancestor(root, p, q): 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
[ "\n :type root: Node\n :type p: Node\n :type q: Node\n :rtype: Node\n " ]
Please provide a description of the function:def climb_stairs(n): arr = [1, 1] for _ in range(1, n): arr.append(arr[-1] + arr[-2]) return arr[-1]
[ "\n :type n: int\n :rtype: int\n " ]
Please provide a description of the function:def find_nth_digit(n): length = 1 count = 9 start = 1 while n > length * count: n -= length * count length += 1 count *= 10 start *= 10 start += (n-1) / length s = str(start) return int(s[(n-1) % length])
[ "find the nth digit of given number.\n 1. find the length of the number where the nth digit is from.\n 2. find the actual number where the nth digit is from\n 3. find the nth digit and return\n " ]
Please provide a description of the function:def hailstone(n): 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 n: The starting point of the hailstone sequence\n " ]
Please provide a description of the function:def word_break(s, word_dict): 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 return dp[-1]
[ "\n :type s: str\n :type word_dict: Set[str]\n :rtype: bool\n " ]
Please provide a description of the function: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 j = 5 while j * j <= n: if n % j == 0 or n % (j + 2) == 0: return False j += 6 return True
[ "Return True if n is a prime number\n Else return False.\n " ]
Please provide a description of the function: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 string[i] in dict: j = max(dict[string[i]], j) dict[string[i]] = i + 1 max_length = max(max_length, i - j + 1) return max_length
[ "\n Find the length of the longest substring\n without repeating characters.\n " ]
Please provide a description of the function: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): if char in used_char and start <= used_char[char]: start = used_char[char] + 1 else: max_len = max(max_len, index - start + 1) used_char[char] = index return max_len
[ "\n Find the length of the longest substring\n without repeating characters.\n Uses alternative algorithm.\n " ]
Please provide a description of the function: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(string)): if string[i] in dict: j = max(dict[string[i]], j) dict[string[i]] = i + 1 if i - j + 1 > max_length: max_length = i - j + 1 sub_string = string[j: i + 1] return max_length, sub_string
[ "\n Find the length of the longest substring\n without repeating characters.\n Return max_len and the substring as a tuple\n " ]
Please provide a description of the function: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 in enumerate(string): if char in used_char and start <= used_char[char]: start = used_char[char] + 1 else: if index - start + 1 > max_len: max_len = index - start + 1 sub_string = string[start: index + 1] used_char[char] = index return max_len, sub_string
[ "\n Find the length of the longest substring\n without repeating characters.\n Uses alternative algorithm.\n Return max_len and the substring as a tuple\n " ]
Please provide a description of the function:def push(self, item, priority=None): priority = item if priority is None else priority node = PriorityQueueNode(item, priority) for index, current in enumerate(self.priority_queue_list): if current.priority < node.priority: self.priority_queue_list.insert(index, node) return # when traversed complete queue self.priority_queue_list.append(node)
[ "Push the item in the priority queue.\n if priority is not given, priority is set to the value of item.\n " ]
Please provide a description of the function: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 not None and not (isinstance(mod, int) and mod > 0): raise ValueError("'mod' must be a positive integer") result = 1 if n == 0: return 1 for i in range(2, n+1): result *= i if mod: result %= mod return result
[ "Calculates factorial iteratively.\n If mod is not None, then return (n! % mod)\n Time Complexity - O(n)" ]
Please provide a description of the function: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 is not None and not (isinstance(mod, int) and mod > 0): raise ValueError("'mod' must be a positive integer") if n == 0: return 1 result = n * factorial(n - 1, mod) if mod: result %= mod return result
[ "Calculates factorial recursively.\n If mod is not None, then return (n! % mod)\n Time Complexity - O(n)" ]
Please provide a description of the function:def selection_sort(arr, simulation=False): 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 correct value if arr[j] < arr[minimum]: minimum = j arr[minimum], arr[i] = arr[i], arr[minimum] if simulation: iteration = iteration + 1 print("iteration",iteration,":",*arr) return arr
[ " Selection Sort\n Complexity: O(n^2)\n " ]
Please provide a description of the function:def remove_dups(head): 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
[ "\n Time Complexity: O(N)\n Space Complexity: O(N)\n " ]
Please provide a description of the function:def remove_dups_wothout_set(head): current = head while current: runner = current while runner.next: if runner.next.val == current.val: runner.next = runner.next.next else: runner = runner.next current = current.next
[ "\n Time Complexity: O(N^2)\n Space Complexity: O(1)\n " ]
Please provide a description of the function: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.left = node_v elif node_u is node_u.parent.right: node_u.parent.right = node_v # check is node_v is None if node_v: node_v.parent = node_u.parent
[ "\n replace u with v\n :param node_u: replaced node\n :param node_v: \n :return: None\n " ]
Please provide a description of the function:def maximum(self, node): temp_node = node while temp_node.right is not None: temp_node = temp_node.right return temp_node
[ "\n find the max node when node regard as a root node \n :param node: \n :return: max node \n " ]
Please provide a description of the function:def minimum(self, node): temp_node = node while temp_node.left: temp_node = temp_node.left return temp_node
[ "\n find the minimum node when node regard as a root node \n :param node:\n :return: minimum node \n " ]
Please provide a description of the function:def modular_exponential(base, exponent, mod): if exponent < 0: raise ValueError("Exponent must be positive.") base %= mod result = 1 while exponent > 0: # If the last bit is 1, add 2^k. if exponent & 1: result = (result * base) % mod exponent = exponent >> 1 # Utilize modular multiplication properties to combine the computed mod C values. base = (base * base) % mod return result
[ "Computes (base ^ exponent) % mod.\n Time complexity - O(log n)\n Use similar to Python in-built function pow." ]
Please provide a description of the function:def can_attend_meetings(intervals): 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
[ "\n :type intervals: List[Interval]\n :rtype: bool\n " ]
Please provide a description of the function: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 = root.left while left_right_most.right: left_right_most = left_right_most.right # Attach right child to the right of that leaf left_right_most.right = root.right # Return left child instead of root, a.k.a delete root return root.left else: return root.right # If left or right child got deleted, the returned root is the child of the deleted node. elif root.val > key: root.left = self.deleteNode(root.left, key) else: root.right = self.deleteNode(root.right, key) return root
[ "\n :type root: TreeNode\n :type key: int\n :rtype: TreeNode\n " ]
Please provide a description of the function:def simplify_path(path): skip = {'..', '.', ''} stack = [] paths = path.split('/') for tok in paths: if tok == '..': if stack: stack.pop() elif tok not in skip: stack.append(tok) return '/' + '/'.join(stack)
[ "\n :type path: str\n :rtype: str\n " ]
Please provide a description of the function:def subsets(nums): 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() # dont take nums[pos] backtrack(res, nums, stack, pos+1) res = [] backtrack(res, nums, [], 0) return res
[ "\n O(2**n)\n " ]
Please provide a description of the function: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 contain taget value # find block that contains target value if arr[n - 1] < target: return -1 while block <= n and arr[block - 1] < target: block_prev = block block += block_size # find target value in block while arr[block_prev] < target : block_prev += 1 if block_prev == min(block, n) : return -1 # if there is target value in array, return it if arr[block_prev] == target : return block_prev else : return -1
[ "Jump Search\n Worst-case Complexity: O(√n) (root(n))\n All items in list must be sorted like binary search\n\n Find block that contains target value and search it linearly in that block\n It returns a first target value in array\n\n reference: https://en.wikipedia.org/wiki/Jump_search\n\n " ]
Please provide a description of the function:def flatten_iter(iterable): for element in iterable: if isinstance(element, Iterable): yield from flatten_iter(element) else: yield element
[ "\n Takes as input multi dimensional iterable and\n returns generator which produces one dimensional output.\n " ]
Please provide a description of the function: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 0 # when only differ by 1 character if sum(c1 != c2 for c1, c2 in zip(begin_word, end_word)) == 1: return 1 begin_set = set() end_set = set() begin_set.add(begin_word) end_set.add(end_word) result = 2 while begin_set and end_set: if len(begin_set) > len(end_set): begin_set, end_set = end_set, begin_set next_begin_set = set() for word in begin_set: for ladder_word in word_range(word): if ladder_word in end_set: return result if ladder_word in word_list: next_begin_set.add(ladder_word) word_list.remove(ladder_word) begin_set = next_begin_set result += 1 # print(begin_set) # print(result) return -1
[ "\n Bidirectional BFS!!!\n :type begin_word: str\n :type end_word: str\n :type word_list: Set[str]\n :rtype: int\n " ]
Please provide a description of the function:def convolved(iterable, kernel_size=1, stride=1, padding=0, default_value=None): # Input validation and error messages if not hasattr(iterable, '__iter__'): raise ValueError( "Can't iterate on object.".format( iterable)) if stride < 1: raise ValueError( "Stride must be of at least one. Got `stride={}`.".format( stride)) if not (padding in ['SAME', 'VALID'] or type(padding) in [int]): raise ValueError( "Padding must be an integer or a string with value `SAME` or `VALID`.") if not isinstance(padding, str): if padding < 0: raise ValueError( "Padding must be of at least zero. Got `padding={}`.".format( padding)) else: if padding == 'SAME': padding = kernel_size // 2 elif padding == 'VALID': padding = 0 if not type(iterable) == list: iterable = list(iterable) # Add padding to iterable if padding > 0: pad = [default_value] * padding iterable = pad + list(iterable) + pad # Fill missing value to the right remainder = (kernel_size - len(iterable)) % stride extra_pad = [default_value] * remainder iterable = iterable + extra_pad i = 0 while True: if i > len(iterable) - kernel_size: break yield iterable[i:i + kernel_size] i += stride
[ "Iterable to get every convolution window per loop iteration.\n\n For example:\n `convolved([1, 2, 3, 4], kernel_size=2)`\n will produce the following result:\n `[[1, 2], [2, 3], [3, 4]]`.\n `convolved([1, 2, 3], kernel_size=2, stride=1, padding=2, default_value=42)`\n will produce the following result:\n `[[42, 42], [42, 1], [1, 2], [2, 3], [3, 42], [42, 42]]`\n\n Arguments:\n iterable: An object to iterate on. It should support slice indexing if `padding == 0`.\n kernel_size: The number of items yielded at every iteration.\n stride: The step size between each iteration.\n padding: Padding must be an integer or a string with value `SAME` or `VALID`. If it is an integer, it represents\n how many values we add with `default_value` on the borders. If it is a string, `SAME` means that the\n convolution will add some padding according to the kernel_size, and `VALID` is the same as\n specifying `padding=0`.\n default_value: Default fill value for padding and values outside iteration range.\n\n For more information, refer to: \n - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py\n - https://github.com/guillaume-chevalier/python-conv-lib\n - MIT License, Copyright (c) 2018 Guillaume Chevalier\n " ]
Please provide a description of the function:def convolved_1d(iterable, kernel_size=1, stride=1, padding=0, default_value=None): return convolved(iterable, kernel_size, stride, padding, default_value)
[ "1D Iterable to get every convolution window per loop iteration.\n\n For more information, refer to:\n - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py\n - https://github.com/guillaume-chevalier/python-conv-lib\n - MIT License, Copyright (c) 2018 Guillaume Chevalier\n " ]
Please provide a description of the function:def convolved_2d(iterable, kernel_size=1, stride=1, padding=0, default_value=None): kernel_size = dimensionize(kernel_size, nd=2) stride = dimensionize(stride, nd=2) padding = dimensionize(padding, nd=2) for row_packet in convolved(iterable, kernel_size[0], stride[0], padding[0], default_value): transposed_inner = [] for col in tuple(row_packet): transposed_inner.append(list( convolved(col, kernel_size[1], stride[1], padding[1], default_value) )) if len(transposed_inner) > 0: for col_i in range(len(transposed_inner[0])): yield tuple(row_j[col_i] for row_j in transposed_inner)
[ "2D Iterable to get every convolution window per loop iteration.\n\n For more information, refer to:\n - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py\n - https://github.com/guillaume-chevalier/python-conv-lib\n - MIT License, Copyright (c) 2018 Guillaume Chevalier\n " ]
Please provide a description of the function: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] * nd return now_a_list else: # Argument is probably an `nd`-sized list. return maybe_a_list
[ "Convert integers to a list of integers to fit the number of dimensions if\n the argument is not already a list.\n\n For example:\n `dimensionize(3, nd=2)`\n will produce the following result:\n `(3, 3)`.\n `dimensionize([3, 1], nd=2)`\n will produce the following result:\n `[3, 1]`.\n\n For more information, refer to:\n - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py\n - https://github.com/guillaume-chevalier/python-conv-lib\n - MIT License, Copyright (c) 2018 Guillaume Chevalier\n " ]
Please provide a description of the function:def max_sliding_window(nums, k): 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)) queue.popleft() queue.append(num) res.append(max(queue)) return res
[ "\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n " ]
Please provide a description of the function:def merge_intervals(intervals): 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: out.append(i) return out
[ " Merge intervals in the form of a list. " ]
Please provide a description of the function:def merge(intervals): 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. " ]
Please provide a description of the function:def print_intervals(intervals): res = [] for i in intervals: res.append(repr(i)) print("".join(res))
[ " Print out the intervals. " ]
Please provide a description of the function:def rotate_v1(array, k): array = array[:] n = len(array) for i in range(k): # unused variable is not a problem temp = array[n - 1] for j in range(n-1, 0, -1): array[j] = array[j - 1] array[0] = temp return array
[ "\n Rotate the entire array 'k' times\n T(n)- O(nk)\n\n :type array: List[int]\n :type k: int\n :rtype: void Do not return anything, modify array in-place instead.\n " ]
Please provide a description of the function:def rotate_v2(array, k): array = array[:] def reverse(arr, a, b): while a < b: arr[a], arr[b] = arr[b], arr[a] a += 1 b -= 1 n = len(array) k = k % n reverse(array, 0, n - k - 1) reverse(array, n - k, n - 1) reverse(array, 0, n - 1) return array
[ "\n Reverse segments of the array, followed by the entire array\n T(n)- O(n)\n :type array: List[int]\n :type k: int\n :rtype: void Do not return anything, modify nums in-place instead.\n " ]
Please provide a description of the function:def pacific_atlantic(matrix): 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 _ in range(m)] for i in range(n): dfs(pacific, matrix, float("-inf"), i, 0) dfs(atlantic, matrix, float("-inf"), i, m-1) for i in range(m): dfs(pacific, matrix, float("-inf"), 0, i) dfs(atlantic, matrix, float("-inf"), n-1, i) for i in range(n): for j in range(m): if pacific[i][j] and atlantic[i][j]: res.append([i, j]) return res
[ "\n :type matrix: List[List[int]]\n :rtype: List[List[int]]\n " ]
Please provide a description of the function:def quick_sort(arr, simulation=False): iteration = 0 if simulation: print("iteration",iteration,":",*arr) arr, _ = quick_sort_recur(arr, 0, len(arr) - 1, iteration, simulation) return arr
[ " Quick sort\n Complexity: best O(n log(n)) avg O(n log(n)), worst O(N^2)\n " ]
Please provide a description of the function:def is_palindrome(s): 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 = i+1, j-1 return True
[ "\n :type s: str\n :rtype: bool\n " ]
Please provide a description of the function:def plus_one_v1(digits): 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.append(summ % 10) ten = summ // 10 i -= 1 return res[::-1]
[ "\n :type digits: List[int]\n :rtype: List[int]\n " ]
Please provide a description of the function: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 = current.next length += 1 # make it circular current.next = head k = k % length # rotate until length-k for i in range(length-k): current = current.next head = current.next current.next = None return head
[ "\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n " ]
Please provide a description of the function: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)): 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_last wo_last = x+y return wo_last
[ "\n :type s: str\n :rtype: int\n " ]
Please provide a description of the function:def search_range(nums, target): 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]: low = mid + 1 else: break for j in range(len(nums) - 1, -1, -1): if nums[j] == target: return [mid, j] return [-1, -1]
[ "\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n " ]
Please provide a description of the function:def first_cyclic_node(head): 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 walker = head while runner is not walker: runner, walker = runner.next, walker.next return runner
[ "\n :type head: Node\n :rtype: Node\n " ]
Please provide a description of the function:def max_heap_sort(arr, simulation=False): iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr) - 1, 0, -1): iteration = max_heapify(arr, i, simulation, iteration) if simulation: iteration = iteration + 1 print("iteration",iteration,":",*arr) return arr
[ " Heap Sort that uses a max heap to sort an array in ascending order\n Complexity: O(n log(n))\n " ]
Please provide a description of the function: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, -1): current_parent = parent # Iterate from current_parent to last_parent while current_parent <= last_parent: # Find greatest child of current_parent child = 2 * current_parent + 1 if child + 1 <= end and arr[child] < arr[child + 1]: child = child + 1 # Swap if child is greater than parent if arr[child] > arr[current_parent]: arr[current_parent], arr[child] = arr[child], arr[current_parent] current_parent = child if simulation: iteration = iteration + 1 print("iteration",iteration,":",*arr) # If no swap occured, no need to keep iterating else: break arr[0], arr[end] = arr[end], arr[0] return iteration
[ " Max heapify helper for max_heap_sort\n " ]
Please provide a description of the function:def min_heap_sort(arr, simulation=False): iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(0, len(arr) - 1): iteration = min_heapify(arr, i, simulation, iteration) return arr
[ " Heap Sort that uses a min heap to sort an array in ascending order\n Complexity: O(n log(n))\n " ]
Please provide a description of the function: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) - 1 last_parent = (end - start - 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 while current_parent <= last_parent: # Find lesser child of current_parent child = 2 * current_parent + 1 if child + 1 <= end - start and arr[child + start] > arr[ child + 1 + start]: child = child + 1 # Swap if child is less than parent if arr[child + start] < arr[current_parent + start]: arr[current_parent + start], arr[child + start] = \ arr[child + start], arr[current_parent + start] current_parent = child if simulation: iteration = iteration + 1 print("iteration",iteration,":",*arr) # If no swap occured, no need to keep iterating else: break return iteration
[ " Min heapify helper for min_heap_sort\n " ]
Please provide a description of the function:def generate_key(k, seed=None): def modinv(a, m): b = 1 while not (a * b) % m == 1: b += 1 return b def gen_prime(k, seed=None): def is_prime(num): if num == 2: return True for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True random.seed(seed) while True: key = random.randrange(int(2 ** (k - 1)), int(2 ** k)) if is_prime(key): return key # size in bits of p and q need to add up to the size of n p_size = k / 2 q_size = k - p_size e = gen_prime(k, seed) # in many cases, e is also chosen to be a small constant while True: p = gen_prime(p_size, seed) if p % e != 1: break while True: q = gen_prime(q_size, seed) if q % e != 1: break n = p * q l = (p - 1) * (q - 1) # calculate totient function d = modinv(e, l) return int(n), int(e), int(d)
[ "\n the RSA key generating algorithm\n k is the number of bits in n\n ", "calculate the inverse of a mod m\n that is, find b such that (a * b) % m == 1", "generate a prime with k bits" ]
Please provide a description of the function:def square_root(n, epsilon=0.001): 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" ]
Please provide a description of the function: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 all positive number different = -m for i in range(len(arr)): arr[i] += -m k = max(arr) temp_arr = [0] * (k + 1) for i in range(0, len(arr)): temp_arr[arr[i]] = temp_arr[arr[i]] + 1 # temp_array[i] contain the times the number i appear in arr for i in range(1, k + 1): temp_arr[i] = temp_arr[i] + temp_arr[i - 1] # temp_array[i] contain the number of element less than or equal i in arr result_arr = arr.copy() # creating a result_arr an put the element in a correct positon for i in range(len(arr) - 1, -1, -1): result_arr[temp_arr[arr[i]] - 1] = arr[i] - different temp_arr[arr[i]] = temp_arr[arr[i]] - 1 return result_arr
[ "\n Counting_sort\n Sorting a array which has no element greater than k\n Creating a new temp_arr,where temp_arr[i] contain the number of\n element less than or equal to i in the arr\n Then placing the number i into a correct position in the result_arr\n return the result_arr\n Complexity: 0(n)\n " ]
Please provide a description of the function: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 r in range(len(s) + 1))
[ "Calculate the powerset of any iterable.\n\n For a range of integers up to the length of the given list,\n make all possible combinations and chain them together as one object.\n From https://docs.python.org/3/library/itertools.html#itertools-recipes\n " ]
Please provide a description of the function:def optimal_set_cover(universe, subsets, costs): pset = powerset(subsets.keys()) best_set = None best_cost = float("inf") for subset in pset: covered = set() cost = 0 for s in subset: covered.update(subsets[s]) cost += costs[s] if len(covered) == len(universe) and cost < best_cost: best_set = subset best_cost = cost return best_set
[ " Optimal algorithm - DONT USE ON BIG INPUTS - O(2^n) complexity!\n Finds the minimum cost subcollection os S that covers all elements of U\n\n Args:\n universe (list): Universe of elements\n subsets (dict): Subsets of U {S1:elements,S2:elements}\n costs (dict): Costs of each subset in S - {S1:cost, S2:cost...}\n " ]
Please provide a description of the function: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 -> invalid input for set cover if elements != universe: return None # track elements of universe covered covered = set() cover_sets = [] while covered != universe: min_cost_elem_ratio = float("inf") min_set = None # find set with minimum cost:elements_added ratio for s, elements in subsets.items(): new_elements = len(elements - covered) # set may have same elements as already covered -> new_elements = 0 # check to avoid division by 0 error if new_elements != 0: cost_elem_ratio = costs[s] / new_elements if cost_elem_ratio < min_cost_elem_ratio: min_cost_elem_ratio = cost_elem_ratio min_set = s cover_sets.append(min_set) # union covered |= subsets[min_set] return cover_sets
[ "Approximate greedy algorithm for set-covering. Can be used on large\n inputs - though not an optimal solution.\n\n Args:\n universe (list): Universe of elements\n subsets (dict): Subsets of U {S1:elements,S2:elements}\n costs (dict): Costs of each subset in S - {S1:cost, S2:cost...}\n " ]
Please provide a description of the function:def num_trees(n): 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]
[ "\n :type n: int\n :rtype: int\n " ]
Please provide a description of the function:def next(self, val): self.queue.append(val) return sum(self.queue) / len(self.queue)
[ "\n :type val: int\n :rtype: float\n " ]
Please provide a description of the function:def n_sum(n, nums, target, **kv): def sum_closure_default(a, b): return a + b def compare_closure_default(num, target): if num < target: return -1 elif num > target: return 1 else: return 0 def same_closure_default(a, b): return a == b def n_sum(n, nums, target): if n == 2: # want answers with only 2 terms? easy! results = two_sum(nums, target) else: results = [] prev_num = None for index, num in enumerate(nums): if prev_num is not None and \ same_closure(prev_num, num): continue prev_num = num n_minus1_results = ( n_sum( # recursive call n - 1, # a nums[index + 1:], # b target - num # c ) # x = n_sum( a, b, c ) ) # n_minus1_results = x n_minus1_results = ( append_elem_to_each_list(num, n_minus1_results) ) results += n_minus1_results return union(results) def two_sum(nums, target): nums.sort() lt = 0 rt = len(nums) - 1 results = [] while lt < rt: sum_ = sum_closure(nums[lt], nums[rt]) flag = compare_closure(sum_, target) if flag == -1: lt += 1 elif flag == 1: rt -= 1 else: results.append(sorted([nums[lt], nums[rt]])) lt += 1 rt -= 1 while (lt < len(nums) and same_closure(nums[lt - 1], nums[lt])): lt += 1 while (0 <= rt and same_closure(nums[rt], nums[rt + 1])): rt -= 1 return results def append_elem_to_each_list(elem, container): results = [] for elems in container: elems.append(elem) results.append(sorted(elems)) return results def union(duplicate_results): results = [] if len(duplicate_results) != 0: duplicate_results.sort() results.append(duplicate_results[0]) for result in duplicate_results[1:]: if results[-1] != result: results.append(result) return results sum_closure = kv.get('sum_closure', sum_closure_default) same_closure = kv.get('same_closure', same_closure_default) compare_closure = kv.get('compare_closure', compare_closure_default) nums.sort() return n_sum(n, nums, target)
[ "\n n: int\n nums: list[object]\n target: object\n sum_closure: function, optional\n Given two elements of nums, return sum of both.\n compare_closure: function, optional\n Given one object of nums and target, return -1, 1, or 0.\n same_closure: function, optional\n Given two object of nums, return bool.\n return: list[list[object]]\n\n Note:\n 1. type of sum_closure's return should be same \n as type of compare_closure's first param\n ", " above, below, or right on? " ]
Please provide a description of the function:def pattern_match(pattern, string): 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 range(1, len(string)-len(pattern)+2): if pattern[0] not in dic and string[:end] not in dic.values(): dic[pattern[0]] = string[:end] if backtrack(pattern[1:], string[end:], dic): return True del dic[pattern[0]] elif pattern[0] in dic and dic[pattern[0]] == string[:end]: if backtrack(pattern[1:], string[end:], dic): return True return False return backtrack(pattern, string, {})
[ "\n :type pattern: str\n :type string: str\n :rtype: bool\n " ]
Please provide a description of the function:def bogo_sort(arr, simulation=False): iteration = 0 if simulation: print("iteration",iteration,":",*arr) def is_sorted(arr): #check the array is inorder i = 0 arr_len = len(arr) while i+1 < arr_len: if arr[i] > arr[i+1]: return False i += 1 return True while not is_sorted(arr): random.shuffle(arr) if simulation: iteration = iteration + 1 print("iteration",iteration,":",*arr) return arr
[ "Bogo Sort\n Best Case Complexity: O(n)\n Worst Case Complexity: O(∞)\n Average Case Complexity: O(n(n-1)!)\n " ]
Please provide a description of the function:def insert(self, key): # 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.left.insert(key) elif key > self.node.val: self.node.right.insert(key) self.re_balance()
[ "\n Insert new key into node\n " ]
Please provide a description of the function:def update_heights(self, recursive=True): if self.node: if recursive: if self.node.left: self.node.left.update_heights() if self.node.right: self.node.right.update_heights() self.height = 1 + max(self.node.left.height, self.node.right.height) else: self.height = -1
[ "\n Update tree height\n " ]
Please provide a description of the function:def update_balances(self, recursive=True): if self.node: if recursive: if self.node.left: self.node.left.update_balances() if self.node.right: self.node.right.update_balances() self.balance = self.node.left.height - self.node.right.height else: self.balance = 0
[ "\n Calculate tree balance factor\n\n " ]
Please provide a description of the function: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_root.left.node = new_left_sub new_root.right.node = old_root
[ "\n Right rotation\n " ]
Please provide a description of the function: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_root.right.node = new_left_sub new_root.left.node = old_root
[ "\n Left rotation\n " ]
Please provide a description of the function:def in_order_traverse(self): 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()) return result
[ "\n In-order traversal of the tree\n " ]
Please provide a description of the function:def strobogrammatic_in_range(low, high): 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 int(perm) < int(low): continue elif len(perm) == high_len and int(perm) > int(high): continue else: count += 1 return count
[ "\n :type low: str\n :type high: str\n :rtype: int\n " ]
Please provide a description of the function:def find_keyboard_row(words): keyboard = [ set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm'), ] result = [] for word in words: for key in keyboard: if set(word.lower()).issubset(key): result.append(word) return result
[ "\n :type words: List[str]\n :rtype: List[str]\n " ]
Please provide a description of the function:def kth_to_last_eval(head, k): if not isinstance(k, int) or not head.val: return False nexts = '.'.join(['next' for n in range(1, k+1)]) seeker = str('.'.join(['head', nexts])) while head: if eval(seeker) is None: return head else: head = head.next return False
[ "\n This is a suboptimal, hacky method using eval(), which is not\n safe for user input. We guard against danger by ensuring k in an int\n " ]
Please provide a description of the function:def kth_to_last_dict(head, k): if not (head and k > -1): return False d = dict() count = 0 while head: d[count] = head head = head.next count += 1 return len(d)-k in d and d[len(d)-k]
[ "\n This is a brute force method where we keep a dict the size of the list\n Then we check it for the value we need. If the key is not in the dict,\n our and statement will short circuit and return False\n " ]
Please provide a description of the function: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): if p1 is None: # Went too far, k is not valid raise IndexError p1 = p1.next while p1: p1 = p1.next p2 = p2.next return p2
[ "\n This is an optimal method using iteration.\n We move p1 k steps ahead into the list.\n Then we move p1 and p2 together until p1 hits the end.\n " ]
Please provide a description of the function:def get_skyline(lrh): 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 < n and lrh[i][0] == x: heapq.heappush(live, (-lrh[i][2], -lrh[i][1])) i += 1 else: x = -live[0][1] while live and -live[0][1] <= x: heapq.heappop(live) height = len(live) and -live[0][0] if not skyline or height != skyline[-1][1]: skyline += [x, height], return skyline
[ "\n Wortst Time Complexity: O(NlogN)\n :type buildings: List[List[int]]\n :rtype: List[List[int]]\n " ]
Please provide a description of the function:def summarize_ranges(array): 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[i] != num: res.append((num, array[i])) else: res.append((num, num)) i += 1 return res
[ "\n :type array: List[int]\n :rtype: List[]\n " ]
Please provide a description of the function:def encode(strs): res = '' for string in strs.split(): res += str(len(string)) + ":" + string return res
[ "Encodes a list of strings to a single string.\n :type strs: List[str]\n :rtype: str\n " ]
Please provide a description of the function:def decode(s): 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.\n :type s: str\n :rtype: List[str]\n " ]
Please provide a description of the function:def multiply(multiplicand: list, multiplier: list) -> list: multiplicand_row, multiplicand_col = len( multiplicand), len(multiplicand[0]) multiplier_row, multiplier_col = len(multiplier), len(multiplier[0]) if(multiplicand_col != multiplier_row): raise Exception( "Multiplicand matrix not compatible with Multiplier matrix.") # create a result matrix result = [[0] * multiplier_col for i in range(multiplicand_row)] for i in range(multiplicand_row): for j in range(multiplier_col): for k in range(len(multiplier)): result[i][j] += multiplicand[i][k] * multiplier[k][j] return result
[ "\n :type A: List[List[int]]\n :type B: List[List[int]]\n :rtype: List[List[int]]\n " ]
Please provide a description of the function:def combination(n, r): if n == r or r == 0: return 1 else: return combination(n-1, r-1) + combination(n-1, r)
[ "This function calculates nCr." ]
Please provide a description of the function:def combination_memo(n, r): 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, r)
[ "This function calculates nCr using memoization method." ]
Please provide a description of the function:def is_anagram(s, t): 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
[ "\n :type s: str\n :type t: str\n :rtype: bool\n " ]
Please provide a description of the function: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 maximum number in arr index_max = arr.index(max(arr[0:cur])) if index_max+1 != cur: #Needs moving if index_max != 0: #reverse from 0 to index_max arr[:index_max+1] = reversed(arr[:index_max+1]) # Reverse list arr[:cur] = reversed(arr[:cur]) return arr
[ "\n Pancake_sort\n Sorting a given array\n mutation of selection sort\n\n reference: https://www.geeksforgeeks.org/pancake-sorting/\n \n Overall time complexity : O(N^2)\n " ]
Please provide a description of the function:def next(self): v=self.queue.pop(0) ret=v.pop(0) if v: self.queue.append(v) return ret
[ "\n :rtype: int\n " ]
Please provide a description of the function: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)): max_so_far = max(max_so_far, prices[j] - prices[i]) return max_so_far
[ "\n :type prices: List[int]\n :rtype: int\n " ]
Please provide a description of the function: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[i] - prices[i-1]) max_so_far = max(max_so_far, cur_max) return max_so_far
[ "\n input: [7, 1, 5, 3, 6, 4]\n diff : [X, -6, 4, -2, 3, -2]\n :type prices: List[int]\n :rtype: int\n " ]
Please provide a description of the function:def first_unique_char(s): 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
[ "\n :type s: str\n :rtype: int\n " ]
Please provide a description of the function:def kth_smallest(self, root, k): count = [] self.helper(root, count) return count[k-1]
[ "\n :type root: TreeNode\n :type k: int\n :rtype: int\n " ]
Please provide a description of the function:def int_to_roman(num): 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"]; return m[num//1000] + c[(num%1000)//100] + x[(num%100)//10] + i[num%10];
[ "\n :type num: int\n :rtype: str\n " ]
Please provide a description of the function: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'): print("---------") print("<path>:", s) depth = s.count('\t') # the depth of current dir or file print("depth: ", depth) print("stack: ", stack) print("curlen: ", curr_len) while len(stack) > depth: # go back to the correct depth curr_len -= stack.pop() stack.append(len(s.strip('\t'))+1) # 1 is the length of '/' curr_len += stack[-1] # increase current length print("stack: ", stack) print("curlen: ", curr_len) if '.' in s: # update maxlen only when it is a file max_len = max(max_len, curr_len-1) # -1 is to minus one '/' return max_len
[ "\n :type input: str\n :rtype: int\n " ]