instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Auto-generate documentation strings for this file
from __future__ import annotations def comb_sort(array: list[int]) -> list[int]: n = len(array) gap = n shrink_factor = 1.3 is_sorted = False while not is_sorted: gap = int(gap / shrink_factor) if gap <= 1: gap = 1 is_sorted = True i = 0 w...
--- +++ @@ -1,8 +1,33 @@+""" +Comb Sort + +Comb sort improves on bubble sort by using a gap sequence that shrinks by +a factor of approximately 1.3 on each pass, eliminating small values near +the end of the list (known as "turtles") more quickly. + +Reference: https://en.wikipedia.org/wiki/Comb_sort + +Complexity: + ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/comb_sort.py
Add minimal docstrings for each function
from __future__ import annotations def bucket_sort(array: list[int]) -> list[int]: num_buckets = len(array) buckets: list[list[int]] = [[] for _ in range(num_buckets)] max_value = max(array) + 1 for value in array: index = value * num_buckets // max_value buckets[index].append(value)...
--- +++ @@ -1,8 +1,33 @@+""" +Bucket Sort + +Bucket sort distributes elements into a number of buckets, sorts each +bucket individually (here using insertion sort), and then concatenates +all buckets. + +Reference: https://en.wikipedia.org/wiki/Bucket_sort + +Complexity: + Time: O(n + k) best / O(n + k) average / O...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/bucket_sort.py
Add docstrings to existing functions
from __future__ import annotations def cycle_sort(array: list[int]) -> list[int]: length = len(array) for start in range(length - 1): item = array[start] # Count how many elements are smaller to find the correct position position = start for i in range(start + 1, length): ...
--- +++ @@ -1,8 +1,33 @@+""" +Cycle Sort + +Cycle sort decomposes the permutation into cycles and rotates each cycle +to produce a sorted result. It minimises the number of writes to the +array, making it useful when writes are expensive. + +Reference: https://en.wikipedia.org/wiki/Cycle_sort + +Complexity: + Time:...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/cycle_sort.py
Annotate my code with docstrings
from __future__ import annotations def counting_sort(array: list[int]) -> list[int]: min_value = min(array) offset = -min_value if min_value < 0 else 0 shifted = [v + offset for v in array] max_value = max(shifted) counts = [0] * (max_value + 1) for value in shifted: counts[value] +...
--- +++ @@ -1,8 +1,33 @@+""" +Counting Sort + +Counting sort counts the occurrences of each value and uses cumulative +counts to place each element in its correct position. It supports +negative integers by shifting values internally. + +Reference: https://en.wikipedia.org/wiki/Counting_sort + +Complexity: + Time: ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/counting_sort.py
Add docstrings to improve collaboration
from __future__ import annotations def max_heap_sort(array: list[int]) -> list[int]: for i in range(len(array) - 1, 0, -1): _max_heapify(array, i) return array def _max_heapify(array: list[int], end: int) -> None: last_parent = (end - 1) // 2 for parent in range(last_parent, -1, -1): ...
--- +++ @@ -1,14 +1,40 @@+""" +Heap Sort + +Heap sort builds a heap from the data and repeatedly extracts the +extreme element to produce a sorted array. Two variants are provided: +max-heap sort and min-heap sort. + +Reference: https://en.wikipedia.org/wiki/Heapsort + +Complexity: + Time: O(n log n) best / O(n lo...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/heap_sort.py
Generate docstrings for this script
from __future__ import annotations def exchange_sort(array: list[int]) -> list[int]: n = len(array) for i in range(n - 1): for j in range(i + 1, n): if array[i] > array[j]: array[i], array[j] = array[j], array[i] return array
--- +++ @@ -1,11 +1,35 @@+""" +Exchange Sort + +Exchange sort compares every pair of elements and swaps them if they are +out of order. It is conceptually similar to bubble sort. + +Reference: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort + +Complexity: + Time: O(n^2) best / O(n^2) average / O(n^2)...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/exchange_sort.py
Provide clean and structured docstrings
from __future__ import annotations def gnome_sort(array: list[int]) -> list[int]: n = len(array) index = 0 while index < n: if index == 0 or array[index] >= array[index - 1]: index += 1 else: array[index], array[index - 1] = array[index - 1], array[index] ...
--- +++ @@ -1,8 +1,33 @@+""" +Gnome Sort + +Gnome sort moves an element toward the front of the list until it finds +an element that is smaller or equal, then steps forward again. It is +similar to insertion sort but uses swaps instead of shifts. + +Reference: https://en.wikipedia.org/wiki/Gnome_sort + +Complexity: + ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/gnome_sort.py
Write docstrings for data processing functions
from __future__ import annotations def insertion_sort(array: list[int]) -> list[int]: for i in range(len(array)): cursor = array[i] pos = i while pos > 0 and array[pos - 1] > cursor: array[pos] = array[pos - 1] pos -= 1 array[pos] = cursor return arra...
--- +++ @@ -1,8 +1,32 @@+""" +Insertion Sort + +Insertion sort builds the sorted list one element at a time by repeatedly +picking the next element and inserting it into its correct position. + +Reference: https://en.wikipedia.org/wiki/Insertion_sort + +Complexity: + Time: O(n) best / O(n^2) average / O(n^2) worst ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/insertion_sort.py
Write clean docstrings for readability
from __future__ import annotations def selection_sort(array: list[int]) -> list[int]: for i in range(len(array)): minimum = i for j in range(i + 1, len(array)): if array[j] < array[minimum]: minimum = j array[minimum], array[i] = array[i], array[minimum] re...
--- +++ @@ -1,12 +1,36 @@+""" +Selection Sort + +Selection sort repeatedly selects the smallest element from the unsorted +portion and moves it to the end of the sorted portion. + +Reference: https://en.wikipedia.org/wiki/Selection_sort + +Complexity: + Time: O(n^2) best / O(n^2) average / O(n^2) worst + Space: ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/selection_sort.py
Add missing documentation to my Python functions
from __future__ import annotations def merge_sort(array: list[int]) -> list[int]: if len(array) <= 1: return array mid = len(array) // 2 left = merge_sort(array[:mid]) right = merge_sort(array[mid:]) _merge(left, right, array) return array def _merge(left: list[int], right: list[i...
--- +++ @@ -1,8 +1,32 @@+""" +Merge Sort + +Merge sort divides the array in half, recursively sorts each half, and +then merges the two sorted halves back together. + +Reference: https://en.wikipedia.org/wiki/Merge_sort + +Complexity: + Time: O(n log n) best / O(n log n) average / O(n log n) worst + Space: O(n) ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/merge_sort.py
Add documentation for all methods
from __future__ import annotations def quick_sort(array: list[int]) -> list[int]: _quick_sort_recursive(array, 0, len(array) - 1) return array def _quick_sort_recursive(array: list[int], first: int, last: int) -> None: if first < last: pivot = _partition(array, first, last) _quick_sort_...
--- +++ @@ -1,13 +1,38 @@+""" +Quick Sort + +Quick sort selects a pivot element, partitions the array around the +pivot, and recursively sorts the two partitions. + +Reference: https://en.wikipedia.org/wiki/Quicksort + +Complexity: + Time: O(n log n) best / O(n log n) average / O(n^2) worst + Space: O(log n) +""...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/quick_sort.py
Add docstrings to meet PEP guidelines
from __future__ import annotations def pigeonhole_sort(array: list[int]) -> list[int]: max_value = max(array) min_value = min(array) size = max_value - min_value + 1 holes = [0] * size for value in array: holes[value - min_value] += 1 i = 0 for count in range(size): whil...
--- +++ @@ -1,8 +1,32 @@+""" +Pigeonhole Sort + +Pigeonhole sort is suitable for sorting lists where the number of +elements and the range of possible key values are approximately equal. + +Reference: https://en.wikipedia.org/wiki/Pigeonhole_sort + +Complexity: + Time: O(n + range) best / O(n + range) average / O(n...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/pigeonhole_sort.py
Add docstrings to make code maintainable
from __future__ import annotations def can_attend_meetings(intervals: list) -> 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
--- +++ @@ -1,10 +1,35 @@+""" +Meeting Rooms + +Given an array of meeting time intervals consisting of start and end times +[[s1, e1], [s2, e2], ...] (si < ei), determine if a person could attend +all meetings (i.e. no two meetings overlap). + +Reference: https://leetcode.com/problems/meeting-rooms/ + +Complexity: + ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/meeting_rooms.py
Generate docstrings for exported functions
from __future__ import annotations def pancake_sort(array: list[int]) -> list[int]: if len(array) <= 1: return array for cur in range(len(array), 1, -1): index_max = array.index(max(array[0:cur])) if index_max + 1 != cur: if index_max != 0: array[: index_m...
--- +++ @@ -1,8 +1,33 @@+""" +Pancake Sort + +Pancake sort sorts an array by repeatedly finding the maximum element in +the unsorted portion, flipping it to the front, and then flipping the +entire unsorted portion so the maximum lands at the end. + +Reference: https://en.wikipedia.org/wiki/Pancake_sorting + +Complexit...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/pancake_sort.py
Document functions with detailed explanations
from __future__ import annotations def sort_colors(array: list[int]) -> list[int]: red = white = 0 for k in range(len(array)): value = array[k] array[k] = 2 if value < 2: array[white] = 1 white += 1 if value == 0: array[red] = 0 ...
--- +++ @@ -1,8 +1,33 @@+""" +Sort Colors (Dutch National Flag) + +Given an array with n objects colored red, white, or blue (represented by +0, 1, and 2), sort them in-place so that objects of the same color are +adjacent, with the colors in order red, white, blue. + +Reference: https://leetcode.com/problems/sort-colo...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/sort_colors.py
Document functions with clear intent
from __future__ import annotations def shell_sort(array: list[int]) -> list[int]: n = len(array) gap = n // 2 while gap > 0: y_index = gap while y_index < n: y = array[y_index] x_index = y_index - gap while x_index >= 0 and y < array[x_index]: ...
--- +++ @@ -1,8 +1,34 @@+""" +Shell Sort + +Shell sort is a generalisation of insertion sort that allows the exchange +of elements that are far apart. The gap between compared elements is +gradually reduced until it becomes 1, at which point the algorithm +behaves like a standard insertion sort. + +Reference: https://...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/shell_sort.py
Add docstrings to make code maintainable
from __future__ import annotations def radix_sort(array: list[int]) -> list[int]: position = 1 max_number = max(array) while position <= max_number: buckets: list[list[int]] = [[] for _ in range(10)] for num in array: digit = num // position % 10 buckets[digit].a...
--- +++ @@ -1,8 +1,33 @@+""" +Radix Sort + +Radix sort processes digits from least significant to most significant, +distributing elements into buckets for each digit and collecting them +back in order. + +Reference: https://en.wikipedia.org/wiki/Radix_sort + +Complexity: + Time: O(n * k) best / O(n * k) average / ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/radix_sort.py
Generate docstrings with examples
from __future__ import annotations def stooge_sort(array: list[int]) -> list[int]: _stooge_sort(array, 0, len(array) - 1) return array def _stooge_sort(array: list[int], low: int, high: int) -> None: if low >= high: return if array[low] > array[high]: array[low], array[high] = arra...
--- +++ @@ -1,13 +1,39 @@+""" +Stooge Sort + +Stooge sort is a recursive sorting algorithm notable for its unusually +bad time complexity. It works by recursively sorting the first 2/3, then +the last 2/3, and then the first 2/3 again. + +Reference: https://en.wikipedia.org/wiki/Stooge_sort + +Complexity: + Time: ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/stooge_sort.py
Improve documentation using docstrings
from __future__ import annotations def wiggle_sort(array: list[int]) -> list[int]: for i in range(len(array)): if (i % 2 == 1) == (array[i - 1] > array[i]): array[i - 1], array[i] = array[i], array[i - 1] return array
--- +++ @@ -1,9 +1,33 @@+""" +Wiggle Sort + +Given an unsorted array, reorder it in-place such that +nums[0] < nums[1] > nums[2] < nums[3] ... + +Reference: https://leetcode.com/problems/wiggle-sort/ + +Complexity: + Time: O(n) best / O(n) average / O(n) worst + Space: O(1) +""" from __future__ import annotat...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/wiggle_sort.py
Create documentation for each function signature
from __future__ import annotations import collections def first_is_consecutive(stack: list[int]) -> bool: storage_stack: list[int] = [] for _ in range(len(stack)): first_value = stack.pop() if len(stack) == 0: return True second_value = stack.pop() if first_value ...
--- +++ @@ -1,3 +1,16 @@+""" +Is Consecutive + +Check whether a stack contains a sequence of consecutive integers +starting from the bottom. Two approaches are provided: one using an +auxiliary stack, and one using an auxiliary queue. + +Reference: https://en.wikipedia.org/wiki/Stack_(abstract_data_type) + +Complexity:...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/stack/is_consecutive.py
Document helper functions with docstrings
from __future__ import annotations def is_sorted(stack: list[int]) -> bool: storage_stack: list[int] = [] for _ in range(len(stack)): if len(stack) == 0: break first_val = stack.pop() if len(stack) == 0: break second_val = stack.pop() if first_v...
--- +++ @@ -1,8 +1,34 @@+""" +Is Sorted + +Check whether a stack is sorted in ascending order from bottom to top +using a single auxiliary stack. + +Reference: https://en.wikipedia.org/wiki/Stack_(abstract_data_type) + +Complexity: + Time: O(n) + Space: O(n) +""" from __future__ import annotations def is...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/stack/is_sorted.py
Create documentation strings for testing functions
from __future__ import annotations def remove_min(stack: list[int]) -> list[int]: storage_stack: list[int] = [] if len(stack) == 0: return stack minimum = stack.pop() stack.append(minimum) for _ in range(len(stack)): val = stack.pop() if val <= minimum: minimum...
--- +++ @@ -1,8 +1,32 @@+""" +Remove Min from Stack + +Remove the smallest value from a stack, preserving the relative order +of the remaining elements. + +Reference: https://en.wikipedia.org/wiki/Stack_(abstract_data_type) + +Complexity: + Time: O(n) + Space: O(n) +""" from __future__ import annotations ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/stack/remove_min.py
Add docstrings for better understanding
from __future__ import annotations def length_longest_path(input_str: str) -> int: current_length = 0 max_length = 0 stack: list[int] = [] for segment in input_str.split("\n"): depth = segment.count("\t") while len(stack) > depth: current_length -= stack.pop() name...
--- +++ @@ -1,8 +1,34 @@+""" +Longest Absolute File Path + +Given a string representing a file system in a special format, find the +length of the longest absolute path to a file. Directories and files +are separated by newlines; depth is indicated by tab characters. + +Reference: https://leetcode.com/problems/longest-...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/stack/longest_abs_path.py
Write clean docstrings for readability
from __future__ import annotations import collections def first_stutter(stack: list[int]) -> list[int]: storage_stack: list[int] = [] for _ in range(len(stack)): storage_stack.append(stack.pop()) for _ in range(len(storage_stack)): val = storage_stack.pop() stack.append(val) ...
--- +++ @@ -1,3 +1,15 @@+""" +Stutter + +Replace every value in a stack with two occurrences of that value. +Two approaches: one using an auxiliary stack, one using an auxiliary queue. + +Reference: https://en.wikipedia.org/wiki/Stack_(abstract_data_type) + +Complexity: + Time: O(n) + Space: O(n) +""" from __...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/stack/stutter.py
Add verbose docstrings with examples
from __future__ import annotations def simplify_path(path: str) -> str: skip = {"..", ".", ""} stack: list[str] = [] tokens = path.split("/") for token in tokens: if token == "..": if stack: stack.pop() elif token not in skip: stack.append(token...
--- +++ @@ -1,8 +1,34 @@+""" +Simplify Path + +Given an absolute Unix-style file path, simplify it by resolving '.' +(current directory), '..' (parent directory), and multiple slashes. + +Reference: https://leetcode.com/problems/simplify-path/ + +Complexity: + Time: O(n) + Space: O(n) +""" from __future__ imp...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/stack/simplify_path.py
Generate docstrings for script automation
from __future__ import annotations class Node: def __init__(self, x: int) -> None: self.val = x self.next: Node | None = None def add_two_numbers(left: Node, right: Node) -> Node: head = Node(0) current = head carry = 0 while left or right: carry //= 10 if left: ...
--- +++ @@ -1,3 +1,16 @@+""" +Add Two Numbers (Linked List) + +Given two non-empty linked lists representing two non-negative integers with +digits stored in reverse order, add the two numbers and return the sum as a +linked list. + +Reference: https://leetcode.com/problems/add-two-numbers/ + +Complexity: + Time: O...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/add_two_numbers.py
Generate consistent documentation across files
from __future__ import annotations def one_sparse(array: list[tuple[int, str]]) -> int | None: sum_signs = 0 bitsum: list[int] = [0] * 32 sum_values = 0 for val, sign in array: if sign == "+": sum_signs += 1 sum_values += val else: sum_signs -= 1 ...
--- +++ @@ -1,8 +1,35 @@+""" +Non-negative 1-Sparse Recovery + +Determines whether a dynamic stream of (value, sign) tuples is 1-sparse, +meaning all values cancel out except for a single unique number. If so, +returns that number; otherwise returns None. + +Reference: https://en.wikipedia.org/wiki/Sparse_recovery + +C...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/streaming/one_sparse_recovery.py
Generate docstrings for this script
from __future__ import annotations class OrderedStack: def __init__(self) -> None: self.items: list[int] = [] def is_empty(self) -> bool: return self.items == [] def _push_direct(self, item: int) -> None: self.items.append(item) def push(self, item: int) -> None: t...
--- +++ @@ -1,19 +1,58 @@+""" +Ordered Stack + +A stack that maintains elements in sorted order, with the highest value +at the top and the lowest at the bottom. Push operations preserve the +ordering invariant. + +Reference: https://en.wikipedia.org/wiki/Stack_(abstract_data_type) + +Complexity: + Time: O(n) for p...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/stack/ordered_stack.py
Document helper functions with docstrings
from __future__ import annotations def encode(strs: str) -> str: result = "" for word in strs.split(): result += str(len(word)) + ":" + word return result def decode(text: str) -> list[str]: words: list[str] = [] index = 0 while index < len(text): colon_index = text.find(":"...
--- +++ @@ -1,8 +1,32 @@+""" +Encode and Decode Strings + +Design an algorithm to encode a list of strings to a single string, and +decode it back to the original list of strings. + +Reference: https://leetcode.com/problems/encode-and-decode-strings/ + +Complexity: + Time: O(n) for both encode and decode + Space...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/encode_decode.py
Add professional docstrings to my codebase
from __future__ import annotations def contain_string(haystack: str, needle: str) -> int: if len(needle) == 0: return 0 if len(needle) > len(haystack): return -1 for index in range(len(haystack)): if len(haystack) - index < len(needle): return -1 if haystack[in...
--- +++ @@ -1,8 +1,33 @@+""" +Contain String (strStr) + +Return the index of the first occurrence of needle in haystack, or -1 if +needle is not part of haystack. + +Reference: https://leetcode.com/problems/implement-strstr/ + +Complexity: + Time: O(n * m) worst case, where n = len(haystack), m = len(needle) + S...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/contain_string.py
Add clean documentation to messy code
from __future__ import annotations def delete_reoccurring_characters(string: str) -> str: seen_characters: set[str] = set() output_string = "" for char in string: if char not in seen_characters: seen_characters.add(char) output_string += char return output_string
--- +++ @@ -1,12 +1,36 @@+""" +Delete Reoccurring Characters + +Given a string, delete any reoccurring characters and return the new string +containing only the first occurrence of each character. + +Reference: https://en.wikipedia.org/wiki/Duplicate_removal + +Complexity: + Time: O(n) where n is the length of the ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/delete_reoccurring.py
Write clean docstrings for readability
from __future__ import annotations def judge_circle(moves: str) -> bool: move_counts = { "U": 0, "D": 0, "R": 0, "L": 0, } for char in moves: move_counts[char] = move_counts[char] + 1 return move_counts["L"] == move_counts["R"] and move_counts["U"] == move_coun...
--- +++ @@ -1,8 +1,32 @@+""" +Judge Route Circle + +Given a sequence of robot moves (R, L, U, D), determine whether the robot +returns to its starting position after completing all moves. + +Reference: https://leetcode.com/problems/robot-return-to-origin/ + +Complexity: + Time: O(n) where n is the number of moves +...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/judge_circle.py
Add verbose docstrings with examples
from __future__ import annotations def decode_string(text: str) -> str: stack: list[tuple[str, int]] = [] current_num = 0 current_string = "" for char in text: if char == "[": stack.append((current_string, current_num)) current_string = "" current_num = 0 ...
--- +++ @@ -1,8 +1,33 @@+""" +Decode String + +Given an encoded string, return its decoded string. The encoding rule is +k[encoded_string], where the encoded_string inside the brackets is repeated +exactly k times. + +Reference: https://leetcode.com/problems/decode-string/ + +Complexity: + Time: O(n * max_k) where ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/decode_string.py
Write docstrings for utility functions
from __future__ import annotations def count_binary_substring(text: str) -> int: current = 1 previous = 0 count = 0 for index in range(1, len(text)): if text[index] != text[index - 1]: count = count + min(previous, current) previous = current current = 1 ...
--- +++ @@ -1,8 +1,32 @@+""" +Count Binary Substrings + +Count the number of non-empty contiguous substrings that have the same number +of 0s and 1s, where all 0s and all 1s are grouped consecutively. + +Reference: https://leetcode.com/problems/count-binary-substrings/ + +Complexity: + Time: O(n) where n is the len...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/count_binary_substring.py
Generate descriptive docstrings automatically
from __future__ import annotations import re from functools import reduce def match_symbol(words: list[str], symbols: list[str]) -> list[str]: combined = [] for symbol in symbols: for word in words: match = re.search(symbol, word) if match: combined.append(re....
--- +++ @@ -1,3 +1,16 @@+""" +Breaking Bad Symbol Matching + +Given an array of words and an array of symbols, display each word with its +matched symbol surrounded by square brackets. If a word matches more than one +symbol, choose the one with the longest length. + +Reference: https://en.wikipedia.org/wiki/Trie + +Co...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/breaking_bad.py
Write docstrings describing each step
from __future__ import annotations from collections import deque from string import ascii_letters def is_palindrome(text: str) -> bool: left = 0 right = len(text) - 1 while left < right: while not text[left].isalnum(): left += 1 while not text[right].isalnum(): ri...
--- +++ @@ -1,3 +1,15 @@+""" +Is Palindrome + +Determine if a string is a palindrome, considering only alphanumeric +characters and ignoring cases. Multiple approaches are provided. + +Reference: https://en.wikipedia.org/wiki/Palindrome + +Complexity: + Time: O(n) for all variations + Space: O(n) for variations ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/is_palindrome.py
Add verbose docstrings with examples
from __future__ import annotations def is_rotated(first: str, second: str) -> bool: if len(first) == len(second): return second in first + first else: return False def is_rotated_v1(first: str, second: str) -> bool: if len(first) != len(second): return False if len(first) ==...
--- +++ @@ -1,8 +1,33 @@+""" +Is Rotated String + +Given two strings, determine if the second is a rotated version of the first. +Two approaches are provided: concatenation check and brute force. + +Reference: https://leetcode.com/problems/rotate-string/ + +Complexity: + Time: O(n) for concatenation approach, O(n^2...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/is_rotated.py
Add docstrings that explain logic
from __future__ import annotations def _common_prefix(first: str, second: str) -> str: if not first or not second: return "" index = 0 while first[index] == second[index]: index = index + 1 if index >= len(first) or index >= len(second): return first[0:index] retur...
--- +++ @@ -1,8 +1,29 @@+""" +Longest Common Prefix + +Find the longest common prefix string amongst an array of strings. +Three approaches: horizontal scanning, vertical scanning, and divide and conquer. + +Reference: https://leetcode.com/problems/longest-common-prefix/ + +Complexity: + Time: O(S) where S is the s...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/longest_common_prefix.py
Improve documentation using docstrings
from __future__ import annotations from collections.abc import Sequence def knuth_morris_pratt(text: Sequence, pattern: Sequence) -> list[int]: text_length = len(text) pattern_length = len(pattern) prefix_table = [0 for _ in range(pattern_length)] match_length = 0 for index in range(1, pattern_...
--- +++ @@ -1,3 +1,15 @@+""" +Knuth-Morris-Pratt String Search + +Given two sequences (text and pattern), return the list of start indexes in +text that match the pattern using the KMP algorithm. + +Reference: https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm + +Complexity: + Time: O(n + m)...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/knuth_morris_pratt.py
Can you add docstrings to this Python file?
from __future__ import annotations count = 0 def make_sentence(text_piece: str, dictionaries: list[str]) -> bool: global count if len(text_piece) == 0: return True for index in range(0, len(text_piece)): prefix, suffix = text_piece[0:index], text_piece[index:] if (prefix in dicti...
--- +++ @@ -1,3 +1,15 @@+""" +Make Sentence + +For a given string and dictionary, count how many sentences can be formed +from the string such that all words are contained in the dictionary. + +Reference: https://en.wikipedia.org/wiki/Word_break_problem + +Complexity: + Time: O(2^n) worst case due to recursive expl...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/make_sentence.py
Add concise docstrings to each method
from __future__ import annotations def license_number(key: str, group_size: int) -> str: result: list[str] = [] alphanumeric: list[str] = [] for char in key: if char != "-": alphanumeric.append(char) for index, char in enumerate(reversed(alphanumeric)): result.append(char)...
--- +++ @@ -1,8 +1,33 @@+""" +License Key Formatting + +Given a license key string and a group size k, reformat the key so that each +group contains exactly k characters, separated by dashes. + +Reference: https://leetcode.com/problems/license-key-formatting/ + +Complexity: + Time: O(n) where n is the length of the...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/license_number.py
Add docstrings to improve code quality
from __future__ import annotations def longest_palindrome(text: str) -> str: if len(text) < 2: return text expanded = "#" + "#".join(text) + "#" palindrome_radii = [0] * len(expanded) center, right_boundary = 0, 0 best_index, best_length = 0, 0 for index in range(len(expanded)): ...
--- +++ @@ -1,8 +1,32 @@+""" +Longest Palindromic Substring + +Given a string, find the longest palindromic substring using Manacher's +algorithm, which runs in linear time. + +Reference: https://en.wikipedia.org/wiki/Longest_palindromic_substring + +Complexity: + Time: O(n) using Manacher's algorithm + Space: O...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/longest_palindromic_substring.py
Document functions with detailed explanations
from __future__ import annotations class RollingHash: def __init__(self, text: str, window_size: int) -> None: self.text = text self.hash = 0 self.window_size = window_size for index in range(0, window_size): self.hash += (ord(self.text[index]) - ord("a") + 1) * ( ...
--- +++ @@ -1,8 +1,26 @@+""" +Rabin-Karp String Search + +A string searching algorithm that uses hashing to find a pattern in text. +Uses a rolling hash to efficiently compare the pattern hash with substrings. + +Reference: https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm + +Complexity: + Time: O(n + m) a...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/rabin_karp.py
Generate docstrings for script automation
from __future__ import annotations def is_merge_recursive(text: str, part1: str, part2: str) -> bool: if not part1: return text == part2 if not part2: return text == part1 if not text: return part1 + part2 == "" if text[0] == part1[0] and is_merge_recursive(text[1:], part1[1:]...
--- +++ @@ -1,8 +1,34 @@+""" +Merge String Checker + +Determine if a given string can be formed by interleaving two other strings, +preserving the character order from each part. + +Reference: https://leetcode.com/problems/interleaving-string/ + +Complexity: + Time: O(2^n) worst case for recursive, similar for iter...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/merge_string_checker.py
Turn comments into proper docstrings
from __future__ import annotations def is_one_edit(source: str, target: str) -> bool: if len(source) > len(target): return is_one_edit(target, source) if len(target) - len(source) > 1 or target == source: return False for index in range(len(source)): if source[index] != target[ind...
--- +++ @@ -1,8 +1,33 @@+""" +One Edit Distance + +Given two strings, determine if they are exactly one edit distance apart. +An edit is an insertion, deletion, or replacement of a single character. + +Reference: https://leetcode.com/problems/one-edit-distance/ + +Complexity: + Time: O(n) where n is the length of t...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/one_edit_distance.py
Add docstrings that explain inputs and outputs
from __future__ import annotations def repeat_string(base: str, target: str) -> int: repetition_count = 1 repeated = base max_count = (len(target) / len(base)) + 1 while target not in repeated: repeated = repeated + base if repetition_count > max_count: repetition_count = ...
--- +++ @@ -1,8 +1,33 @@+""" +Repeated String Match + +Given two strings A and B, find the minimum number of times A has to be +repeated such that B is a substring of the result. Return -1 if impossible. + +Reference: https://leetcode.com/problems/repeated-string-match/ + +Complexity: + Time: O(n * m) where n = len...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/repeat_string.py
Create docstrings for all classes and functions
from __future__ import annotations from collections import deque from typing import Any def dfs_traverse(graph: dict[Any, list[Any]], start: Any) -> set[Any]: visited: set[Any] = set() stack = [start] while stack: node = stack.pop() if node not in visited: visited.add(node) ...
--- +++ @@ -1,3 +1,13 @@+""" +Graph Traversal Algorithms + +Provides DFS and BFS traversal of a graph represented as an adjacency +dictionary. + +Complexity: + Time: O(V + E) + Space: O(V) +""" from __future__ import annotations @@ -6,6 +16,19 @@ def dfs_traverse(graph: dict[Any, list[Any]], start: Any)...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/traversal.py
Add docstrings to make code maintainable
from __future__ import annotations def roman_to_int(text: str) -> int: number = 0 roman_values = { "M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1, } for index in range(len(text) - 1): if roman_values[text[index]] < roman...
--- +++ @@ -1,8 +1,32 @@+""" +Roman Numeral to Integer + +Given a Roman numeral string, convert it to an integer. Input is guaranteed +to be within the range from 1 to 3999. + +Reference: https://en.wikipedia.org/wiki/Roman_numerals + +Complexity: + Time: O(n) where n is the length of the Roman numeral string + ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/roman_to_int.py
Add docstrings to improve readability
def manacher(s: str) -> str: # Transform "abc" -> "^#a#b#c#$" so every palindrome has odd length t = "^#" + "#".join(s) + "#$" n = len(t) p = [0] * n # p[i] = radius of palindrome centred at i centre = right = 0 for i in range(1, n - 1): mirror = 2 * centre - i if i < right: ...
--- +++ @@ -1,6 +1,15 @@+"""Manacher's algorithm — find the longest palindromic substring in O(n). + +Manacher's algorithm uses the symmetry of palindromes to avoid redundant +comparisons, achieving linear time. It transforms the input to handle +both odd- and even-length palindromes uniformly. + +Inspired by PR #931 (...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/manacher.py
Document this module using docstrings
from __future__ import annotations from algorithms.tree.tree import TreeNode def bin_tree_to_list(root: TreeNode | None) -> TreeNode | None: if not root: return root root = _bin_tree_to_list_util(root) while root.left: root = root.left return root def _bin_tree_to_list_util(root: T...
--- +++ @@ -1,3 +1,15 @@+""" +Binary Tree to Doubly Linked List + +Converts a binary tree to a sorted doubly linked list in-place by +rearranging the left and right pointers of each node. + +Reference: https://en.wikipedia.org/wiki/Binary_tree + +Complexity: + Time: O(n) + Space: O(n) due to recursion stack +"""...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/bin_tree_to_list.py
Include argument descriptions in docstrings
from __future__ import annotations from string import ascii_lowercase def panagram(string: str) -> bool: letters = set(ascii_lowercase) for char in string: letters.discard(char.lower()) return len(letters) == 0
--- +++ @@ -1,3 +1,15 @@+""" +Panagram Checker + +Check whether a given string is a panagram (a sentence using every letter +of the English alphabet at least once). + +Reference: https://en.wikipedia.org/wiki/Pangram + +Complexity: + Time: O(n) where n is the length of the string + Space: O(1) since the letter s...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/panagram.py
Add detailed documentation for each class
from __future__ import annotations def rotate(text: str, positions: int) -> str: long_string = text * (positions // len(text) + 2) if positions <= len(text): return long_string[positions : positions + len(text)] else: return long_string[positions - len(text) : positions] def rotate_alt(...
--- +++ @@ -1,8 +1,33 @@+""" +Rotate String + +Given a string and an integer k, return the string rotated by k positions +to the left. Two approaches are provided. + +Reference: https://en.wikipedia.org/wiki/Circular_shift + +Complexity: + Time: O(n) where n is the length of the string + Space: O(n) +""" from...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/rotate.py
Document functions with clear intent
from __future__ import annotations def min_distance(word1: str, word2: str) -> int: return len(word1) + len(word2) - 2 * _lcs(word1, word2, len(word1), len(word2)) def _lcs(word1: str, word2: str, length1: int, length2: int) -> int: if length1 == 0 or length2 == 0: return 0 if word1[length1 - 1...
--- +++ @@ -1,12 +1,48 @@+""" +Minimum Edit Distance (Delete Operation) + +Given two words, find the minimum number of steps required to make them the +same, where each step deletes one character from either string. + +Reference: https://leetcode.com/problems/delete-operation-for-two-strings/ + +Complexity: + Time: ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/min_distance.py
Document this code for team use
from __future__ import annotations class Node: def __init__(self, x: object) -> None: self.val = x self.next: Node | None = None def first_cyclic_node(head: Node | None) -> Node | None: runner = walker = head while runner and runner.next: runner = runner.next.next walker...
--- +++ @@ -1,3 +1,15 @@+""" +First Cyclic Node + +Given a linked list, find the first node of a cycle in it using Floyd's +cycle-finding algorithm (Tortoise and Hare). + +Reference: https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare + +Complexity: + Time: O(n) + Space: O(1) +""" from __f...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/first_cyclic_node.py
Improve documentation using docstrings
from __future__ import annotations _MORSE_CODE = { "a": ".-", "b": "-...", "c": "-.-.", "d": "-..", "e": ".", "f": "..-.", "g": "--.", "h": "....", "i": "..", "j": ".---", "k": "-.-", "l": ".-..", "m": "--", "n": "-.", "o": "---", "p": ".--.", "q": "...
--- +++ @@ -1,3 +1,15 @@+""" +Unique Morse Code Representations + +Given a list of words, determine the number of unique Morse code +transformations among all the words. + +Reference: https://leetcode.com/problems/unique-morse-code-words/ + +Complexity: + Time: O(n * k) where n is the number of words, k is average ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/unique_morse.py
Generate docstrings with parameter types
from __future__ import annotations from algorithms.tree.tree import TreeNode def binary_tree_paths(root: TreeNode | None) -> list[str]: result: list[str] = [] if root is None: return result _dfs(result, root, str(root.val)) return result def _dfs(result: list[str], root: TreeNode, current:...
--- +++ @@ -1,3 +1,15 @@+""" +Binary Tree Paths + +Given a binary tree, return all root-to-leaf paths as a list of strings +in the format "root->...->leaf". + +Reference: https://en.wikipedia.org/wiki/Binary_tree#Combinatorics + +Complexity: + Time: O(n) + Space: O(n) +""" from __future__ import annotations ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/binary_tree_paths.py
Document helper functions with docstrings
from __future__ import annotations def reverse_vowel(text: str) -> str: vowels = "AEIOUaeiou" left, right = 0, len(text) - 1 characters = list(text) while left < right: while left < right and characters[left] not in vowels: left += 1 while left < right and characters[right...
--- +++ @@ -1,8 +1,32 @@+""" +Reverse Vowels of a String + +Given a string, reverse only the vowels while keeping all other characters +in their original positions. + +Reference: https://leetcode.com/problems/reverse-vowels-of-a-string/ + +Complexity: + Time: O(n) where n is the length of the string + Space: O(n...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/reverse_vowel.py
Improve documentation using docstrings
def is_bst(root): 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 = root root = root.right return True
--- +++ @@ -1,6 +1,31 @@+""" +Given a binary tree, determine if it is a valid binary search tree (BST). + +Assume a BST is defined as follows: + +The left subtree of a node contains only nodes +with keys less than the node's key. +The right subtree of a node contains only nodes +with keys greater than the node's key. +...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/bst_is_bst.py
Add docstrings for internal functions
from __future__ import annotations def recursive(text: str) -> str: length = len(text) if length < 2: return text return recursive(text[length // 2 :]) + recursive(text[: length // 2]) def iterative(text: str) -> str: characters = list(text) left, right = 0, len(text) - 1 while left...
--- +++ @@ -1,8 +1,32 @@+""" +Reverse String + +Reverse a string using four different approaches: recursive, iterative, +pythonic (using reversed), and ultra-pythonic (using slicing). + +Reference: https://en.wikipedia.org/wiki/String_(computer_science)#Reversal + +Complexity: + Time: O(n) for all approaches + S...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/reverse_string.py
Generate docstrings with parameter types
from __future__ import annotations def compute_z_array(s: str) -> list[int]: n = len(s) if n == 0: return [] z = [0] * n z[0] = n left = right = 0 for i in range(1, n): if i < right: z[i] = min(right - i, z[i - left]) while i + z[i] < n and s[z[i]] == s[i +...
--- +++ @@ -1,8 +1,18 @@+"""Z-algorithm — linear-time pattern matching via the Z-array. + +The Z-array for a string S stores at Z[i] the length of the longest +substring starting at S[i] that is also a prefix of S. By concatenating +pattern + '$' + text, occurrences of the pattern correspond to positions +where Z[i] ==...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/z_algorithm.py
Document all public functions with docstrings
class Solution: 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: ...
--- +++ @@ -1,7 +1,52 @@+""" +Given a root node reference of a BST and a key, delete the node +with the given key in the BST. Return the root node reference +(possibly updated) of the BST. + +Basically, the deletion can be divided into two stages: + +Search for a node to remove. +If the node is found, delete the node. ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/bst_delete_node.py
Add docstrings for production code
from __future__ import annotations from algorithms.tree.tree import TreeNode def reverse(root: TreeNode | None) -> None: if root is None: return root.left, root.right = root.right, root.left if root.left: reverse(root.left) if root.right: reverse(root.right)
--- +++ @@ -1,3 +1,14 @@+""" +Invert Binary Tree + +Inverts a binary tree by swapping the left and right children of every node. + +Reference: https://en.wikipedia.org/wiki/Binary_tree + +Complexity: + Time: O(n) + Space: O(n) due to recursion stack +""" from __future__ import annotations @@ -5,10 +16,18 @@...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/invert_tree.py
Create simple docstrings for beginners
from __future__ import annotations from algorithms.common.tree_node import TreeNode pre_index = 0 def construct_tree_util( pre: list[int], post: list[int], low: int, high: int, size: int ) -> TreeNode | None: global pre_index if pre_index == -1: pre_index = 0 if pre_index >= size or low >...
--- +++ @@ -1,3 +1,16 @@+""" +Construct Tree from Preorder and Postorder Traversal + +Given preorder and postorder traversals of a full binary tree, construct the +tree and return its inorder traversal. A full binary tree has either zero or +two children per node. + +Reference: https://en.wikipedia.org/wiki/Binary_tree...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/construct_tree_postorder_preorder.py
Write docstrings for data processing functions
from __future__ import annotations from algorithms.tree.tree import TreeNode def is_balanced(root: TreeNode | None) -> bool: return _get_depth(root) != -1 def _get_depth(root: TreeNode | None) -> int: if root is None: return 0 left = _get_depth(root.left) right = _get_depth(root.right) ...
--- +++ @@ -1,3 +1,15 @@+""" +Balanced Binary Tree + +Determines whether a binary tree is height-balanced, meaning the depth of the +left and right subtrees of every node differ by at most one. + +Reference: https://en.wikipedia.org/wiki/AVL_tree + +Complexity: + Time: O(n) + Space: O(n) due to recursion stack +...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/is_balanced.py
Improve my code by adding docstrings
from __future__ import annotations from algorithms.tree.tree import TreeNode class DeepestLeft: def __init__(self) -> None: self.depth: int = 0 self.Node: TreeNode | None = None def find_deepest_left( root: TreeNode | None, is_left: bool, depth: int, res: DeepestLeft ) -> None: if not...
--- +++ @@ -1,3 +1,15 @@+""" +Deepest Left Leaf + +Given a binary tree, find the deepest node that is the left child of its +parent node. + +Reference: https://en.wikipedia.org/wiki/Binary_tree + +Complexity: + Time: O(n) + Space: O(n) due to recursion stack +""" from __future__ import annotations @@ -5,6 +...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/deepest_left.py
Generate docstrings with parameter types
from __future__ import annotations import collections from algorithms.tree.tree import TreeNode def is_subtree(big: TreeNode, small: TreeNode) -> bool: flag = False queue: collections.deque[TreeNode] = collections.deque() queue.append(big) while queue: node = queue.popleft() if node...
--- +++ @@ -1,3 +1,15 @@+""" +Subtree Check + +Given two binary trees s and t, check whether t is a subtree of s. A subtree +of s is a tree consisting of a node in s and all of its descendants. + +Reference: https://en.wikipedia.org/wiki/Binary_tree + +Complexity: + Time: O(m * n) where m and n are sizes of the two...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/is_subtree.py
Document my Python code with docstrings
from __future__ import annotations from algorithms.tree.tree import TreeNode def max_path_sum(root: TreeNode | None) -> float: maximum = float("-inf") _helper(root, maximum) return maximum def _helper(root: TreeNode | None, maximum: float) -> float: if root is None: return 0 left = _he...
--- +++ @@ -1,3 +1,16 @@+""" +Binary Tree Maximum Path Sum + +Given a binary tree, find the maximum path sum. A path is any sequence of nodes +from some starting node to any node in the tree along parent-child connections. +The path must contain at least one node. + +Reference: https://en.wikipedia.org/wiki/Binary_tree...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/max_path_sum.py
Create docstrings for API functions
from __future__ import annotations from collections import defaultdict class RandomListNode: def __init__(self, label: int) -> None: self.label = label self.next: RandomListNode | None = None self.random: RandomListNode | None = None def copy_random_pointer_v1(head: RandomListNode | N...
--- +++ @@ -1,3 +1,15 @@+""" +Copy List with Random Pointer + +Given a linked list where each node contains an additional random pointer that +could point to any node in the list or null, return a deep copy of the list. + +Reference: https://leetcode.com/problems/copy-list-with-random-pointer/ + +Complexity: + Time:...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/copy_random_pointer.py
Generate docstrings for exported functions
from __future__ import annotations from algorithms.tree.tree import TreeNode def min_depth(self: object, root: TreeNode | None) -> int: 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...
--- +++ @@ -1,3 +1,15 @@+""" +Minimum Depth of Binary Tree + +Given a binary tree, find its minimum depth. The minimum depth is the number +of nodes along the shortest path from the root down to the nearest leaf. + +Reference: https://en.wikipedia.org/wiki/Binary_tree + +Complexity: + Time: O(n) + Space: O(n) +"...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/min_height.py
Generate helpful docstrings for debugging
from __future__ import annotations from algorithms.tree.tree import TreeNode def is_same_tree(tree_p: TreeNode | None, tree_q: TreeNode | None) -> bool: if tree_p is None and tree_q is None: return True if tree_p is not None and tree_q is not None and tree_p.val == tree_q.val: return is_same...
--- +++ @@ -1,3 +1,15 @@+""" +Same Tree + +Given two binary trees, check if they are structurally identical and the +nodes have the same values. + +Reference: https://en.wikipedia.org/wiki/Binary_tree + +Complexity: + Time: O(min(n, m)) where n and m are sizes of the trees + Space: O(min(h1, h2)) where h1 and h2...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/same_tree.py
Add docstrings to improve code quality
import getpass import math import os from dataclasses import dataclass from pathlib import Path import requests import torch from einops import rearrange from huggingface_hub import hf_hub_download, login from imwatermark import WatermarkEncoder from PIL import ExifTags, Image from safetensors.torch import load_file a...
--- +++ @@ -62,6 +62,7 @@ def get_checkpoint_path(repo_id: str, filename: str, env_var: str) -> Path: + """Get the local path for a checkpoint file, downloading if necessary.""" if os.environ.get(env_var) is not None: local_path = os.environ[env_var] if os.path.exists(local_path): @@ -105,...
https://raw.githubusercontent.com/black-forest-labs/flux/HEAD/src/flux/util.py
Create docstrings for API functions
from __future__ import annotations class Node: def __init__(self, val: object = None) -> None: self.val = val self.next: Node | None = None def kth_to_last_eval(head: Node, k: int) -> Node | bool: if not isinstance(k, int) or not head.val: return False while head: seeke...
--- +++ @@ -1,3 +1,15 @@+""" +Kth to Last Element + +Find the kth to last element of a singly linked list. Three approaches are +provided: eval-based, dictionary-based, and two-pointer iterative. + +Reference: https://en.wikipedia.org/wiki/Linked_list + +Complexity (two-pointer): + Time: O(n) + Space: O(1) +""" ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/kth_to_last.py
Write docstrings for data processing functions
from typing import Any, Callable, Dict, Optional, Tuple, Type, Union from langchain.agents import Tool as LCTool from pydantic import BaseModel from kotaemon.base import BaseComponent class ToolException(Exception): class BaseTool(BaseComponent): name: str """The unique name of the tool that clearly commu...
--- +++ @@ -7,6 +7,13 @@ class ToolException(Exception): + """An optional exception that tool throws when execution error occurs. + + When this exception is thrown, the agent will not stop working, + but will handle the exception according to the handle_tool_error + variable of the tool, and the process...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/agents/tools/base.py
Add docstrings to meet PEP guidelines
import logging import re from functools import partial from typing import Optional import tiktoken from kotaemon.agents.base import BaseAgent, BaseLLM from kotaemon.agents.io import AgentAction, AgentFinish, AgentOutput, AgentType from kotaemon.agents.tools import BaseTool from kotaemon.base import Document, Param fr...
--- +++ @@ -16,6 +16,10 @@ class ReactAgent(BaseAgent): + """ + Sequential ReactAgent class inherited from BaseAgent. + Implementing ReAct agent paradigm https://arxiv.org/pdf/2210.03629.pdf + """ name: str = "ReactAgent" agent_type: AgentType = AgentType.react @@ -42,6 +46,13 @@ trim_fu...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/agents/react/agent.py
Write docstrings describing functionality
import logging import re from concurrent.futures import ThreadPoolExecutor from functools import partial from typing import Any import tiktoken from kotaemon.agents.base import BaseAgent from kotaemon.agents.io import AgentOutput, AgentType, BaseScratchPad from kotaemon.agents.tools import BaseTool from kotaemon.agen...
--- +++ @@ -20,6 +20,8 @@ class RewooAgent(BaseAgent): + """Distributive RewooAgent class inherited from BaseAgent. + Implementing ReWOO paradigm https://arxiv.org/pdf/2305.18323.pdf""" name: str = "RewooAgent" agent_type: AgentType = AgentType.rewoo @@ -64,6 +66,24 @@ def _parse_plan_map( ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/agents/rewoo/agent.py
Create docstrings for reusable components
import asyncio import json import logging import shlex from typing import Any, Optional, Type from pydantic import BaseModel, Field, create_model from .base import BaseTool logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # JSON Schema → Pydantic h...
--- +++ @@ -1,315 +1,380 @@- -import asyncio -import json -import logging -import shlex -from typing import Any, Optional, Type - -from pydantic import BaseModel, Field, create_model - -from .base import BaseTool - -logger = logging.getLogger(__name__) - - -# ------------------------------------------------------------...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/agents/tools/mcp.py
Write beginner-friendly docstrings
from typing import Any, AnyStr, Optional, Type, Union from pydantic import BaseModel, Field from kotaemon.base import Document from .base import BaseTool class Wiki: def __init__(self) -> None: try: import wikipedia # noqa: F401 except ImportError: raise ValueError( ...
--- +++ @@ -8,8 +8,10 @@ class Wiki: + """Wrapper around wikipedia API.""" def __init__(self) -> None: + """Check that wikipedia package is installed.""" try: import wikipedia # noqa: F401 except ImportError: @@ -19,6 +21,11 @@ ) def search(self, s...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/agents/tools/wikipedia.py
Add return value explanations in docstrings
from __future__ import annotations from typing import TYPE_CHECKING, Any, Literal, Optional, TypeVar from langchain.schema.messages import AIMessage as LCAIMessage from langchain.schema.messages import HumanMessage as LCHumanMessage from langchain.schema.messages import SystemMessage as LCSystemMessage from llama_ind...
--- +++ @@ -19,6 +19,22 @@ class Document(BaseDocument): + """ + Base document class, mostly inherited from Document class from llama-index. + + This class accept one positional argument `content` of an arbitrary type, which will + store the raw content of the document. If specified, the class will ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/base/schema.py
Annotate my code with docstrings
from kotaemon.base import Document def get_plugin_response_content(output) -> str: if isinstance(output, Document): return output.text else: return str(output) def calculate_cost(model_name: str, prompt_token: int, completion_token: int) -> float: # TODO: to be implemented return 0.0
--- +++ @@ -2,6 +2,9 @@ def get_plugin_response_content(output) -> str: + """ + Wrapper for AgentOutput content return + """ if isinstance(output, Document): return output.text else: @@ -9,5 +12,11 @@ def calculate_cost(model_name: str, prompt_token: int, completion_token: int) -> fl...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/agents/utils.py
Add verbose docstrings with examples
from abc import abstractmethod from typing import List, Optional from theflow import SessionFunction from kotaemon.base import BaseComponent, LLMInterface from kotaemon.base.schema import AIMessage, BaseMessage, HumanMessage, SystemMessage class BaseChatBot(BaseComponent): @abstractmethod def run(self, mess...
--- +++ @@ -14,10 +14,17 @@ def session_chat_storage(obj): + """Store using the bot location rather than the session location""" return obj._store_result class ChatConversation(SessionFunction): + """Base implementation of a chat bot component + + A chatbot component should: + - handle int...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/chatbot/base.py
Generate helpful docstrings for debugging
import os import click import yaml from trogon import tui # check if the output is not a .yml file -> raise error def check_config_format(config): if os.path.exists(config): if isinstance(config, str): with open(config) as f: yaml.safe_load(f) else: raise V...
--- +++ @@ -33,6 +33,7 @@ @click.argument("export_path", nargs=1) @click.option("--output", default="promptui.yml", show_default=True, required=False) def export(export_path, output): + """Export a pipeline to a config file""" import sys from theflow.utils.modules import import_dotted_string @@ -78,6 +...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/cli.py
Add docstrings that explain purpose and usage
import inspect from pathlib import Path from typing import Any, Dict, Optional, Type, Union import yaml from kotaemon.base import BaseComponent from kotaemon.chatbot import BaseChatBot from .base import DEFAULT_COMPONENT_BY_TYPES def config_from_value(value: Any) -> dict: component = DEFAULT_COMPONENT_BY_TYPES...
--- +++ @@ -1,3 +1,4 @@+"""Get config from Pipeline""" import inspect from pathlib import Path from typing import Any, Dict, Optional, Type, Union @@ -11,6 +12,14 @@ def config_from_value(value: Any) -> dict: + """Get the config from default value + + Args: + value (Any): default value + + Return...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/contribs/promptui/config.py
Provide clean and structured docstrings
from __future__ import annotations def is_valid_sudoku(board: list[list[str]]) -> bool: seen: list[tuple[str, ...]] = [] for i, row in enumerate(board): for j, cell in enumerate(row): if cell != ".": seen += [(cell, j), (i, cell), (i // 3, j // 3, cell)] return len(see...
--- +++ @@ -1,11 +1,35 @@+""" +Valid Sudoku + +Determine if a partially filled 9x9 Sudoku board is valid. A board is +valid if each row, column, and 3x3 sub-box contains no duplicate digits. + +Reference: https://leetcode.com/problems/valid-sudoku/ + +Complexity: + Time: O(1) (board is always 9x9) + Space: O(1) ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/map/valid_sudoku.py
Create structured documentation for my script
from __future__ import annotations def multiply(mat_a: list[list[int]], mat_b: list[list[int]]) -> list[list[int]]: size = len(mat_a) result = [[0] * size for _ in range(size)] for i in range(size): for j in range(size): for k in range(size): result[i][j] += mat_a[i][k...
--- +++ @@ -1,8 +1,34 @@+""" +Matrix Exponentiation + +Compute the n-th power of a square matrix using repeated squaring +(exponentiation by squaring). Useful for computing Fibonacci numbers, +linear recurrences, and graph path counting. + +Reference: https://en.wikipedia.org/wiki/Exponentiation_by_squaring + +Complexi...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/matrix_exponentiation.py
Provide docstrings following PEP 257
import requests from kotaemon.base import Document, DocumentWithEmbedding from .base import BaseEmbeddings class EndpointEmbeddings(BaseEmbeddings): endpoint_url: str def run( self, text: str | list[str] | Document | list[Document] ) -> list[DocumentWithEmbedding]: if not isinstance(te...
--- +++ @@ -6,12 +6,25 @@ class EndpointEmbeddings(BaseEmbeddings): + """ + An Embeddings component that uses an OpenAI API compatible endpoint. + + Attributes: + endpoint_url (str): The url of an OpenAI API compatible endpoint. + """ endpoint_url: str def run( self, text: ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/embeddings/endpoint_based.py
Document this module using docstrings
from itertools import islice from typing import Optional import numpy as np import openai import tiktoken from tenacity import ( retry, retry_if_not_exception_type, stop_after_attempt, wait_random_exponential, ) from theflow.utils.modules import import_dotted_string from kotaemon.base import Param fr...
--- +++ @@ -18,6 +18,15 @@ def split_text_by_chunk_size(text: str, chunk_size: int) -> list[list[int]]: + """Split the text into chunks of a given size + + Args: + text: text to split + chunk_size: size of each chunk + + Returns: + list of chunks (as tokens) + """ encoding = ti...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/embeddings/openai.py
Write docstrings that follow conventions
from typing import TYPE_CHECKING, Optional from kotaemon.base import Document, DocumentWithEmbedding, Param from .base import BaseEmbeddings if TYPE_CHECKING: from fastembed import TextEmbedding class FastEmbedEmbeddings(BaseEmbeddings): model_name: str = Param( "BAAI/bge-small-en-v1.5", h...
--- +++ @@ -9,6 +9,11 @@ class FastEmbedEmbeddings(BaseEmbeddings): + """Utilize fastembed library for embeddings locally without GPU. + + Supported model: https://qdrant.github.io/fastembed/examples/Supported_Models/ + Code: https://github.com/qdrant/fastembed + """ model_name: str = Param( ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/embeddings/fastembed.py
Add docstrings to improve readability
from __future__ import annotations def reverse_list(head: object | None) -> object | None: if not head or not head.next: return head prev = None while head: current = head head = head.next current.next = prev prev = current return prev def reverse_list_recurs...
--- +++ @@ -1,8 +1,32 @@+""" +Reverse Linked List + +Reverse a singly linked list. Both iterative and recursive solutions are +provided. + +Reference: https://leetcode.com/problems/reverse-linked-list/ + +Complexity: + Time: O(n) + Space: O(1) iterative, O(n) recursive +""" from __future__ import annotations ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/reverse.py
Help me write clear docstrings
import importlib from kotaemon.base import Document, DocumentWithEmbedding, Param from .base import BaseEmbeddings vo = None def _import_voyageai(): global vo if not vo: vo = importlib.import_module("voyageai") return vo def _format_output(texts: list[str], embeddings: list[list]): retur...
--- +++ @@ -1,3 +1,5 @@+"""Implements embeddings from [Voyage AI](https://voyageai.com). +""" import importlib @@ -16,6 +18,11 @@ def _format_output(texts: list[str], embeddings: list[list]): + """Formats the output of all `.embed` calls. + Args: + texts: List of original documents + embedd...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/embeddings/voyageai.py
Add docstrings that explain inputs and outputs
import pickle from datetime import datetime from pathlib import Path import gradio as gr from theflow.storage import storage from kotaemon.chatbot import ChatConversation from kotaemon.contribs.promptui.base import get_component from kotaemon.contribs.promptui.export import export from kotaemon.contribs.promptui.ui.b...
--- +++ @@ -46,6 +46,18 @@ def construct_chat_ui( config, func_new_chat, func_chat, func_end_chat, func_export_to_excel ) -> gr.Blocks: + """Construct the prompt engineering UI for chat + + Args: + config: the UI config + func_new_chat: the function for starting a new chat session + fun...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/contribs/promptui/ui/chat.py
Add missing documentation to my Python functions
from __future__ import annotations from abc import abstractmethod from typing import Any, Type from llama_index.core.node_parser.interface import NodeParser from kotaemon.base import BaseComponent, Document, RetrievedDocument class DocTransformer(BaseComponent): @abstractmethod def run( self, ...
--- +++ @@ -9,6 +9,13 @@ class DocTransformer(BaseComponent): + """This is a base class for document transformers + + A document transformer transforms a list of documents into another list + of documents. Transforming can mean splitting a document into multiple documents, + reducing a large list of doc...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/indices/base.py
Add docstrings for production code
from pathlib import Path from typing import Type from decouple import config from llama_index.core.readers.base import BaseReader from llama_index.readers.file import PDFReader from theflow.settings import settings as flowsettings from kotaemon.base import BaseComponent, Document, Param from kotaemon.indices.extracto...
--- +++ @@ -59,6 +59,23 @@ class DocumentIngestor(BaseComponent): + """Ingest common office document types into Document for indexing + + Document types: + - pdf + - xlsx, xls + - docx, doc + + Args: + pdf_mode: mode for pdf extraction, one of "normal", "mathpix", "ocr" + ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/indices/ingests/files.py
Write docstrings for utility functions
from __future__ import annotations from collections import deque from algorithms.tree.tree import TreeNode def max_height(root: TreeNode | None) -> int: if root is None: return 0 height = 0 queue: deque[TreeNode] = deque([root]) while queue: height += 1 level: deque[TreeNode...
--- +++ @@ -1,3 +1,15 @@+""" +Maximum Depth of Binary Tree + +Given a binary tree, find its maximum depth. The maximum depth is the number +of nodes along the longest path from the root down to the farthest leaf. + +Reference: https://en.wikipedia.org/wiki/Binary_tree + +Complexity: + Time: O(n) + Space: O(n) +"...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/max_height.py
Generate consistent documentation across files
import threading from collections import defaultdict from typing import Generator import numpy as np from decouple import config from theflow.settings import settings as flowsettings from kotaemon.base import ( AIMessage, BaseComponent, Document, HumanMessage, Node, SystemMessage, ) from kotae...
--- +++ @@ -81,6 +81,19 @@ class AnswerWithContextPipeline(BaseComponent): + """Answer the question based on the evidence + + Args: + llm: the language model to generate the answer + citation_pipeline: generates citation from the evidence + qa_template: the prompt template for LLM to gene...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/indices/qa/citation_qa.py
Generate docstrings for exported functions
from typing import List from pydantic import BaseModel, Field from kotaemon.base import BaseComponent from kotaemon.base.schema import HumanMessage, SystemMessage from kotaemon.llms import BaseLLM class CiteEvidence(BaseModel): evidences: List[str] = Field( ..., description=( "Each ...
--- +++ @@ -8,6 +8,7 @@ class CiteEvidence(BaseModel): + """List of evidences (maximum 5) to support the answer.""" evidences: List[str] = Field( ..., @@ -19,6 +20,8 @@ class CitationPipeline(BaseComponent): + """Citation pipeline to extract cited evidences from source + (based on input...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/indices/qa/citation.py
Auto-generate documentation strings for this file
from __future__ import annotations from algorithms.tree.tree import TreeNode def lca(root: TreeNode | None, p: TreeNode, q: TreeNode) -> TreeNode | None: 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 r...
--- +++ @@ -1,3 +1,16 @@+""" +Lowest Common Ancestor + +Given a binary tree, find the lowest common ancestor (LCA) of two given nodes. +The LCA is the lowest node that has both nodes as descendants (a node can be a +descendant of itself). + +Reference: https://en.wikipedia.org/wiki/Lowest_common_ancestor + +Complexity:...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/lowest_common_ancestor.py
Add docstrings that explain inputs and outputs
import re import threading from collections import defaultdict from dataclasses import dataclass from typing import Generator import numpy as np from kotaemon.base import AIMessage, Document, HumanMessage, SystemMessage from kotaemon.llms import PromptTemplate from .citation_qa import CITATION_TIMEOUT, MAX_IMAGES, A...
--- +++ @@ -76,6 +76,7 @@ @dataclass class InlineEvidence: + """List of evidences to support the answer.""" start_phrase: str | None = None end_phrase: str | None = None @@ -83,10 +84,12 @@ class AnswerWithInlineCitation(AnswerWithContextPipeline): + """Answer the question based on the evidence...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/indices/qa/citation_qa_inline.py
Document this code for team use
import math from dataclasses import dataclass import torch from einops import rearrange from torch import Tensor, nn from flux.math import attention, rope class EmbedND(nn.Module): def __init__(self, dim: int, theta: int, axes_dim: list[int]): super().__init__() self.dim = dim self.theta...
--- +++ @@ -26,6 +26,14 @@ def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0): + """ + Create sinusoidal timestep embeddings. + :param t: a 1-D Tensor of N indices, one per batch element. + These may be fractional. + :param dim: the dimension of th...
https://raw.githubusercontent.com/black-forest-labs/flux/HEAD/src/flux/modules/layers.py
Generate docstrings for each module
from __future__ import annotations import re from concurrent.futures import ThreadPoolExecutor from functools import partial import tiktoken from kotaemon.base import Document, HumanMessage, SystemMessage from kotaemon.indices.splitters import TokenSplitter from kotaemon.llms import BaseLLM, PromptTemplate from .ll...
--- +++ @@ -50,6 +50,7 @@ def validate_rating(rating) -> int: + """Validate a rating is between 0 and 10.""" if not 0 <= rating <= 10: raise ValueError("Rating must be between 0 and 10") @@ -58,6 +59,21 @@ def re_0_10_rating(s: str) -> int: + """Extract a 0-10 rating from a string. + + ...
https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/indices/rankings/llm_trulens.py
Add structured docstrings to improve clarity
# # SPDX-FileCopyrightText: Copyright (c) 1993-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at...
--- +++ @@ -84,6 +84,30 @@ precision_constraints="none", verbose=False, ): + """ + Metod used to build a TRT engine from a given set of flags or configurations using polygraphy. + + Args: + engine_path (str): Output path used to store the build engine. + ...
https://raw.githubusercontent.com/black-forest-labs/flux/HEAD/src/flux/trt/trt_config/base_trt_config.py