sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
keon/algorithms:algorithms/math/rabin_miller.py
""" Rabin-Miller Primality Test A probabilistic primality test where returning False guarantees the number is composite, and returning True means the number is probably prime with a 4^(-k) chance of error. Reference: https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test Complexity: Time: O(k * log^2(n)) Space: O(1) """ from __future__ import annotations import random def is_prime(n: int, k: int) -> bool: """Test if n is probably prime using the Rabin-Miller algorithm. Args: n: The integer to test for primality. k: The number of rounds of testing (higher = more accurate). Returns: True if n is probably prime, False if n is definitely composite. Examples: >>> is_prime(7, 2) True >>> is_prime(6, 2) False """ def _pow2_factor(num: int) -> tuple[int, float]: """Factor num into 2^power * odd_part. Args: num: The integer to factor. Returns: A tuple (power, odd_part). """ power = 0 while num % 2 == 0: num /= 2 power += 1 return power, num def _valid_witness(a: int) -> bool: """Check if a is a witness for the compositeness of n. Args: a: The potential witness value. Returns: True if a proves n is composite, False otherwise. """ x = pow(int(a), int(d), int(n)) if x == 1 or x == n - 1: return False for _ in range(r - 1): x = pow(int(x), 2, int(n)) if x == 1: return True if x == n - 1: return False return True if n < 5: return n == 2 or n == 3 r, d = _pow2_factor(n - 1) return all( not _valid_witness(random.randrange(2, n - 2)) for _ in range(k) )
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/rabin_miller.py", "license": "MIT License", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/recursive_binomial_coefficient.py
""" Recursive Binomial Coefficient Calculate the binomial coefficient C(n, k) using a recursive formula with the identity C(n, k) = (n/k) * C(n-1, k-1). Reference: https://en.wikipedia.org/wiki/Binomial_coefficient Complexity: Time: O(k) Space: O(k) recursive stack """ from __future__ import annotations def recursive_binomial_coefficient(n: int, k: int) -> int: """Calculate C(n, k) recursively, where n >= k. Args: n: Total number of items. k: Number of items to choose. Returns: The binomial coefficient C(n, k). Raises: ValueError: If k > n. Examples: >>> recursive_binomial_coefficient(5, 0) 1 >>> recursive_binomial_coefficient(8, 2) 28 """ if k > n: raise ValueError("Invalid Inputs, ensure that n >= k") if k == 0 or n == k: return 1 if k > n / 2: return recursive_binomial_coefficient(n, n - k) return int((n / k) * recursive_binomial_coefficient(n - 1, k - 1))
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/recursive_binomial_coefficient.py", "license": "MIT License", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/rsa.py
""" RSA Encryption Algorithm Implements RSA key generation, encryption, and decryption. RSA uses separate public and private keys where ((x^e)^d) % n == x % n. Reference: https://en.wikipedia.org/wiki/RSA_(cryptosystem) Complexity: Time: O(k^3) for key generation (k = bit length) Space: O(k) """ from __future__ import annotations import random def generate_key(k: int, seed: int | None = None) -> tuple[int, int, int]: """Generate an RSA key triplet (n, e, d). Args: k: The number of bits in the modulus n. seed: Optional random seed for reproducibility. Returns: A tuple (n, e, d) where n is the modulus, e is the encryption exponent, and d is the decryption exponent. Examples: >>> n, e, d = generate_key(16, seed=42) """ def _modinv(a: int, m: int) -> int: """Calculate the modular inverse of a mod m. Args: a: The integer. m: The modulus. Returns: b such that (a * b) % m == 1. """ b = 1 while (a * b) % m != 1: b += 1 return b def _gen_prime(k: int, seed: int | None = None) -> int: """Generate a random prime with k bits. Args: k: The number of bits. seed: Optional random seed. Returns: A prime number. """ def _is_prime(num: int) -> bool: if num == 2: return True return all( num % i != 0 for i in range(2, int(num**0.5) + 1) ) random.seed(seed) while True: key = random.randrange(int(2 ** (k - 1)), int(2**k)) if _is_prime(key): return key p_size = k / 2 q_size = k - p_size e = _gen_prime(k, seed) 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 totient = (p - 1) * (q - 1) d = _modinv(e, totient) return int(n), int(e), int(d) def encrypt(data: int, e: int, n: int) -> int: """Encrypt data using RSA public key. Args: data: The plaintext integer. e: The encryption exponent. n: The modulus. Returns: The encrypted integer. Examples: >>> encrypt(7, 23, 143) 2 """ return pow(int(data), int(e), int(n)) def decrypt(data: int, d: int, n: int) -> int: """Decrypt data using RSA private key. Args: data: The encrypted integer. d: The decryption exponent. n: The modulus. Returns: The decrypted plaintext integer. Examples: >>> decrypt(2, 47, 143) 7 """ return pow(int(data), int(d), int(n))
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/rsa.py", "license": "MIT License", "lines": 95, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/sqrt_precision_factor.py
""" Square Root by Newton's Method Compute the square root of a positive number using Newton's method (Babylonian method) with a configurable precision factor. Reference: https://en.wikipedia.org/wiki/Newton%27s_method#Square_root Complexity: Time: O(log(1/epsilon)) iterations for convergence Space: O(1) """ from __future__ import annotations def square_root(n: float, epsilon: float = 0.001) -> float: """Compute the square root of n with maximum absolute error epsilon. Args: n: A positive number. epsilon: Maximum allowed absolute error. Returns: An approximation of sqrt(n). Examples: >>> abs(square_root(5, 0.001) - 2.236) < 0.002 True """ guess = n / 2 while abs(guess * guess - n) > epsilon: guess = (guess + (n / guess)) / 2 return guess
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/sqrt_precision_factor.py", "license": "MIT License", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/summing_digits.py
""" Summing Digits Power Find all integers in a range where each digit raised to its positional power (1-indexed) sums to the number itself (e.g., 89 = 8^1 + 9^2). Reference: https://en.wikipedia.org/wiki/Perfect_digit-to-digit_invariant Complexity: Time: O((high - low) * d) where d is the number of digits Space: O(result size) """ from __future__ import annotations def sum_dig_pow(low: int, high: int) -> list[int]: """Find numbers where digits raised to positional powers equal the number. Args: low: Lower bound of the range (inclusive). high: Upper bound of the range (inclusive). Returns: List of matching numbers in the range. Examples: >>> sum_dig_pow(1, 10) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> sum_dig_pow(1, 100) [1, 2, 3, 4, 5, 6, 7, 8, 9, 89] """ result = [] for number in range(low, high + 1): exponent = 1 summation = 0 number_as_string = str(number) tokens = list(map(int, number_as_string)) for k in tokens: summation = summation + (k**exponent) exponent += 1 if summation == number: result.append(number) return result
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/summing_digits.py", "license": "MIT License", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/surface_area_of_torus.py
""" Surface Area of a Torus Calculate the surface area of a torus given its major and minor radii using the formula A = 4 * pi^2 * R * r. Reference: https://en.wikipedia.org/wiki/Torus Complexity: Time: O(1) Space: O(1) """ from __future__ import annotations from math import pi def surface_area_of_torus(major_radius: float, minor_radius: float) -> float: """Calculate the surface area of a torus. Args: major_radius: Distance from the center of the tube to the center of the torus (R). minor_radius: Radius of the tube (r). Returns: The surface area of the torus. Raises: ValueError: If either radius is negative. Examples: >>> surface_area_of_torus(3.0, 1.0) 118.4352528130723 """ if major_radius < 0 or minor_radius < 0: raise ValueError("Radii must be non-negative") return 4 * pi**2 * major_radius * minor_radius
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/surface_area_of_torus.py", "license": "MIT License", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/symmetry_group_cycle_index.py
""" Symmetry Group Cycle Index Compute the cycle index polynomial of the symmetric group S_n and use it to count distinct configurations of grids under row/column permutations via Burnside's lemma. Reference: https://en.wikipedia.org/wiki/Cycle_index#Symmetric_group_Sn Complexity: Time: O(n!) for cycle index computation Space: O(n!) for memoization """ from __future__ import annotations from fractions import Fraction from algorithms.math.gcd import lcm from algorithms.math.polynomial import Monomial, Polynomial def cycle_product(m1: Monomial, m2: Monomial) -> Monomial: """Compute the cycle product of two monomials from cycle indices. Args: m1: First monomial from a cycle index. m2: Second monomial from a cycle index. Returns: The resultant monomial from the Cartesian product merging. """ assert isinstance(m1, Monomial) and isinstance(m2, Monomial) a_vars = m1.variables b_vars = m2.variables result_variables: dict[int, int] = dict() for i in a_vars: for j in b_vars: k = lcm(i, j) g = (i * j) // k if k in result_variables: result_variables[k] += a_vars[i] * b_vars[j] * g else: result_variables[k] = a_vars[i] * b_vars[j] * g return Monomial(result_variables, Fraction(m1.coeff * m2.coeff, 1)) def cycle_product_for_two_polynomials( p1: Polynomial, p2: Polynomial, q: float | int | Fraction ) -> float | int | Fraction: """Compute the product of two cycle indices and evaluate at q. Args: p1: First cycle index polynomial. p2: Second cycle index polynomial. q: The value to substitute for all variables. Returns: The evaluated result. """ ans = Fraction(0, 1) for m1 in p1.monomials: for m2 in p2.monomials: ans += cycle_product(m1, m2).substitute(q) return ans def _cycle_index_sym_helper(n: int, memo: dict[int, Polynomial]) -> Polynomial: """Recursively compute the cycle index of S_n with memoization. Args: n: The order of the symmetric group. memo: Dictionary of precomputed cycle indices. Returns: The cycle index polynomial of S_n. """ if n in memo: return memo[n] ans = Polynomial([Monomial({}, Fraction(0, 1))]) for t in range(1, n + 1): ans = ans.__add__( Polynomial([Monomial({t: 1}, Fraction(1, 1))]) * _cycle_index_sym_helper(n - t, memo) ) ans *= Fraction(1, n) memo[n] = ans return memo[n] def get_cycle_index_sym(n: int) -> Polynomial: """Compute the cycle index of the symmetric group S_n. Args: n: The order of the symmetric group (non-negative integer). Returns: The cycle index as a Polynomial. Raises: ValueError: If n is negative. Examples: >>> get_cycle_index_sym(1) # doctest: +SKIP Polynomial(...) """ if n < 0: raise ValueError("n should be a non-negative integer.") memo = { 0: Polynomial([Monomial({}, Fraction(1, 1))]), 1: Polynomial([Monomial({1: 1}, Fraction(1, 1))]), 2: Polynomial( [Monomial({1: 2}, Fraction(1, 2)), Monomial({2: 1}, Fraction(1, 2))] ), 3: Polynomial( [ Monomial({1: 3}, Fraction(1, 6)), Monomial({1: 1, 2: 1}, Fraction(1, 2)), Monomial({3: 1}, Fraction(1, 3)), ] ), 4: Polynomial( [ Monomial({1: 4}, Fraction(1, 24)), Monomial({2: 1, 1: 2}, Fraction(1, 4)), Monomial({3: 1, 1: 1}, Fraction(1, 3)), Monomial({2: 2}, Fraction(1, 8)), Monomial({4: 1}, Fraction(1, 4)), ] ), } result = _cycle_index_sym_helper(n, memo) return result
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/symmetry_group_cycle_index.py", "license": "MIT License", "lines": 109, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
keon/algorithms:algorithms/queue/max_sliding_window.py
""" Max Sliding Window (Deque-based) Given an array and a window size k, find the maximum element in each sliding window using a monotonic deque that stores indices of elements in decreasing order of their values. Reference: https://leetcode.com/problems/sliding-window-maximum/ Complexity: Time: O(n) Space: O(k) """ from __future__ import annotations import collections def max_sliding_window(arr: list[int], k: int) -> list[int]: """Find the maximum in each sliding window of size k. Uses a deque to maintain indices of useful elements in decreasing order. The front of the deque always holds the index of the current window maximum. Args: arr: Input array of integers. k: Window size. Returns: List of maximum values for each window position. Examples: >>> max_sliding_window([1, 3, -1, -3, 5, 3, 6, 7], 3) [3, 3, 5, 5, 6, 7] """ index_deque: collections.deque[int] = collections.deque() result: list[int] = [] for i, value in enumerate(arr): while index_deque and arr[index_deque[-1]] < value: index_deque.pop() index_deque.append(i) if index_deque[0] == i - k: index_deque.popleft() if i >= k - 1: result.append(arr[index_deque[0]]) return result
{ "repo_id": "keon/algorithms", "file_path": "algorithms/queue/max_sliding_window.py", "license": "MIT License", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/queue/moving_average.py
""" Moving Average from Data Stream Calculate the moving average of integers in a sliding window of fixed size using a bounded deque. Reference: https://leetcode.com/problems/moving-average-from-data-stream/ Complexity: Time: O(1) per call to next Space: O(size) """ from __future__ import annotations from collections import deque class MovingAverage: """Computes the moving average over a sliding window. Examples: >>> m = MovingAverage(3) >>> m.next(1) 1.0 >>> m.next(10) 5.5 """ def __init__(self, size: int) -> None: """Initialize the moving average calculator. Args: size: The window size for the moving average. """ self.queue: deque[int] = deque(maxlen=size) def next(self, val: int) -> float: """Add a value and return the current moving average. Args: val: The next integer in the data stream. Returns: The current moving average as a float. """ self.queue.append(val) return sum(self.queue) / len(self.queue)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/queue/moving_average.py", "license": "MIT License", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/queue/reconstruct_queue.py
""" Reconstruct Queue by Height Given a list of people described by (height, k) pairs where k is the number of taller-or-equal people in front, reconstruct the queue by sorting and inserting. Reference: https://leetcode.com/problems/queue-reconstruction-by-height/ Complexity: Time: O(n^2) Space: O(n) """ from __future__ import annotations def reconstruct_queue(people: list[list[int]]) -> list[list[int]]: """Reconstruct the queue from (height, k) pairs. Args: people: List of [height, k] pairs. Returns: The reconstructed queue as a list of [height, k] pairs. Examples: >>> reconstruct_queue([[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]) [[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]] """ queue: list[list[int]] = [] people.sort(key=lambda x: (-x[0], x[1])) for height, count in people: queue.insert(count, [height, count]) return queue
{ "repo_id": "keon/algorithms", "file_path": "algorithms/queue/reconstruct_queue.py", "license": "MIT License", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/queue/zigzagiterator.py
""" Zigzag Iterator Interleave elements from two lists in a zigzag fashion. Elements are yielded alternately from each list until both are exhausted. Reference: https://leetcode.com/problems/zigzag-iterator/ Complexity: Time: O(n) total across all next() calls Space: O(n) """ from __future__ import annotations class ZigZagIterator: """Iterator that interleaves elements from two lists. Examples: >>> it = ZigZagIterator([1, 2], [3, 4, 5]) >>> it.next() 1 >>> it.next() 3 """ def __init__(self, v1: list[int], v2: list[int]) -> None: """Initialize with two lists. Args: v1: First input list. v2: Second input list. """ self.queue: list[list[int]] = [lst for lst in (v1, v2) if lst] def next(self) -> int: """Return the next element in zigzag order. Returns: The next interleaved element. """ current_list = self.queue.pop(0) ret = current_list.pop(0) if current_list: self.queue.append(current_list) return ret def has_next(self) -> bool: """Check if there are more elements. Returns: True if elements remain, False otherwise. """ return bool(self.queue)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/queue/zigzagiterator.py", "license": "MIT License", "lines": 42, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/searching/binary_search.py
""" Binary Search Search for an element in a sorted array by repeatedly dividing the search interval in half. Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm Complexity: Time: O(1) best / O(log n) average / O(log n) worst Space: O(1) iterative, O(log n) recursive """ from __future__ import annotations def binary_search(array: list[int], query: int) -> int: """Search for *query* in a sorted *array* using iterative binary search. Args: array: Sorted list of integers in ascending order. query: Value to search for. Returns: Index of *query* in *array*, or -1 if not found. Examples: >>> binary_search([1, 2, 3, 4, 5], 3) 2 >>> binary_search([1, 2, 3, 4, 5], 6) -1 """ low, high = 0, len(array) - 1 while low <= high: mid = low + (high - low) // 2 val = array[mid] if val == query: return mid if val < query: low = mid + 1 else: high = mid - 1 return -1 def binary_search_recur(array: list[int], low: int, high: int, val: int) -> int: """Search for *val* in a sorted *array* using recursive binary search. Args: array: Sorted list of integers in ascending order. low: Lower bound index of the current search range. high: Upper bound index of the current search range. val: Value to search for. Returns: Index of *val* in *array*, or -1 if not found. Examples: >>> binary_search_recur([1, 2, 3, 4, 5], 0, 4, 3) 2 >>> binary_search_recur([1, 2, 3, 4, 5], 0, 4, 6) -1 """ if low > high: return -1 mid = low + (high - low) // 2 if val < array[mid]: return binary_search_recur(array, low, mid - 1, val) if val > array[mid]: return binary_search_recur(array, mid + 1, high, val) return mid
{ "repo_id": "keon/algorithms", "file_path": "algorithms/searching/binary_search.py", "license": "MIT License", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/searching/find_min_rotate.py
""" Find Minimum in Rotated Sorted Array Find the minimum element in a sorted array that has been rotated at some unknown pivot. Assumes no duplicates exist in the array. Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm Complexity: Time: O(1) best / O(log n) average / O(log n) worst Space: O(1) iterative, O(log n) recursive """ from __future__ import annotations def find_min_rotate(array: list[int]) -> int: """Find the minimum element in a rotated sorted array (iterative). Args: array: A sorted list of unique integers that has been rotated. Returns: The minimum value in the array. Examples: >>> find_min_rotate([4, 5, 6, 7, 0, 1, 2]) 0 >>> find_min_rotate([1, 2, 3]) 1 """ low = 0 high = len(array) - 1 while low < high: mid = (low + high) // 2 if array[mid] > array[high]: low = mid + 1 else: high = mid return array[low] def find_min_rotate_recur(array: list[int], low: int, high: int) -> int: """Find the minimum element in a rotated sorted array (recursive). Args: array: A sorted list of unique integers that has been rotated. low: Lower bound index of the current search range. high: Upper bound index of the current search range. Returns: The minimum value in the array. Examples: >>> find_min_rotate_recur([4, 5, 6, 7, 0, 1, 2], 0, 6) 0 """ mid = (low + high) // 2 if mid == low: return array[low] if array[mid] > array[high]: return find_min_rotate_recur(array, mid + 1, high) return find_min_rotate_recur(array, low, mid)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/searching/find_min_rotate.py", "license": "MIT License", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/searching/first_occurrence.py
""" First Occurrence Find the index of the first occurrence of a target value in a sorted array using binary search. Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm Complexity: Time: O(1) best / O(log n) average / O(log n) worst Space: O(1) """ from __future__ import annotations def first_occurrence(array: list[int], query: int) -> int: """Find the index of the first occurrence of *query* in *array*. Args: array: Sorted list of integers in ascending order. query: Value to search for. Returns: Index of the first occurrence of *query*, or -1 if not found. Examples: >>> first_occurrence([1, 2, 2, 2, 3, 4], 2) 1 >>> first_occurrence([1, 2, 3, 4, 5], 6) -1 """ low, high = 0, len(array) - 1 while low <= high: mid = low + (high - low) // 2 if low == high: break if array[mid] < query: low = mid + 1 else: high = mid if array[low] == query: return low return -1
{ "repo_id": "keon/algorithms", "file_path": "algorithms/searching/first_occurrence.py", "license": "MIT License", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/searching/generalized_binary_search.py
""" Generalized Binary Search Find the smallest value in a numeric range for which a monotonic boolean predicate evaluates to True. Instead of searching for a specific value in an array, this version accepts an arbitrary predicate, allowing the same binary search logic to be reused across many problem domains. Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm Complexity: Time: O(log n) Space: O(1) """ from __future__ import annotations from collections.abc import Callable def binary_search_first_true( low: int, high: int, predicate: Callable[[int], bool], ) -> int: """Find the smallest *x* in [low, high] where *predicate(x)* is True. The predicate must be monotonic: once it returns True for some value, it must return True for all larger values in the range. Args: low: Lower bound of the search range (inclusive). high: Upper bound of the search range (inclusive). predicate: A monotonic boolean function. Returns: The smallest *x* for which *predicate(x)* is True, or -1 if no such value exists in the range. Examples: >>> binary_search_first_true(0, 10, lambda x: x >= 7) 7 >>> binary_search_first_true(0, 10, lambda x: x * x >= 25) 5 >>> binary_search_first_true(0, 5, lambda x: x > 10) -1 """ result = -1 while low <= high: mid = low + (high - low) // 2 if predicate(mid): result = mid high = mid - 1 else: low = mid + 1 return result if __name__ == "__main__": print(binary_search_first_true(0, 10, lambda x: x >= 7)) # 7 print(binary_search_first_true(0, 10, lambda x: x * x >= 25)) # 5 print(binary_search_first_true(0, 5, lambda x: x > 10)) # -1
{ "repo_id": "keon/algorithms", "file_path": "algorithms/searching/generalized_binary_search.py", "license": "MIT License", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/searching/interpolation_search.py
""" Interpolation Search Search for a target value in a uniformly distributed sorted array by estimating the position of the target using linear interpolation. Reference: https://en.wikipedia.org/wiki/Interpolation_search Complexity: Time: O(1) best / O(log log n) average / O(n) worst Space: O(1) """ from __future__ import annotations def interpolation_search(array: list[int], search_key: int) -> int: """Search for *search_key* in a sorted *array* using interpolation search. Args: array: Sorted list of integers in ascending order. search_key: Value to search for. Returns: Index of *search_key* in *array*, or -1 if not found. Examples: >>> interpolation_search([-25, -12, -1, 10, 12, 15, 20, 41, 55], -1) 2 >>> interpolation_search([5, 10, 12, 14, 17, 20, 21], 55) -1 >>> interpolation_search([5, 10, 12, 14, 17, 20, 21], -5) -1 """ high = len(array) - 1 low = 0 while (low <= high) and (array[low] <= search_key <= array[high]): pos = low + int( ((search_key - array[low]) * (high - low)) / (array[high] - array[low]) ) if array[pos] == search_key: return pos if array[pos] < search_key: low = pos + 1 else: high = pos - 1 return -1 if __name__ == "__main__": import doctest doctest.testmod()
{ "repo_id": "keon/algorithms", "file_path": "algorithms/searching/interpolation_search.py", "license": "MIT License", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/searching/jump_search.py
""" Jump Search Search for a target value in a sorted array by jumping ahead in fixed-size blocks and then performing a linear search within the identified block. Reference: https://en.wikipedia.org/wiki/Jump_search Complexity: Time: O(1) best / O(sqrt n) average / O(sqrt n) worst Space: O(1) """ from __future__ import annotations import math def jump_search(array: list[int], target: int) -> int: """Search for *target* in a sorted *array* using jump search. Args: array: Sorted list of integers in ascending order. target: Value to search for. Returns: Index of *target* in *array*, or -1 if not found. Examples: >>> jump_search([1, 2, 3, 4, 5, 6, 7, 8, 9], 5) 4 >>> jump_search([1, 2, 3, 4, 5], 0) -1 """ length = len(array) block_size = int(math.sqrt(length)) block_prev = 0 block = block_size if array[length - 1] < target: return -1 while block <= length and array[block - 1] < target: block_prev = block block += block_size while array[block_prev] < target: block_prev += 1 if block_prev == min(block, length): return -1 if array[block_prev] == target: return block_prev return -1
{ "repo_id": "keon/algorithms", "file_path": "algorithms/searching/jump_search.py", "license": "MIT License", "lines": 40, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/searching/last_occurrence.py
""" Last Occurrence Find the index of the last occurrence of a target value in a sorted array using binary search. Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm Complexity: Time: O(1) best / O(log n) average / O(log n) worst Space: O(1) """ from __future__ import annotations def last_occurrence(array: list[int], query: int) -> int: """Find the index of the last occurrence of *query* in *array*. Args: array: Sorted list of integers in ascending order. query: Value to search for. Returns: Index of the last occurrence of *query*, or -1 if not found. Examples: >>> last_occurrence([1, 2, 2, 2, 3, 4], 2) 3 >>> last_occurrence([1, 2, 3, 4, 5], 6) -1 """ low, high = 0, len(array) - 1 while low <= high: mid = (high + low) // 2 if (array[mid] == query and mid == len(array) - 1) or ( array[mid] == query and array[mid + 1] > query ): return mid if array[mid] <= query: low = mid + 1 else: high = mid - 1 return -1
{ "repo_id": "keon/algorithms", "file_path": "algorithms/searching/last_occurrence.py", "license": "MIT License", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/searching/linear_search.py
""" Linear Search Search for a target value in an array by checking every element sequentially. The array does not need to be sorted. Reference: https://en.wikipedia.org/wiki/Linear_search Complexity: Time: O(1) best / O(n) average / O(n) worst Space: O(1) """ from __future__ import annotations def linear_search(array: list[int], query: int) -> int: """Search for *query* in *array* using linear search. Args: array: List of integers (order does not matter). query: Value to search for. Returns: Index of *query* in *array*, or -1 if not found. Examples: >>> linear_search([5, 1, 3, 2, 4], 3) 2 >>> linear_search([5, 1, 3, 2, 4], 6) -1 """ for i, value in enumerate(array): if value == query: return i return -1
{ "repo_id": "keon/algorithms", "file_path": "algorithms/searching/linear_search.py", "license": "MIT License", "lines": 27, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/searching/next_greatest_letter.py
""" Next Greatest Letter Given a sorted list of lowercase letters and a target letter, find the smallest letter in the list that is larger than the target. Letters wrap around, so if the target is greater than or equal to the last letter the answer is the first letter. Reference: https://leetcode.com/problems/find-smallest-letter-greater-than-target/description/ Complexity: next_greatest_letter -- O(log n) time, O(1) space (bisect) next_greatest_letter_v1 -- O(log n) time, O(1) space (manual binary search) next_greatest_letter_v2 -- O(n) time, O(1) space (brute force) """ from __future__ import annotations import bisect def next_greatest_letter(letters: list[str], target: str) -> str: """Find the smallest letter greater than *target* using ``bisect``. Args: letters: Sorted list of lowercase letters. target: The letter to exceed. Returns: The smallest letter in *letters* that is strictly greater than *target*, wrapping around if necessary. Examples: >>> next_greatest_letter(["c", "f", "j"], "a") 'c' >>> next_greatest_letter(["c", "f", "j"], "c") 'f' """ index = bisect.bisect(letters, target) return letters[index % len(letters)] def next_greatest_letter_v1(letters: list[str], target: str) -> str: """Find the smallest letter greater than *target* using binary search. Args: letters: Sorted list of lowercase letters. target: The letter to exceed. Returns: The smallest letter in *letters* that is strictly greater than *target*, wrapping around if necessary. Examples: >>> next_greatest_letter_v1(["c", "f", "j"], "d") 'f' """ if letters[0] > target: return letters[0] if letters[len(letters) - 1] <= target: return letters[0] left, right = 0, len(letters) - 1 while left <= right: mid = left + (right - left) // 2 if letters[mid] > target: right = mid - 1 else: left = mid + 1 return letters[left] def next_greatest_letter_v2(letters: list[str], target: str) -> str: """Find the smallest letter greater than *target* using brute force. Args: letters: Sorted list of lowercase letters. target: The letter to exceed. Returns: The smallest letter in *letters* that is strictly greater than *target*, wrapping around if necessary. Examples: >>> next_greatest_letter_v2(["c", "f", "j"], "d") 'f' """ for letter in letters: if letter > target: return letter return letters[0]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/searching/next_greatest_letter.py", "license": "MIT License", "lines": 70, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/searching/search_insert.py
""" Search Insert Position Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm Complexity: Time: O(1) best / O(log n) average / O(log n) worst Space: O(1) """ from __future__ import annotations def search_insert(array: list[int], val: int) -> int: """Return the index of *val* or the position where it should be inserted. Args: array: Sorted list of integers in ascending order. val: Value to search for or insert. Returns: Index of *val* in *array*, or the index at which *val* would be inserted to keep *array* sorted. Examples: >>> search_insert([1, 3, 5, 6], 5) 2 >>> search_insert([1, 3, 5, 6], 2) 1 >>> search_insert([1, 3, 5, 6], 7) 4 >>> search_insert([1, 3, 5, 6], 0) 0 """ low = 0 high = len(array) - 1 while low <= high: mid = low + (high - low) // 2 if val > array[mid]: low = mid + 1 else: high = mid - 1 return low
{ "repo_id": "keon/algorithms", "file_path": "algorithms/searching/search_insert.py", "license": "MIT License", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/searching/search_range.py
""" Search Range Given a sorted array of integers and a target value, find the starting and ending positions of the target. Returns [-1, -1] if the target is not found. Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm Complexity: Time: O(log n + k) where k is the number of occurrences in the worst case for the backward scan, O(log n) for the initial search Space: O(1) """ from __future__ import annotations def search_range(nums: list[int], target: int) -> list[int]: """Find the first and last positions of *target* in *nums*. Args: nums: Sorted list of integers in ascending order. target: Value to search for. Returns: A two-element list ``[first, last]`` of indices, or ``[-1, -1]`` if *target* is not present. Examples: >>> search_range([5, 7, 7, 8, 8, 8, 10], 8) [3, 5] >>> search_range([5, 7, 7, 8, 8, 8, 10], 11) [-1, -1] """ low = 0 high = len(nums) - 1 while low < high: mid = low + (high - low) // 2 if target <= nums[mid]: high = mid else: low = mid + 1 for j in range(len(nums) - 1, -1, -1): if nums[j] == target: return [low, j] return [-1, -1]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/searching/search_range.py", "license": "MIT License", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/searching/search_rotate.py
""" Search in Rotated Sorted Array Search for a target value in an array that was sorted in ascending order and then rotated at some unknown pivot. One half of the array is always in sorted order; we identify that half and decide which side to search. Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm Complexity: Time: O(1) best / O(log n) average / O(log n) worst Space: O(1) iterative, O(log n) recursive """ from __future__ import annotations def search_rotate(array: list[int], val: int) -> int: """Search for *val* in a rotated sorted *array* (iterative). Args: array: A sorted list of integers that has been rotated at an unknown pivot. val: Value to search for. Returns: Index of *val* in *array*, or -1 if not found. Examples: >>> search_rotate([4, 5, 6, 7, 0, 1, 2], 0) 4 >>> search_rotate([4, 5, 6, 7, 0, 1, 2], 3) -1 """ low, high = 0, len(array) - 1 while low <= high: mid = (low + high) // 2 if val == array[mid]: return mid if array[low] <= array[mid]: if array[low] <= val <= array[mid]: high = mid - 1 else: low = mid + 1 else: if array[mid] <= val <= array[high]: low = mid + 1 else: high = mid - 1 return -1 def search_rotate_recur( array: list[int], low: int, high: int, val: int, ) -> int: """Search for *val* in a rotated sorted *array* (recursive). Args: array: A sorted list of integers that has been rotated at an unknown pivot. low: Lower bound index of the current search range. high: Upper bound index of the current search range. val: Value to search for. Returns: Index of *val* in *array*, or -1 if not found. Examples: >>> search_rotate_recur([4, 5, 6, 7, 0, 1, 2], 0, 6, 0) 4 """ if low >= high: return -1 mid = (low + high) // 2 if val == array[mid]: return mid if array[low] <= array[mid]: if array[low] <= val <= array[mid]: return search_rotate_recur(array, low, mid - 1, val) return search_rotate_recur(array, mid + 1, high, val) if array[mid] <= val <= array[high]: return search_rotate_recur(array, mid + 1, high, val) return search_rotate_recur(array, low, mid - 1, val)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/searching/search_rotate.py", "license": "MIT License", "lines": 72, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/searching/ternary_search.py
""" Ternary Search Search for a target value in a sorted array by dividing the search range into three equal parts instead of two. At each step two midpoints are computed and the search range is narrowed to one third. Reference: https://en.wikipedia.org/wiki/Ternary_search Complexity: Time: O(1) best / O(log3 n) average / O(log3 n) worst Space: O(1) """ from __future__ import annotations def ternary_search(left: int, right: int, key: int, array: list[int]) -> int: """Search for *key* in a sorted *array* using ternary search. Args: left: Lower bound index of the search range (inclusive). right: Upper bound index of the search range (inclusive). key: Value to search for. array: Sorted list of integers in ascending order. Returns: Index of *key* in *array*, or -1 if not found within the range. Examples: >>> ternary_search(0, 8, 5, [1, 2, 3, 4, 5, 6, 7, 8, 9]) 4 >>> ternary_search(0, 4, 0, [1, 2, 3, 4, 5]) -1 """ while right >= left: mid1 = left + (right - left) // 3 mid2 = right - (right - left) // 3 if key == array[mid1]: return mid1 if key == array[mid2]: return mid2 if key < array[mid1]: right = mid1 - 1 elif key > array[mid2]: left = mid2 + 1 else: left = mid1 + 1 right = mid2 - 1 return -1
{ "repo_id": "keon/algorithms", "file_path": "algorithms/searching/ternary_search.py", "license": "MIT License", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/searching/two_sum.py
""" Two Sum Given a sorted array of integers and a target sum, find the 1-based indices of the two numbers that add up to the target. Three approaches are provided: binary search, hash table, and two pointers. Reference: https://en.wikipedia.org/wiki/Subset_sum_problem Complexity: two_sum -- O(n log n) time, O(1) space (binary search) two_sum1 -- O(n) time, O(n) space (hash table) two_sum2 -- O(n) time, O(1) space (two pointers) """ from __future__ import annotations def two_sum(numbers: list[int], target: int) -> list[int] | None: """Find two numbers that add up to *target* using binary search. Args: numbers: Sorted list of integers in ascending order. target: Desired sum of the two numbers. Returns: A list of two 1-based indices ``[i, j]`` such that ``numbers[i-1] + numbers[j-1] == target``, or ``None`` if no pair exists. Examples: >>> two_sum([2, 7, 11, 15], 9) [1, 2] >>> two_sum([1, 2, 3], 7) is None True """ for i, number in enumerate(numbers): second_val = target - number low, high = i + 1, len(numbers) - 1 while low <= high: mid = low + (high - low) // 2 if second_val == numbers[mid]: return [i + 1, mid + 1] if second_val > numbers[mid]: low = mid + 1 else: high = mid - 1 return None def two_sum1(numbers: list[int], target: int) -> list[int] | None: """Find two numbers that add up to *target* using a hash table. Args: numbers: List of integers (need not be sorted). target: Desired sum of the two numbers. Returns: A list of two 1-based indices ``[i, j]`` such that ``numbers[i-1] + numbers[j-1] == target``, or ``None`` if no pair exists. Examples: >>> two_sum1([2, 7, 11, 15], 9) [1, 2] """ seen: dict[int, int] = {} for i, num in enumerate(numbers): if target - num in seen: return [seen[target - num] + 1, i + 1] seen[num] = i return None def two_sum2(numbers: list[int], target: int) -> list[int] | None: """Find two numbers that add up to *target* using two pointers. Args: numbers: Sorted list of integers in ascending order. target: Desired sum of the two numbers. Returns: A list of two 1-based indices ``[i, j]`` such that ``numbers[i-1] + numbers[j-1] == target``, or ``None`` if no pair exists. Examples: >>> two_sum2([2, 7, 11, 15], 9) [1, 2] """ left = 0 right = len(numbers) - 1 while left < right: current_sum = numbers[left] + numbers[right] if current_sum == target: return [left + 1, right + 1] if current_sum > target: right = right - 1 else: left = left + 1 return None
{ "repo_id": "keon/algorithms", "file_path": "algorithms/searching/two_sum.py", "license": "MIT License", "lines": 82, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/bead_sort.py
""" Bead Sort Bead sort (also known as gravity sort) simulates how beads settle under gravity on an abacus. It only works with non-negative integers. Reference: https://en.wikipedia.org/wiki/Bead_sort Complexity: Time: O(n) best / O(n * max_value) average / O(n * max_value) worst Space: O(n * max_value) """ from __future__ import annotations def bead_sort(array: list[int]) -> list[int]: """Sort an array of non-negative integers using bead sort. Args: array: List of non-negative integers to sort. Returns: A sorted list. Raises: ValueError: If any element is negative. Examples: >>> bead_sort([6, 3, 4, 1, 5, 2]) [1, 2, 3, 4, 5, 6] """ if any(num < 0 for num in array): raise ValueError("Bead sort only works with non-negative integers.") max_value = max(array) if array else 0 grid = [[0] * len(array) for _ in range(max_value)] # Drop beads (place beads in columns) for col, num in enumerate(array): for row in range(num): grid[row][col] = 1 # Let the beads "fall" (count beads in each row) for row in grid: bead_count = sum(row) for col in range(len(array)): row[col] = 1 if col < bead_count else 0 # Read sorted values from the grid (rightmost column has fewest beads) n = len(array) sorted_array = [0] * n for col in range(n): sorted_array[col] = sum(grid[row][n - 1 - col] for row in range(max_value)) return sorted_array
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/bead_sort.py", "license": "MIT License", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/bitonic_sort.py
""" Bitonic Sort Bitonic sort is a comparison-based sorting algorithm designed for parallel execution. This implementation is sequential. The input size must be a power of two. Reference: https://en.wikipedia.org/wiki/Bitonic_sorter Complexity: Time: O(n log^2 n) best / O(n log^2 n) average / O(n log^2 n) worst Space: O(n log^2 n) """ from __future__ import annotations def bitonic_sort(array: list[int], reverse: bool = False) -> list[int]: """Sort an array using bitonic sort. Args: array: List of integers to sort. reverse: If True, sort in descending order. Returns: A sorted list. Raises: ValueError: If the array length is not a power of two. Examples: >>> bitonic_sort([4, 2, 1, 3]) [1, 2, 3, 4] """ n = len(array) if n <= 1: return array if not (n and not (n & (n - 1))): raise ValueError("the size of input should be power of two") left = bitonic_sort(array[: n // 2], True) right = bitonic_sort(array[n // 2 :], False) return _bitonic_merge(left + right, reverse) def _compare(array: list[int], reverse: bool) -> list[int]: """Compare and swap elements across the two halves of *array*.""" half = len(array) // 2 for i in range(half): if reverse != (array[i] > array[i + half]): array[i], array[i + half] = array[i + half], array[i] return array def _bitonic_merge(array: list[int], reverse: bool) -> list[int]: """Recursively merge a bitonic sequence into sorted order.""" n = len(array) if n <= 1: return array array = _compare(array, reverse) left = _bitonic_merge(array[: n // 2], reverse) right = _bitonic_merge(array[n // 2 :], reverse) return left + right
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/bitonic_sort.py", "license": "MIT License", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/bogo_sort.py
""" Bogo Sort Bogo sort repeatedly shuffles the array at random until it happens to be sorted. It is extremely inefficient and used only for educational purposes. Reference: https://en.wikipedia.org/wiki/Bogosort Complexity: Time: O(n) best / O(n * n!) average / O(infinity) worst Space: O(1) """ from __future__ import annotations import random def bogo_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using bogo sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> bogo_sort([3, 1, 2]) [1, 2, 3] """ while not _is_sorted(array): random.shuffle(array) return array def _is_sorted(array: list[int]) -> bool: """Return True if *array* is in non-decreasing order.""" return all( array[i] <= array[i + 1] for i in range(len(array) - 1) )
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/bogo_sort.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/bubble_sort.py
""" Bubble Sort Bubble sort repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. Reference: https://en.wikipedia.org/wiki/Bubble_sort Complexity: Time: O(n) best / O(n^2) average / O(n^2) worst Space: O(1) """ from __future__ import annotations def bubble_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using bubble sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> bubble_sort([3, 1, 2]) [1, 2, 3] """ n = len(array) swapped = True passes = 0 while swapped: swapped = False for i in range(1, n - passes): if array[i - 1] > array[i]: array[i - 1], array[i] = array[i], array[i - 1] swapped = True passes += 1 return array
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/bubble_sort.py", "license": "MIT License", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/bucket_sort.py
""" 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(n^2) worst Space: O(n + k) """ from __future__ import annotations def bucket_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using bucket sort. Args: array: List of non-negative integers to sort. Returns: A sorted list. Examples: >>> bucket_sort([3, 1, 2, 4]) [1, 2, 3, 4] """ 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) sorted_list: list[int] = [] for bucket in buckets: sorted_list.extend(_insertion_sort(bucket)) return sorted_list def _insertion_sort(array: list[int]) -> list[int]: """Sort *array* in-place using insertion sort and return it.""" for i in range(1, len(array)): key = array[i] j = i - 1 while j >= 0 and array[j] > key: array[j + 1] = array[j] j -= 1 array[j + 1] = key return array
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/bucket_sort.py", "license": "MIT License", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/cocktail_shaker_sort.py
""" Cocktail Shaker Sort Cocktail shaker sort is a variation of bubble sort that traverses the list alternately from left-to-right and right-to-left. Reference: https://en.wikipedia.org/wiki/Cocktail_shaker_sort Complexity: Time: O(n) best / O(n^2) average / O(n^2) worst Space: O(1) """ from __future__ import annotations def cocktail_shaker_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using cocktail shaker sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> cocktail_shaker_sort([3, 1, 2]) [1, 2, 3] """ n = len(array) swapped = True while swapped: swapped = False for i in range(1, n): if array[i - 1] > array[i]: array[i - 1], array[i] = array[i], array[i - 1] swapped = True if not swapped: return array swapped = False for i in range(n - 1, 0, -1): if array[i - 1] > array[i]: array[i - 1], array[i] = array[i], array[i - 1] swapped = True return array
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/cocktail_shaker_sort.py", "license": "MIT License", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/comb_sort.py
""" 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: Time: O(n log n) best / O(n^2) average / O(n^2) worst Space: O(1) """ from __future__ import annotations def comb_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using comb sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> comb_sort([3, 1, 2]) [1, 2, 3] """ 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 while i + gap < n: if array[i] > array[i + gap]: array[i], array[i + gap] = array[i + gap], array[i] is_sorted = False i += 1 return array
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/comb_sort.py", "license": "MIT License", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/counting_sort.py
""" 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: O(n + k) best / O(n + k) average / O(n + k) worst Space: O(n + k) where k is the range of input values """ from __future__ import annotations def counting_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using counting sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> counting_sort([3, 1, 2]) [1, 2, 3] """ 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 # Build cumulative counts for i in range(1, max_value + 1): counts[i] += counts[i - 1] result = [0] * len(array) for i in range(len(array) - 1, -1, -1): value = shifted[i] counts[value] -= 1 result[counts[value]] = value - offset return result
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/counting_sort.py", "license": "MIT License", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/cycle_sort.py
""" 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: O(n^2) best / O(n^2) average / O(n^2) worst Space: O(1) """ from __future__ import annotations def cycle_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using cycle sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> cycle_sort([3, 1, 2]) [1, 2, 3] """ 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): if array[i] < item: position += 1 # No cycle needed for this element if position == start: continue # Skip duplicates while item == array[position]: position += 1 array[position], item = item, array[position] # Rotate the rest of the cycle while position != start: position = start for i in range(start + 1, length): if array[i] < item: position += 1 while item == array[position]: position += 1 array[position], item = item, array[position] return array
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/cycle_sort.py", "license": "MIT License", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/exchange_sort.py
""" 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) worst Space: O(1) """ from __future__ import annotations def exchange_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using exchange sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> exchange_sort([3, 1, 2]) [1, 2, 3] """ 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
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/exchange_sort.py", "license": "MIT License", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/gnome_sort.py
""" 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: Time: O(n) best / O(n^2) average / O(n^2) worst Space: O(1) """ from __future__ import annotations def gnome_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using gnome sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> gnome_sort([3, 1, 2]) [1, 2, 3] """ 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] index -= 1 return array
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/gnome_sort.py", "license": "MIT License", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/heap_sort.py
""" 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 log n) average / O(n log n) worst Space: O(1) """ from __future__ import annotations def max_heap_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using a max-heap. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> max_heap_sort([3, 1, 2]) [1, 2, 3] """ for i in range(len(array) - 1, 0, -1): _max_heapify(array, i) return array def _max_heapify(array: list[int], end: int) -> None: """Build a max-heap on *array[0..end]* and swap the root to *end*.""" last_parent = (end - 1) // 2 for parent in range(last_parent, -1, -1): current = parent while current <= last_parent: child = 2 * current + 1 if child + 1 <= end and array[child] < array[child + 1]: child += 1 if array[child] > array[current]: array[current], array[child] = array[child], array[current] current = child else: break array[0], array[end] = array[end], array[0] def min_heap_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using a min-heap. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> min_heap_sort([3, 1, 2]) [1, 2, 3] """ for i in range(len(array) - 1): _min_heapify(array, i) return array def _min_heapify(array: list[int], start: int) -> None: """Build a min-heap on *array[start..]* and place the minimum at *start*.""" end = len(array) - 1 last_parent = (end - start - 1) // 2 for parent in range(last_parent, -1, -1): current = parent while current <= last_parent: child = 2 * current + 1 if ( child + 1 <= end - start and array[child + start] > array[child + 1 + start] ): child += 1 if array[child + start] < array[current + start]: array[current + start], array[child + start] = ( array[child + start], array[current + start], ) current = child else: break
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/heap_sort.py", "license": "MIT License", "lines": 73, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/insertion_sort.py
""" 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 Space: O(1) """ from __future__ import annotations def insertion_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using insertion sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> insertion_sort([3, 1, 2]) [1, 2, 3] """ 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 array
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/insertion_sort.py", "license": "MIT License", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/meeting_rooms.py
""" 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: Time: O(n log n) best / O(n log n) average / O(n log n) worst Space: O(1) """ from __future__ import annotations def can_attend_meetings(intervals: list) -> bool: """Determine whether all meetings can be attended without overlap. Args: intervals: List of interval objects with *start* and *end* attributes. Returns: True if a person can attend all meetings, False otherwise. Examples: >>> # With intervals [[0,30],[5,10],[15,20]] the answer is False. >>> # With intervals [[7,10],[2,4]] the answer is True. """ 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
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/meeting_rooms.py", "license": "MIT License", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/merge_sort.py
""" 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) """ from __future__ import annotations def merge_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using merge sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> merge_sort([3, 1, 2]) [1, 2, 3] """ 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[int], merged: list[int]) -> None: """Merge two sorted lists into *merged* in-place. Args: left: Sorted left half. right: Sorted right half. merged: Destination list (length == len(left) + len(right)). """ left_cursor = 0 right_cursor = 0 while left_cursor < len(left) and right_cursor < len(right): if left[left_cursor] <= right[right_cursor]: merged[left_cursor + right_cursor] = left[left_cursor] left_cursor += 1 else: merged[left_cursor + right_cursor] = right[right_cursor] right_cursor += 1 for left_cursor in range(left_cursor, len(left)): # noqa: B020 merged[left_cursor + right_cursor] = left[left_cursor] for right_cursor in range(right_cursor, len(right)): # noqa: B020 merged[left_cursor + right_cursor] = right[right_cursor]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/merge_sort.py", "license": "MIT License", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/pancake_sort.py
""" 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 Complexity: Time: O(n) best / O(n^2) average / O(n^2) worst Space: O(1) """ from __future__ import annotations def pancake_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using pancake sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> pancake_sort([3, 1, 2]) [1, 2, 3] """ 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_max + 1] = reversed(array[: index_max + 1]) array[:cur] = reversed(array[:cur]) return array
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/pancake_sort.py", "license": "MIT License", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/pigeonhole_sort.py
""" 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 + range) worst Space: O(range) """ from __future__ import annotations def pigeonhole_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using pigeonhole sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> pigeonhole_sort([3, 1, 2]) [1, 2, 3] """ 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): while holes[count] > 0: holes[count] -= 1 array[i] = count + min_value i += 1 return array
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/pigeonhole_sort.py", "license": "MIT License", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/quick_sort.py
""" 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) """ from __future__ import annotations def quick_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using quick sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> quick_sort([3, 1, 2]) [1, 2, 3] """ _quick_sort_recursive(array, 0, len(array) - 1) return array def _quick_sort_recursive(array: list[int], first: int, last: int) -> None: """Recursively sort *array[first..last]* in-place.""" if first < last: pivot = _partition(array, first, last) _quick_sort_recursive(array, first, pivot - 1) _quick_sort_recursive(array, pivot + 1, last) def _partition(array: list[int], first: int, last: int) -> int: """Partition *array[first..last]* using the last element as pivot. Returns: The final index of the pivot element. """ wall = first for pos in range(first, last): if array[pos] < array[last]: array[pos], array[wall] = array[wall], array[pos] wall += 1 array[wall], array[last] = array[last], array[wall] return wall
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/quick_sort.py", "license": "MIT License", "lines": 40, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/radix_sort.py
""" 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 / O(n * k) worst Space: O(n + k) where k is the number of digits in the largest value """ from __future__ import annotations def radix_sort(array: list[int]) -> list[int]: """Sort an array of non-negative integers using radix sort. Args: array: List of non-negative integers to sort. Returns: A sorted list. Examples: >>> radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) [2, 24, 45, 66, 75, 90, 170, 802] """ 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].append(num) index = 0 for bucket in buckets: for num in bucket: array[index] = num index += 1 position *= 10 return array
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/radix_sort.py", "license": "MIT License", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/selection_sort.py
""" 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: O(1) """ from __future__ import annotations def selection_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using selection sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> selection_sort([3, 1, 2]) [1, 2, 3] """ 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] return array
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/selection_sort.py", "license": "MIT License", "lines": 27, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/shell_sort.py
""" 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://en.wikipedia.org/wiki/Shellsort Complexity: Time: O(n log n) best / O(n^(4/3)) average / O(n^2) worst Space: O(1) """ from __future__ import annotations def shell_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using shell sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> shell_sort([3, 1, 2]) [1, 2, 3] """ 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]: array[x_index + gap] = array[x_index] x_index -= gap array[x_index + gap] = y y_index += 1 gap //= 2 return array
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/shell_sort.py", "license": "MIT License", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/sort_colors.py
""" 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-colors/ Complexity: Time: O(n) best / O(n) average / O(n) worst Space: O(1) """ from __future__ import annotations def sort_colors(array: list[int]) -> list[int]: """Sort an array of 0s, 1s, and 2s in-place. Args: array: List of integers (each 0, 1, or 2) to sort. Returns: The sorted list. Examples: >>> sort_colors([2, 0, 1, 2, 1, 0]) [0, 0, 1, 1, 2, 2] """ 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 red += 1 return array
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/sort_colors.py", "license": "MIT License", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/stooge_sort.py
""" 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: O(n^2.709) best / O(n^2.709) average / O(n^2.709) worst Space: O(n) """ from __future__ import annotations def stooge_sort(array: list[int]) -> list[int]: """Sort an array in ascending order using stooge sort. Args: array: List of integers to sort. Returns: A sorted list. Examples: >>> stooge_sort([3, 1, 2]) [1, 2, 3] """ _stooge_sort(array, 0, len(array) - 1) return array def _stooge_sort(array: list[int], low: int, high: int) -> None: """Recursively sort *array[low..high]* using stooge sort.""" if low >= high: return if array[low] > array[high]: array[low], array[high] = array[high], array[low] if high - low + 1 > 2: third = (high - low + 1) // 3 _stooge_sort(array, low, high - third) _stooge_sort(array, low + third, high) _stooge_sort(array, low, high - third)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/stooge_sort.py", "license": "MIT License", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/sorting/wiggle_sort.py
""" 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 annotations def wiggle_sort(array: list[int]) -> list[int]: """Reorder *array* in-place into wiggle-sorted order. Args: array: List of integers to reorder. Returns: The wiggle-sorted list. Examples: >>> wiggle_sort([3, 5, 2, 1, 6, 4]) [3, 5, 1, 6, 2, 4] """ 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
{ "repo_id": "keon/algorithms", "file_path": "algorithms/sorting/wiggle_sort.py", "license": "MIT License", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/add_binary.py
""" Add Binary Given two binary strings, return their sum as a binary string. Reference: https://leetcode.com/problems/add-binary/ Complexity: Time: O(max(m, n)) where m, n are lengths of the two strings Space: O(max(m, n)) """ from __future__ import annotations def add_binary(first: str, second: str) -> str: """Add two binary strings and return their binary sum. Args: first: A string representing a binary number. second: A string representing a binary number. Returns: A string representing the binary sum of the two inputs. Examples: >>> add_binary("11", "1") '100' """ result = "" carry, index_a, index_b = 0, len(first) - 1, len(second) - 1 zero = ord("0") while index_a >= 0 or index_b >= 0 or carry == 1: if index_a >= 0: carry += ord(first[index_a]) - zero index_a -= 1 if index_b >= 0: carry += ord(second[index_b]) - zero index_b -= 1 result = chr(carry % 2 + zero) + result carry //= 2 return result
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/add_binary.py", "license": "MIT License", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/atbash_cipher.py
""" Atbash Cipher Atbash cipher maps each letter of the alphabet to its reverse. The first letter 'a' maps to 'z', 'b' maps to 'y', and so on. Reference: https://en.wikipedia.org/wiki/Atbash Complexity: Time: O(n) where n is the length of the input string Space: O(n) """ from __future__ import annotations def atbash(text: str) -> str: """Encrypt or decrypt a string using the Atbash cipher. Args: text: The input string to transform. Returns: The Atbash-transformed string. Examples: >>> atbash("abcdefghijklmno") 'zyxwvutsrqponml' """ translated = "" for char in text: code = ord(char) if char.isalpha(): if char.isupper(): offset = code - ord("A") translated += chr(ord("Z") - offset) elif char.islower(): offset = code - ord("a") translated += chr(ord("z") - offset) else: translated += char return translated
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/atbash_cipher.py", "license": "MIT License", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/breaking_bad.py
""" 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 Complexity: Time: O(n * m) for brute force, O(n * k) for trie-based approach Space: O(n * m) for storing results """ from __future__ import annotations import re from functools import reduce def match_symbol(words: list[str], symbols: list[str]) -> list[str]: """Match symbols in words using regex and surround matches with brackets. Args: words: List of words to search through. symbols: List of symbols to match within the words. Returns: List of words with matched symbols surrounded by square brackets. Examples: >>> match_symbol(['Google'], ['le']) ['Goog[le]'] """ combined = [] for symbol in symbols: for word in words: match = re.search(symbol, word) if match: combined.append(re.sub(symbol, f"[{symbol}]", word)) return combined def match_symbol_1(words: list[str], symbols: list[str]) -> list[str]: """Match the longest symbol in each word using sorted symbol list. Args: words: List of words to search through. symbols: List of symbols to match, sorted by length descending. Returns: List of words with the longest matched symbol bracketed. Examples: >>> match_symbol_1(['Microsoft'], ['i', 'cro']) ['Mi[cro]soft'] """ result = [] symbols = sorted(symbols, key=lambda item: len(item), reverse=True) for word in words: word_replaced = "" for symbol in symbols: if word.find(symbol) != -1: word_replaced = word.replace(symbol, "[" + symbol + "]") result.append(word_replaced) break if word_replaced == "": result.append(word) return result class _TrieNode: """Internal trie node for the bracket function.""" def __init__(self) -> None: self.children: dict[str, _TrieNode] = {} self.symbol: str | None = None def bracket(words: list[str], symbols: list[str]) -> tuple[str, ...]: """Match the longest symbol in each word using a trie-based approach. Args: words: List of words to search through. symbols: List of symbols to build the trie from. Returns: Tuple of words with the longest matched symbol bracketed. Examples: >>> bracket(['Amazon', 'Microsoft', 'Google'], ['Am', 'cro', 'le']) ('[Am]azon', 'Mi[cro]soft', 'Goog[le]') """ root = _TrieNode() for symbol in symbols: node = root for char in symbol: if char not in node.children: node.children[char] = _TrieNode() node = node.children[char] node.symbol = symbol matched = {} for word in words: index = 0 symbol_list = [] while index < len(word): cursor, node = index, root while cursor < len(word) and word[cursor] in node.children: node = node.children[word[cursor]] if node.symbol is not None: symbol_list.append( (cursor + 1 - len(node.symbol), cursor + 1, node.symbol) ) cursor += 1 index += 1 if len(symbol_list) > 0: best = reduce( lambda x, y: x if x[1] - x[0] >= y[1] - y[0] else y, symbol_list, ) matched[word] = f"{word[: best[0]]}[{best[2]}]{word[best[1] :]}" return tuple(matched.get(word, word) for word in words)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/breaking_bad.py", "license": "MIT License", "lines": 99, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/caesar_cipher.py
""" Caesar Cipher Caesar's cipher shifts each letter by a fixed number of positions in the alphabet. Letters wrap around when they pass the end of the alphabet. Reference: https://en.wikipedia.org/wiki/Caesar_cipher Complexity: Time: O(n) where n is the length of the input string Space: O(n) """ from __future__ import annotations def caesar_cipher(text: str, shift: int) -> str: """Encrypt a string using the Caesar cipher with the given shift. Args: text: The plaintext string to encrypt. shift: The number of positions to shift each letter. Returns: The encrypted string with shifted letters. Examples: >>> caesar_cipher("Hello_World!", 4) 'Lipps_Asvph!' """ result = "" for char in text: code = ord(char) if 64 < code < 91: code = ((code - 65 + shift) % 26) + 65 if 96 < code < 123: code = ((code - 97 + shift) % 26) + 97 result = result + chr(code) return result
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/caesar_cipher.py", "license": "MIT License", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/check_pangram.py
""" Check Pangram Checks whether a given string is a pangram, meaning it contains 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 input string Space: O(1) """ from __future__ import annotations def check_pangram(input_string: str) -> bool: """Check if the input string is a pangram. Args: input_string: The string to check. Returns: True if the string contains every letter of the alphabet, False otherwise. Examples: >>> check_pangram("The quick brown fox jumps over the lazy dog") True """ alphabet = "abcdefghijklmnopqrstuvwxyz" return all(char in input_string.lower() for char in alphabet)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/check_pangram.py", "license": "MIT License", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/contain_string.py
""" 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) Space: O(1) """ from __future__ import annotations def contain_string(haystack: str, needle: str) -> int: """Find the first occurrence of needle in haystack. Args: haystack: The string to search in. needle: The string to search for. Returns: The index of the first occurrence, or -1 if not found. Examples: >>> contain_string("hello", "ll") 2 """ 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[index : index + len(needle)] == needle: return index return -1
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/contain_string.py", "license": "MIT License", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/count_binary_substring.py
""" 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 length of the string Space: O(1) """ from __future__ import annotations def count_binary_substring(text: str) -> int: """Count substrings with equal consecutive 0s and 1s. Args: text: A binary string consisting of '0' and '1' characters. Returns: The number of valid binary substrings. Examples: >>> count_binary_substring("00110011") 6 """ 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 else: current = current + 1 count = count + min(previous, current) return count
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/count_binary_substring.py", "license": "MIT License", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/decode_string.py
""" 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 n is the length of the string Space: O(n) for the stack """ from __future__ import annotations def decode_string(text: str) -> str: """Decode an encoded string with nested repeat patterns. Args: text: The encoded string in the format k[encoded_string]. Returns: The fully decoded string. Examples: >>> decode_string("3[a]2[bc]") 'aaabcbc' """ 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 elif char == "]": prev_string, num = stack.pop() current_string = prev_string + num * current_string elif char.isdigit(): current_num = current_num * 10 + int(char) else: current_string += char return current_string
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/decode_string.py", "license": "MIT License", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/delete_reoccurring.py
""" 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 string Space: O(n) """ from __future__ import annotations def delete_reoccurring_characters(string: str) -> str: """Remove duplicate characters, keeping only the first occurrence of each. Args: string: The input string to process. Returns: A new string with duplicate characters removed. Examples: >>> delete_reoccurring_characters("aaabcccc") 'abc' """ 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
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/delete_reoccurring.py", "license": "MIT License", "lines": 27, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/domain_extractor.py
""" Domain Name Extractor Given a URL as a string, parse out just the domain name and return it. Uses only the .split() built-in function without regex or urlparse. Reference: https://en.wikipedia.org/wiki/Domain_name Complexity: Time: O(n) where n is the length of the URL Space: O(n) """ from __future__ import annotations def domain_name_1(url: str) -> str: """Extract the domain name from a URL by splitting on protocol and dots. Args: url: The full URL string. Returns: The domain name extracted from the URL. Examples: >>> domain_name_1("https://github.com/SaadBenn") 'github' """ full_domain_name = url.split("//")[-1] actual_domain = full_domain_name.split(".") if len(actual_domain) > 2: return actual_domain[1] return actual_domain[0] def domain_name_2(url: str) -> str: """Extract the domain name from a URL using chained splits. Args: url: The full URL string. Returns: The domain name extracted from the URL. Examples: >>> domain_name_2("http://google.com") 'google' """ return url.split("//")[-1].split("www.")[-1].split(".")[0]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/domain_extractor.py", "license": "MIT License", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/encode_decode.py
""" 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: O(n) """ from __future__ import annotations def encode(strs: str) -> str: """Encode a space-separated string into a length-prefixed format. Args: strs: A space-separated string of words. Returns: A single encoded string with length-prefixed words. Examples: >>> encode("keon is awesome") '4:keon2:is7:awesome' """ result = "" for word in strs.split(): result += str(len(word)) + ":" + word return result def decode(text: str) -> list[str]: """Decode a length-prefixed string back into a list of strings. Args: text: The encoded string with length-prefixed words. Returns: A list of the original decoded strings. Examples: >>> decode("4:keon2:is7:awesome") ['keon', 'is', 'awesome'] """ words: list[str] = [] index = 0 while index < len(text): colon_index = text.find(":", index) size = int(text[index:colon_index]) words.append(text[colon_index + 1 : colon_index + 1 + size]) index = colon_index + 1 + size return words
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/encode_decode.py", "license": "MIT License", "lines": 42, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/first_unique_char.py
""" First Unique Character in a String Given a string, find the first non-repeating character and return its index. If no unique character exists, return -1. Reference: https://leetcode.com/problems/first-unique-character-in-a-string/ Complexity: Time: O(n^2) worst case due to nested comparisons Space: O(n) for the banned list """ from __future__ import annotations def first_unique_char(text: str) -> int: """Find the index of the first non-repeating character in a string. Args: text: The input string to search. Returns: The index of the first unique character, or -1 if none exists. Examples: >>> first_unique_char("leetcode") 0 """ if len(text) == 1: return 0 banned: list[str] = [] for index in range(len(text)): if ( all(text[index] != text[other] for other in range(index + 1, len(text))) and text[index] not in banned ): return index else: banned.append(text[index]) return -1
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/first_unique_char.py", "license": "MIT License", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/fizzbuzz.py
""" FizzBuzz Return an array of numbers from 1 to N, replacing multiples of 3 with 'Fizz', multiples of 5 with 'Buzz', and multiples of both with 'FizzBuzz'. Reference: https://en.wikipedia.org/wiki/Fizz_buzz Complexity: Time: O(n) Space: O(n) """ from __future__ import annotations def fizzbuzz(number: int) -> list[int | str]: """Generate FizzBuzz sequence from 1 to number. Args: number: The upper bound of the sequence (inclusive). Returns: A list where multiples of 3 are 'Fizz', multiples of 5 are 'Buzz', multiples of both are 'FizzBuzz', and all others are the integer value. Raises: ValueError: If number is less than 1. TypeError: If number is None. Examples: >>> fizzbuzz(5) [1, 2, 'Fizz', 4, 'Buzz'] """ if number < 1: raise ValueError("n cannot be less than one") if number is None: raise TypeError("n cannot be None") result: list[int | str] = [] for value in range(1, number + 1): if value % 3 == 0 and value % 5 == 0: result.append("FizzBuzz") elif value % 3 == 0: result.append("Fizz") elif value % 5 == 0: result.append("Buzz") else: result.append(value) return result def fizzbuzz_with_helper_func(number: int) -> list[int | str]: """Generate FizzBuzz sequence using a helper function. Args: number: The upper bound of the sequence (inclusive). Returns: A list of FizzBuzz values from 1 to number. Examples: >>> fizzbuzz_with_helper_func(3) [1, 2, 'Fizz'] """ return [_fb(value) for value in range(1, number + 1)] def _fb(value: int) -> int | str: """Return the FizzBuzz value for a single number. Args: value: The number to evaluate. Returns: 'Fizz', 'Buzz', 'FizzBuzz', or the number itself. """ result = (value % 3 == 0) * "Fizz" + (value % 5 == 0) * "Buzz" return result if result != "" else value
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/fizzbuzz.py", "license": "MIT License", "lines": 59, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/group_anagrams.py
""" Group Anagrams Given an array of strings, group anagrams together. Anagrams are words that contain the same letters in a different order. Reference: https://leetcode.com/problems/group-anagrams/ Complexity: Time: O(n * k log k) where n is the number of strings and k is max length Space: O(n * k) """ from __future__ import annotations def group_anagrams(strings: list[str]) -> list[list[str]]: """Group a list of strings by anagram equivalence. Args: strings: A list of strings to group. Returns: A list of groups, where each group contains strings that are anagrams. Examples: >>> group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]) [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']] """ anagram_map: dict[str, int] = {} groups: list[list[str]] = [] group_index = 0 for word in strings: sorted_word = "".join(sorted(word)) if sorted_word not in anagram_map: anagram_map[sorted_word] = group_index group_index += 1 groups.append([]) groups[-1].append(word) else: groups[anagram_map[sorted_word]].append(word) return groups
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/group_anagrams.py", "license": "MIT License", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/int_to_roman.py
""" Integer to Roman Numeral Given an integer, convert it to a Roman numeral string. Input is guaranteed to be within the range from 1 to 3999. Reference: https://en.wikipedia.org/wiki/Roman_numerals Complexity: Time: O(1) since the input range is bounded Space: O(1) """ from __future__ import annotations def int_to_roman(num: int) -> str: """Convert an integer to its Roman numeral representation. Args: num: An integer between 1 and 3999. Returns: The Roman numeral string for the given integer. Examples: >>> int_to_roman(644) 'DCXLIV' """ thousands = ["", "M", "MM", "MMM"] hundreds = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"] tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"] ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"] return ( thousands[num // 1000] + hundreds[(num % 1000) // 100] + tens[(num % 100) // 10] + ones[num % 10] )
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/int_to_roman.py", "license": "MIT License", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/is_palindrome.py
""" 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 that create new strings, O(1) for two-pointer """ from __future__ import annotations from collections import deque from string import ascii_letters def is_palindrome(text: str) -> bool: """Check if a string is a palindrome using two pointers on the original. Args: text: The input string to check. Returns: True if the string is a palindrome, False otherwise. Examples: >>> is_palindrome("Otto") True """ left = 0 right = len(text) - 1 while left < right: while not text[left].isalnum(): left += 1 while not text[right].isalnum(): right -= 1 if text[left].lower() != text[right].lower(): return False left, right = left + 1, right - 1 return True def _remove_punctuation(text: str) -> str: """Remove punctuation, case sensitivity and spaces from a string. Args: text: The input string to clean. Returns: A lowercase string with only alphabetic characters. """ return "".join(char.lower() for char in text if char in ascii_letters) def _string_reverse(text: str) -> str: """Reverse a string using slicing. Args: text: The string to reverse. Returns: The reversed string. """ return text[::-1] def is_palindrome_reverse(text: str) -> bool: """Check if a string is a palindrome by comparing with its reverse. Args: text: The input string to check. Returns: True if the string is a palindrome, False otherwise. Examples: >>> is_palindrome_reverse("Otto") True """ text = _remove_punctuation(text) return text == _string_reverse(text) def is_palindrome_two_pointer(text: str) -> bool: """Check if a string is a palindrome using two pointers from both ends. Args: text: The input string to check. Returns: True if the string is a palindrome, False otherwise. Examples: >>> is_palindrome_two_pointer("Otto") True """ text = _remove_punctuation(text) for index in range(0, len(text) // 2): if text[index] != text[len(text) - index - 1]: return False return True def is_palindrome_stack(text: str) -> bool: """Check if a string is a palindrome using a stack. Args: text: The input string to check. Returns: True if the string is a palindrome, False otherwise. Examples: >>> is_palindrome_stack("Otto") True """ stack: list[str] = [] text = _remove_punctuation(text) for index in range(len(text) // 2, len(text)): stack.append(text[index]) return all(text[index] == stack.pop() for index in range(0, len(text) // 2)) def is_palindrome_deque(text: str) -> bool: """Check if a string is a palindrome using a deque. Args: text: The input string to check. Returns: True if the string is a palindrome, False otherwise. Examples: >>> is_palindrome_deque("Otto") True """ text = _remove_punctuation(text) character_deque: deque[str] = deque() for char in text: character_deque.appendleft(char) equal = True while len(character_deque) > 1 and equal: first = character_deque.pop() last = character_deque.popleft() if first != last: equal = False return equal
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/is_palindrome.py", "license": "MIT License", "lines": 112, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/is_rotated.py
""" 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) for brute force Space: O(n) """ from __future__ import annotations def is_rotated(first: str, second: str) -> bool: """Check if second is a rotation of first using string concatenation. Args: first: The original string. second: The string to check as a rotation. Returns: True if second is a rotation of first, False otherwise. Examples: >>> is_rotated("hello", "llohe") True """ if len(first) == len(second): return second in first + first else: return False def is_rotated_v1(first: str, second: str) -> bool: """Check if second is a rotation of first using brute force comparison. Args: first: The original string. second: The string to check as a rotation. Returns: True if second is a rotation of first, False otherwise. Examples: >>> is_rotated_v1("hello", "llohe") True """ if len(first) != len(second): return False if len(first) == 0: return True for offset in range(len(first)): if all( first[(offset + index) % len(first)] == second[index] for index in range(len(first)) ): return True return False
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/is_rotated.py", "license": "MIT License", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/judge_circle.py
""" 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 Space: O(1) """ from __future__ import annotations def judge_circle(moves: str) -> bool: """Determine whether a sequence of moves returns to the origin. Args: moves: A string of move characters ('U', 'D', 'L', 'R'). Returns: True if the robot ends at the starting position, False otherwise. Examples: >>> judge_circle("UD") True """ 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_counts["D"]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/judge_circle.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/knuth_morris_pratt.py
""" 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) where n = len(text), m = len(pattern) Space: O(m) for the prefix table """ from __future__ import annotations from collections.abc import Sequence def knuth_morris_pratt(text: Sequence, pattern: Sequence) -> list[int]: """Find all occurrences of pattern in text using the KMP algorithm. Args: text: The sequence to search in. pattern: The pattern sequence to search for. Returns: A list of starting indices where pattern occurs in text. Examples: >>> knuth_morris_pratt('hello there hero!', 'he') [0, 7, 12] """ 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_length): while match_length and pattern[index] != pattern[match_length]: match_length = prefix_table[match_length - 1] if pattern[index] == pattern[match_length]: match_length += 1 prefix_table[index] = match_length match_length = 0 matches: list[int] = [] for index in range(text_length): while match_length and text[index] != pattern[match_length]: match_length = prefix_table[match_length - 1] if text[index] == pattern[match_length]: match_length += 1 if match_length == pattern_length: matches.append(index - pattern_length + 1) match_length = prefix_table[match_length - 1] return matches
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/knuth_morris_pratt.py", "license": "MIT License", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/license_number.py
""" 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 key Space: O(n) """ from __future__ import annotations def license_number(key: str, group_size: int) -> str: """Reformat a license key string into groups of a given size. Args: key: The license key string with dashes. group_size: The desired size of each group. Returns: The reformatted license key with groups separated by dashes. Examples: >>> license_number("a-bc-dfd-df", 2) 'ab-cd-fd-df' """ 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) if (index + 1) % group_size == 0 and index != len(alphanumeric) - 1: result.append("-") return "".join(result[::-1])
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/license_number.py", "license": "MIT License", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
keon/algorithms:algorithms/string/longest_common_prefix.py
""" 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 sum of all characters in all strings Space: O(1) for iterative, O(m * log n) for divide and conquer """ from __future__ import annotations def _common_prefix(first: str, second: str) -> str: """Return the common prefix of two strings. Args: first: The first string. second: The second string. Returns: The common prefix shared by both strings. """ 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] return first[0:index] def longest_common_prefix_v1(strings: list[str]) -> str: """Find longest common prefix using horizontal scanning. Args: strings: A list of strings to compare. Returns: The longest common prefix, or empty string if none exists. Examples: >>> longest_common_prefix_v1(["flower", "flow", "flight"]) 'fl' """ if not strings: return "" result = strings[0] for index in range(len(strings)): result = _common_prefix(result, strings[index]) return result def longest_common_prefix_v2(strings: list[str]) -> str: """Find longest common prefix using vertical scanning. Args: strings: A list of strings to compare. Returns: The longest common prefix, or empty string if none exists. Examples: >>> longest_common_prefix_v2(["flower", "flow", "flight"]) 'fl' """ if not strings: return "" for index in range(len(strings[0])): for string in strings[1:]: if index == len(string) or string[index] != strings[0][index]: return strings[0][0:index] return strings[0] def longest_common_prefix_v3(strings: list[str]) -> str: """Find longest common prefix using divide and conquer. Args: strings: A list of strings to compare. Returns: The longest common prefix, or empty string if none exists. Examples: >>> longest_common_prefix_v3(["flower", "flow", "flight"]) 'fl' """ if not strings: return "" return _longest_common_recursive(strings, 0, len(strings) - 1) def _longest_common_recursive(strings: list[str], left: int, right: int) -> str: """Recursively find the longest common prefix using divide and conquer. Args: strings: The list of strings. left: The left index of the current partition. right: The right index of the current partition. Returns: The longest common prefix for the partition. """ if left == right: return strings[left] mid = (left + right) // 2 lcp_left = _longest_common_recursive(strings, left, mid) lcp_right = _longest_common_recursive(strings, mid + 1, right) return _common_prefix(lcp_left, lcp_right)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/longest_common_prefix.py", "license": "MIT License", "lines": 87, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/longest_palindromic_substring.py
""" 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(n) """ from __future__ import annotations def longest_palindrome(text: str) -> str: """Find the longest palindromic substring using Manacher's algorithm. Args: text: The input string to search. Returns: The longest palindromic substring. Examples: >>> longest_palindrome("cbbd") 'bb' """ 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)): if index < right_boundary and 2 * center - index < len(expanded): palindrome_radii[index] = min( right_boundary - index, palindrome_radii[2 * center - index], ) else: palindrome_radii[index] = 1 while ( palindrome_radii[index] + index < len(expanded) and index - palindrome_radii[index] >= 0 and expanded[index - palindrome_radii[index]] == expanded[index + palindrome_radii[index]] ): palindrome_radii[index] += 1 if index + palindrome_radii[index] > right_boundary: right_boundary = index + palindrome_radii[index] center = index if palindrome_radii[index] > best_length: best_index = index best_length = palindrome_radii[index] substring = expanded[ best_index - palindrome_radii[best_index] + 1 : best_index + palindrome_radii[best_index] ] return substring.replace("#", "")
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/longest_palindromic_substring.py", "license": "MIT License", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
keon/algorithms:algorithms/string/make_sentence.py
""" 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 exploration Space: O(n) recursion depth """ from __future__ import annotations count = 0 def make_sentence(text_piece: str, dictionaries: list[str]) -> bool: """Check if a string can be segmented into dictionary words and count ways. Updates the global ``count`` variable with the number of valid segmentations. Args: text_piece: The string to segment. dictionaries: A list of valid dictionary words. Returns: True if any segmentation is possible (always returns True). Examples: >>> make_sentence("applet", ["", "app", "let", "t", "apple", "applet"]) True """ 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 dictionaries and (suffix in dictionaries or make_sentence(suffix, dictionaries))): count += 1 return True
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/make_sentence.py", "license": "MIT License", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/merge_string_checker.py
""" 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 iterative Space: O(n) for recursion depth / stack """ from __future__ import annotations def is_merge_recursive(text: str, part1: str, part2: str) -> bool: """Check if text is an interleaving of part1 and part2 recursively. Args: text: The merged string to verify. part1: The first source string. part2: The second source string. Returns: True if text is a valid interleaving of part1 and part2. Examples: >>> is_merge_recursive("codewars", "cdw", "oears") True """ 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:], part2): return True return (text[0] == part2[0] and is_merge_recursive(text[1:], part1, part2[1:])) def is_merge_iterative(text: str, part1: str, part2: str) -> bool: """Check if text is an interleaving of part1 and part2 iteratively. Args: text: The merged string to verify. part1: The first source string. part2: The second source string. Returns: True if text is a valid interleaving of part1 and part2. Examples: >>> is_merge_iterative("codewars", "cdw", "oears") True """ tuple_list = [(text, part1, part2)] while tuple_list: string, first_part, second_part = tuple_list.pop() if string: if first_part and string[0] == first_part[0]: tuple_list.append((string[1:], first_part[1:], second_part)) if second_part and string[0] == second_part[0]: tuple_list.append((string[1:], first_part, second_part[1:])) else: if not first_part and not second_part: return True return False
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/merge_string_checker.py", "license": "MIT License", "lines": 56, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/min_distance.py
""" 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: O(2^n) for recursive LCS, O(m * n) for DP approach Space: O(m * n) for DP table """ from __future__ import annotations def min_distance(word1: str, word2: str) -> int: """Find minimum deletions to make two words equal via recursive LCS. Args: word1: The first word. word2: The second word. Returns: The minimum number of deletion steps. Examples: >>> min_distance("sea", "eat") 2 """ return len(word1) + len(word2) - 2 * _lcs(word1, word2, len(word1), len(word2)) def _lcs(word1: str, word2: str, length1: int, length2: int) -> int: """Compute the length of the longest common subsequence recursively. Args: word1: The first word. word2: The second word. length1: Current length to consider in word1. length2: Current length to consider in word2. Returns: The length of the longest common subsequence. """ if length1 == 0 or length2 == 0: return 0 if word1[length1 - 1] == word2[length2 - 1]: return 1 + _lcs(word1, word2, length1 - 1, length2 - 1) return max( _lcs(word1, word2, length1 - 1, length2), _lcs(word1, word2, length1, length2 - 1), ) def min_distance_dp(word1: str, word2: str) -> int: """Find minimum deletions to make two words equal using dynamic programming. Args: word1: The first word. word2: The second word. Returns: The minimum number of deletion steps. Examples: >>> min_distance_dp("sea", "eat") 2 """ rows, cols = len(word1) + 1, len(word2) + 1 table = [[0 for _ in range(cols)] for _ in range(rows)] if rows == cols: for index in range(1, rows): table[index][0], table[0][index] = index, index else: for index in range(rows): table[index][0] = index for index in range(cols): table[0][index] = index for row in range(1, rows): for col in range(1, cols): if word1[row - 1] == word2[col - 1]: table[row][col] = table[row - 1][col - 1] else: table[row][col] = min(table[row - 1][col], table[row][col - 1]) + 1 return table[len(word1)][len(word2)]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/min_distance.py", "license": "MIT License", "lines": 68, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/multiply_strings.py
""" Multiply Strings Given two non-negative integers represented as strings, return their product as a string without using built-in BigInteger or direct integer conversion. Reference: https://leetcode.com/problems/multiply-strings/ Complexity: Time: O(m * n) where m, n are the lengths of the two numbers Space: O(m + n) """ from __future__ import annotations def multiply(num1: str, num2: str) -> str: """Multiply two numbers represented as strings. Args: num1: The first number as a string. num2: The second number as a string. Returns: The product of the two numbers as a string. Examples: >>> multiply("23", "23") '529' """ intermediate: list[int] = [] zero = ord("0") position_i = 1 for digit_i in reversed(num1): position_j = 1 accumulator = 0 for digit_j in reversed(num2): product = ( (ord(digit_i) - zero) * (ord(digit_j) - zero) * position_j * position_i ) position_j *= 10 accumulator += product position_i *= 10 intermediate.append(accumulator) return str(sum(intermediate))
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/multiply_strings.py", "license": "MIT License", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/one_edit_distance.py
""" 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 the shorter string Space: O(n) for string slicing """ from __future__ import annotations def is_one_edit(source: str, target: str) -> bool: """Check if two strings are exactly one edit apart using slicing. Args: source: The first string. target: The second string. Returns: True if the strings are exactly one edit apart, False otherwise. Examples: >>> is_one_edit("abc", "abd") True """ 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[index]: return ( source[index + 1 :] == target[index + 1 :] or source[index:] == target[index + 1 :] ) return True def is_one_edit2(source: str, target: str) -> bool: """Check if two strings are exactly one edit apart using modification. Args: source: The first string. target: The second string. Returns: True if the strings are exactly one edit apart, False otherwise. Examples: >>> is_one_edit2("abc", "abd") True """ source_length, target_length = len(source), len(target) if source_length > target_length: return is_one_edit2(target, source) if len(target) - len(source) > 1 or target == source: return False for index in range(len(source)): if source[index] != target[index]: if source_length == target_length: source = source[:index] + target[index] + source[index + 1 :] else: source = source[:index] + target[index] + source[index:] break return source == target or source == target[:-1]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/one_edit_distance.py", "license": "MIT License", "lines": 56, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/panagram.py
""" 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 set is bounded at 26 """ from __future__ import annotations from string import ascii_lowercase def panagram(string: str) -> bool: """Check if the input string is an English panagram. Args: string: A sentence to check. Returns: True if the string contains every English letter, False otherwise. Examples: >>> panagram("the quick brown fox jumps over the lazy dog") True """ letters = set(ascii_lowercase) for char in string: letters.discard(char.lower()) return len(letters) == 0
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/panagram.py", "license": "MIT License", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/rabin_karp.py
""" 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) average, O(n * m) worst case Space: O(1) """ from __future__ import annotations class RollingHash: """A rolling hash implementation for the Rabin-Karp algorithm. Args: text: The text to compute the hash over. window_size: The size of the hash window. """ 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) * ( 26 ** (window_size - index - 1) ) self.window_start = 0 self.window_end = window_size def move_window(self) -> None: """Slide the hash window one position to the right.""" if self.window_end <= len(self.text) - 1: self.hash -= (ord(self.text[self.window_start]) - ord("a") + 1) * 26 ** ( self.window_size - 1 ) self.hash *= 26 self.hash += ord(self.text[self.window_end]) - ord("a") + 1 self.window_start += 1 self.window_end += 1 def window_text(self) -> str: """Return the current text within the hash window. Returns: The substring currently covered by the rolling hash window. """ return self.text[self.window_start : self.window_end] def rabin_karp(word: str, text: str) -> int | None: """Find the first occurrence of word in text using the Rabin-Karp algorithm. Args: word: The pattern to search for. text: The text to search in. Returns: The index of the first occurrence, or None if not found. Examples: >>> rabin_karp("abc", "zsnabckfkd") 3 """ if word == "" or text == "": return None if len(word) > len(text): return None rolling_hash = RollingHash(text, len(word)) word_hash = RollingHash(word, len(word)) for _ in range(len(text) - len(word) + 1): if (rolling_hash.hash == word_hash.hash and rolling_hash.window_text() == word): return rolling_hash.window_start rolling_hash.move_window() return None
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/rabin_karp.py", "license": "MIT License", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/repeat_string.py
""" 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(A), m = len(B) Space: O(n * (m/n + 2)) """ from __future__ import annotations def repeat_string(base: str, target: str) -> int: """Find minimum repetitions of base needed to contain target as a substring. Args: base: The string to repeat. target: The string that should appear as a substring. Returns: The minimum number of repetitions, or -1 if not possible. Examples: >>> repeat_string("abcd", "cdabcdab") 3 """ 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 break repetition_count = repetition_count + 1 return repetition_count
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/repeat_string.py", "license": "MIT License", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/repeat_substring.py
""" Repeated Substring Pattern Given a non-empty string, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. Reference: https://leetcode.com/problems/repeated-substring-pattern/ Complexity: Time: O(n) for the string containment check Space: O(n) """ from __future__ import annotations def repeat_substring(text: str) -> bool: """Check if a string is composed of a repeated substring pattern. Args: text: The input string to check. Returns: True if the string is a repeated pattern, False otherwise. Examples: >>> repeat_substring("abab") True """ doubled = (text + text)[1:-1] return text in doubled
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/repeat_substring.py", "license": "MIT License", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/reverse_string.py
""" 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 Space: O(n) for all approaches, O(log n) stack for recursive """ from __future__ import annotations def recursive(text: str) -> str: """Reverse a string using a recursive divide-and-conquer approach. Args: text: The string to reverse. Returns: The reversed string. Examples: >>> recursive("hello there") 'ereht olleh' """ length = len(text) if length < 2: return text return recursive(text[length // 2 :]) + recursive(text[: length // 2]) def iterative(text: str) -> str: """Reverse a string using iterative character swapping. Args: text: The string to reverse. Returns: The reversed string. Examples: >>> iterative("hello there") 'ereht olleh' """ characters = list(text) left, right = 0, len(text) - 1 while left < right: characters[left], characters[right] = ( characters[right], characters[left], ) left += 1 right -= 1 return "".join(characters) def pythonic(text: str) -> str: """Reverse a string using the built-in reversed function. Args: text: The string to reverse. Returns: The reversed string. Examples: >>> pythonic("hello there") 'ereht olleh' """ characters = list(reversed(text)) return "".join(characters) def ultra_pythonic(text: str) -> str: """Reverse a string using slice notation. Args: text: The string to reverse. Returns: The reversed string. Examples: >>> ultra_pythonic("hello there") 'ereht olleh' """ return text[::-1]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/reverse_string.py", "license": "MIT License", "lines": 67, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/reverse_vowel.py
""" 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) for the character list """ from __future__ import annotations def reverse_vowel(text: str) -> str: """Reverse only the vowels in a string. Args: text: The input string. Returns: A new string with vowels reversed. Examples: >>> reverse_vowel("hello") 'holle' """ 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] not in vowels: right -= 1 characters[left], characters[right] = ( characters[right], characters[left], ) left, right = left + 1, right - 1 return "".join(characters)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/reverse_vowel.py", "license": "MIT License", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/reverse_words.py
""" Reverse Words in a String Given a string, reverse the order of words. Leading and trailing spaces are trimmed and words are separated by single spaces. Reference: https://leetcode.com/problems/reverse-words-in-a-string/ Complexity: Time: O(n) where n is the length of the string Space: O(n) """ from __future__ import annotations def _reverse_list(array: list[str], left: int, right: int) -> None: """Reverse a portion of a list in place. Args: array: The list to modify. left: The starting index. right: The ending index. """ while left < right: array[left], array[right] = array[right], array[left] left += 1 right -= 1 def reverse_words(string: str) -> str: """Reverse the order of words in a string. Args: string: The input string of words. Returns: A string with the word order reversed. Examples: >>> reverse_words("I am keon kim and I like pizza") 'pizza like I and kim keon am I' """ words = string.strip().split() word_count = len(words) _reverse_list(words, 0, word_count - 1) return " ".join(words)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/reverse_words.py", "license": "MIT License", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/roman_to_int.py
""" 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 Space: O(1) """ from __future__ import annotations def roman_to_int(text: str) -> int: """Convert a Roman numeral string to an integer. Args: text: A valid Roman numeral string. Returns: The integer value of the Roman numeral. Examples: >>> roman_to_int("DCXXI") 621 """ 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_values[text[index + 1]]: number -= roman_values[text[index]] else: number += roman_values[text[index]] return number + roman_values[text[-1]]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/roman_to_int.py", "license": "MIT License", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/rotate.py
""" 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 __future__ import annotations def rotate(text: str, positions: int) -> str: """Rotate a string left by k positions using repeated string approach. Args: text: The string to rotate. positions: The number of positions to rotate left. Returns: The rotated string. Examples: >>> rotate("hello", 2) 'llohe' """ 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(string: str, positions: int) -> str: """Rotate a string left by k positions using modular arithmetic. Args: string: The string to rotate. positions: The number of positions to rotate left. Returns: The rotated string. Examples: >>> rotate_alt("hello", 2) 'llohe' """ positions = positions % len(string) return string[positions:] + string[:positions]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/rotate.py", "license": "MIT License", "lines": 39, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/strip_url_params.py
""" Strip URL Parameters Remove duplicate query string parameters from a URL and optionally remove specified parameters. Three approaches of increasing Pythonic style. Reference: https://en.wikipedia.org/wiki/Query_string Complexity: Time: O(n) where n is the length of the URL Space: O(n) """ from __future__ import annotations import urllib import urllib.parse from collections import defaultdict def strip_url_params1(url: str, params_to_strip: list[str] | None = None) -> str: """Remove duplicate and specified URL parameters using manual parsing. Args: url: The URL string to process. params_to_strip: Optional list of parameter names to remove. Returns: The URL with duplicate and specified parameters removed. Examples: >>> strip_url_params1("www.saadbenn.com?a=1&b=2&a=2") 'www.saadbenn.com?a=1&b=2' """ if not params_to_strip: params_to_strip = [] if url: result = "" tokens = url.split("?") domain = tokens[0] query_string = tokens[-1] result += domain if len(tokens) > 1: result += "?" if not query_string: return url else: key_value_pairs: list[str] = [] fragment = "" for char in query_string: if char.isdigit(): key_value_pairs.append(fragment + char) fragment = "" else: fragment += char seen: dict[str, int] = defaultdict(int) for pair in key_value_pairs: token_parts = pair.split("=") if token_parts[0]: length = len(token_parts[0]) if length == 1: if token_parts and (token_parts[0] not in seen): if params_to_strip: if token_parts[0] != params_to_strip[0]: seen[token_parts[0]] = token_parts[1] result = ( result + token_parts[0] + "=" + token_parts[1] ) else: if token_parts[0] not in seen: seen[token_parts[0]] = token_parts[1] result = ( result + token_parts[0] + "=" + token_parts[1] ) else: check = token_parts[0] letter = check[1] if token_parts and (letter not in seen): if params_to_strip: if letter != params_to_strip[0]: seen[letter] = token_parts[1] result = ( result + token_parts[0] + "=" + token_parts[1] ) else: if letter not in seen: seen[letter] = token_parts[1] result = ( result + token_parts[0] + "=" + token_parts[1] ) return result def strip_url_params2(url: str, param_to_strip: list[str] | None = None) -> str: """Remove duplicate and specified URL parameters using list operations. Args: url: The URL string to process. param_to_strip: Optional list of parameter names to remove. Returns: The URL with duplicate and specified parameters removed. Examples: >>> strip_url_params2("www.saadbenn.com?a=1&b=2&a=2") 'www.saadbenn.com?a=1&b=2' """ if param_to_strip is None: param_to_strip = [] if "?" not in url: return url queries = (url.split("?")[1]).split("&") query_keys = [query[0] for query in queries] for index in range(len(query_keys) - 1, 0, -1): if ( query_keys[index] in param_to_strip or query_keys[index] in query_keys[0:index] ): queries.pop(index) return url.split("?")[0] + "?" + "&".join(queries) def strip_url_params3(url: str, strip: list[str] | None = None) -> str: """Remove duplicate and specified URL parameters using urllib. Args: url: The URL string to process. strip: Optional list of parameter names to remove. Returns: The URL with duplicate and specified parameters removed. Examples: >>> strip_url_params3("www.saadbenn.com?a=1&b=2&a=2") 'www.saadbenn.com?a=1&b=2' """ if not strip: strip = [] parsed = urllib.parse.urlparse(url) query = urllib.parse.parse_qs(parsed.query) query = {key: values[0] for key, values in query.items() if key not in strip} query_string = urllib.parse.urlencode(query) new_parsed = parsed._replace(query=query_string) return new_parsed.geturl()
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/strip_url_params.py", "license": "MIT License", "lines": 124, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
keon/algorithms:algorithms/string/strong_password.py
""" Strong Password Checker Given a password string, determine the minimum number of characters that must be added to make it strong. A strong password has at least 6 characters, a digit, a lowercase letter, an uppercase letter, and a special character. Reference: https://www.hackerrank.com/challenges/strong-password/problem Complexity: Time: O(n) where n is the length of the password Space: O(1) """ from __future__ import annotations def strong_password(length: int, password: str) -> int: """Calculate minimum characters to add for a strong password. Args: length: The current length of the password. password: The password string to evaluate. Returns: The minimum number of characters to add. Examples: >>> strong_password(3, "Ab1") 3 """ missing_types = 0 if not any(char.isdigit() for char in password): missing_types += 1 if not any(char.islower() for char in password): missing_types += 1 if not any(char.isupper() for char in password): missing_types += 1 if not any(char in "!@#$%^&*()-+" for char in password): missing_types += 1 return max(missing_types, 6 - length)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/strong_password.py", "license": "MIT License", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/text_justification.py
""" Text Justification Given an array of words and a max width, format the text such that each line has exactly max_width characters and is fully justified. Extra spaces are distributed as evenly as possible with left slots getting more. Reference: https://leetcode.com/problems/text-justification/ Complexity: Time: O(n) where n is the total number of characters Space: O(n) """ from __future__ import annotations def text_justification(words: list[str], max_width: int) -> list[str]: """Justify text to a fixed width with evenly distributed spaces. Args: words: A list of words to justify. max_width: The maximum width of each line. Returns: A list of fully justified strings. Raises: ValueError: If any word is longer than max_width. Examples: >>> text_justification(["What", "must", "be"], 16) ['What must be'] """ result: list[str] = [] row_length = 0 row_words: list[str] = [] index = 0 is_first_word = True while index < len(words): while row_length <= max_width and index < len(words): if len(words[index]) > max_width: raise ValueError( "there exists word whose length is larger than max_width" ) tentative_length = row_length row_words.append(words[index]) tentative_length += len(words[index]) if not is_first_word: tentative_length += 1 if tentative_length > max_width: row_words.pop() break row_length = tentative_length index += 1 is_first_word = False row = "" if index == len(words): for word in row_words: row += word + " " row = row[:-1] row += " " * (max_width - len(row)) elif len(row_words) != 1: extra_spaces = max_width - row_length spaces_per_gap = extra_spaces // (len(row_words) - 1) remaining_spaces = extra_spaces - spaces_per_gap * (len(row_words) - 1) for word_index in range(len(row_words)): row += row_words[word_index] if word_index != len(row_words) - 1: row += " " * (1 + spaces_per_gap) if remaining_spaces > 0: row += " " remaining_spaces -= 1 else: row += row_words[0] row += " " * (max_width - len(row)) result.append(row) row_length = 0 row_words = [] is_first_word = True return result
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/text_justification.py", "license": "MIT License", "lines": 71, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
keon/algorithms:algorithms/string/unique_morse.py
""" 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 word length Space: O(n) """ from __future__ import annotations _MORSE_CODE = { "a": ".-", "b": "-...", "c": "-.-.", "d": "-..", "e": ".", "f": "..-.", "g": "--.", "h": "....", "i": "..", "j": ".---", "k": "-.-", "l": ".-..", "m": "--", "n": "-.", "o": "---", "p": ".--.", "q": "--.-", "r": ".-.", "s": "...", "t": "-", "u": "..-", "v": "...-", "w": ".--", "x": "-..-", "y": "-.--", "z": "--..", } def convert_morse_word(word: str) -> str: """Convert a word to its Morse code representation. Args: word: The word to convert (case-insensitive). Returns: The Morse code string for the word. Examples: >>> convert_morse_word("gin") '--...-.' """ morse_word = "" word = word.lower() for char in word: morse_word = morse_word + _MORSE_CODE[char] return morse_word def unique_morse(words: list[str]) -> int: """Count the number of unique Morse code transformations. Args: words: A list of words to transform and count. Returns: The number of distinct Morse code representations. Examples: >>> unique_morse(["gin", "zen", "gig", "msg"]) 2 """ unique_transformations: list[str] = [] for word in words: morse_word = convert_morse_word(word) if morse_word not in unique_transformations: unique_transformations.append(morse_word) return len(unique_transformations)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/unique_morse.py", "license": "MIT License", "lines": 69, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
keon/algorithms:algorithms/string/validate_coordinates.py
""" Validate Coordinates Validate if given parameters are valid geographical coordinates. Latitude must be between -90 and 90, longitude between -180 and 180. Reference: https://en.wikipedia.org/wiki/Geographic_coordinate_system Complexity: Time: O(n) where n is the length of the coordinate string Space: O(1) """ from __future__ import annotations import re def is_valid_coordinates_0(coordinates: str) -> bool: """Validate coordinates by character checking and parsing. Args: coordinates: A string of the form "lat, lng". Returns: True if the coordinates are valid, False otherwise. Examples: >>> is_valid_coordinates_0("-23, 25") True """ for char in coordinates: if not (char.isdigit() or char in ["-", ".", ",", " "]): return False parts = coordinates.split(", ") if len(parts) != 2: return False try: latitude = float(parts[0]) longitude = float(parts[1]) except ValueError: return False return -90 <= latitude <= 90 and -180 <= longitude <= 180 def is_valid_coordinates_1(coordinates: str) -> bool: """Validate coordinates by splitting and converting to floats. Args: coordinates: A string of the form "lat, lng". Returns: True if the coordinates are valid, False otherwise. Examples: >>> is_valid_coordinates_1("43.91343345, 143") True """ try: latitude, longitude = [ abs(float(part)) for part in coordinates.split(",") if "e" not in part ] except ValueError: return False return latitude <= 90 and longitude <= 180 def is_valid_coordinates_regular_expression(coordinates: str) -> bool: """Validate coordinates using a regular expression. Args: coordinates: A string of the form "lat, lng". Returns: True if the coordinates are valid, False otherwise. Examples: >>> is_valid_coordinates_regular_expression("4, -3") True """ return bool( re.match( r"-?(\d|[1-8]\d|90)\.?\d*, -?(\d|[1-9]\d|1[0-7]\d|180)\.?\d*$", coordinates, ) )
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/validate_coordinates.py", "license": "MIT License", "lines": 66, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/string/word_squares.py
""" Word Squares Given a set of words (without duplicates), find all word squares that can be built from them. A word square reads the same horizontally and vertically. Reference: https://leetcode.com/problems/word-squares/ Complexity: Time: O(n * 26^L) where n is the number of words, L is word length Space: O(n * L) for the prefix map """ from __future__ import annotations import collections def word_squares(words: list[str]) -> list[list[str]]: """Find all valid word squares from a list of same-length words. Args: words: A list of words, all having the same length. Returns: A list of word squares, where each square is a list of words. Examples: >>> word_squares(["area", "lead", "wall", "lady", "ball"]) [['wall', 'area', 'lead', 'lady'], ['ball', 'area', 'lead', 'lady']] """ word_length = len(words[0]) prefix_map: dict[str, list[str]] = collections.defaultdict(list) for word in words: for index in range(word_length): prefix_map[word[:index]].append(word) def _build(square: list[str]) -> None: if len(square) == word_length: squares.append(square) return prefix = "" for row in range(len(square)): prefix += square[row][len(square)] for word in prefix_map[prefix]: _build(square + [word]) squares: list[list[str]] = [] for word in words: _build([word]) return squares
{ "repo_id": "keon/algorithms", "file_path": "algorithms/string/word_squares.py", "license": "MIT License", "lines": 39, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:tests/test_backtracking.py
import unittest from algorithms.backtracking import ( add_operators, anagram, array_sum_combinations, combination_sum, find_words, generate_abbreviations, generate_parenthesis_v1, generate_parenthesis_v2, get_factors, letter_combinations, palindromic_substrings, pattern_match, permute, permute_iter, permute_recursive, permute_unique, recursive_get_factors, subsets, subsets_unique, subsets_v2, unique_array_sum_combinations, ) class TestAddOperator(unittest.TestCase): def test_add_operators(self): # "123", 6 -> ["1+2+3", "1*2*3"] s = "123" target = 6 self.assertEqual(add_operators(s, target), ["1+2+3", "1*2*3"]) # "232", 8 -> ["2*3+2", "2+3*2"] s = "232" target = 8 self.assertEqual(add_operators(s, target), ["2+3*2", "2*3+2"]) s = "123045" target = 3 answer = [ "1+2+3*0*4*5", "1+2+3*0*45", "1+2-3*0*4*5", "1+2-3*0*45", "1-2+3+0-4+5", "1-2+3-0-4+5", "1*2+3*0-4+5", "1*2-3*0-4+5", "1*23+0-4*5", "1*23-0-4*5", "12+3*0-4-5", "12-3*0-4-5", ] self.assertEqual(add_operators(s, target), answer) class TestPermuteAndAnagram(unittest.TestCase): def test_permute(self): perms = ["abc", "bac", "bca", "acb", "cab", "cba"] self.assertEqual(perms, permute("abc")) def test_permute_iter(self): it = permute_iter("abc") perms = ["abc", "bac", "bca", "acb", "cab", "cba"] for i in range(len(perms)): self.assertEqual(perms[i], next(it)) def test_angram(self): self.assertTrue(anagram("apple", "pleap")) self.assertFalse(anagram("apple", "cherry")) class TestArrayCombinationSum(unittest.TestCase): def test_array_sum_combinations(self): a = [1, 2, 3, 3] b = [2, 3, 3, 4] c = [2, 3, 3, 4] target = 7 answer = [ [1, 2, 4], [1, 3, 3], [1, 3, 3], [1, 3, 3], [1, 3, 3], [1, 4, 2], [2, 2, 3], [2, 2, 3], [2, 3, 2], [2, 3, 2], [3, 2, 2], [3, 2, 2], ] answer.sort() self.assertListEqual(sorted(array_sum_combinations(a, b, c, target)), answer) def test_unique_array_sum_combinations(self): a = [1, 2, 3, 3] b = [2, 3, 3, 4] c = [2, 3, 3, 4] target = 7 answer = [(2, 3, 2), (3, 2, 2), (1, 2, 4), (1, 4, 2), (2, 2, 3), (1, 3, 3)] answer.sort() self.assertListEqual( sorted(unique_array_sum_combinations(a, b, c, target)), answer ) class TestCombinationSum(unittest.TestCase): def check_sum(self, nums, target): if sum(nums) == target: return (True, nums) else: return (False, nums) def test_combination_sum(self): candidates1 = [2, 3, 6, 7] target1 = 7 answer1 = [[2, 2, 3], [7]] self.assertEqual(combination_sum(candidates1, target1), answer1) candidates2 = [2, 3, 5] target2 = 8 answer2 = [[2, 2, 2, 2], [2, 3, 3], [3, 5]] self.assertEqual(combination_sum(candidates2, target2), answer2) class TestFactorCombinations(unittest.TestCase): def test_get_factors(self): target1 = 32 answer1 = [[2, 16], [2, 2, 8], [2, 2, 2, 4], [2, 2, 2, 2, 2], [2, 4, 4], [4, 8]] self.assertEqual(sorted(get_factors(target1)), sorted(answer1)) target2 = 12 answer2 = [[2, 6], [2, 2, 3], [3, 4]] self.assertEqual(sorted(get_factors(target2)), sorted(answer2)) self.assertEqual(sorted(get_factors(1)), []) self.assertEqual(sorted(get_factors(37)), []) def test_recursive_get_factors(self): target1 = 32 answer1 = [[2, 16], [2, 2, 8], [2, 2, 2, 4], [2, 2, 2, 2, 2], [2, 4, 4], [4, 8]] self.assertEqual(sorted(recursive_get_factors(target1)), sorted(answer1)) target2 = 12 answer2 = [[2, 6], [2, 2, 3], [3, 4]] self.assertEqual(sorted(recursive_get_factors(target2)), sorted(answer2)) self.assertEqual(sorted(recursive_get_factors(1)), []) self.assertEqual(sorted(recursive_get_factors(37)), []) class TestFindWords(unittest.TestCase): def test_normal(self): board = [ ["o", "a", "a", "n"], ["e", "t", "a", "e"], ["i", "h", "k", "r"], ["i", "f", "l", "v"], ] words = ["oath", "pea", "eat", "rain"] result = find_words(board, words) test_result = ["oath", "eat"] self.assertEqual(sorted(result), sorted(test_result)) def test_none(self): board = [ ["o", "a", "a", "n"], ["e", "t", "a", "e"], ["i", "h", "k", "r"], ["i", "f", "l", "v"], ] words = ["chicken", "nugget", "hello", "world"] self.assertEqual(find_words(board, words), []) def test_empty(self): board = [] words = [] self.assertEqual(find_words(board, words), []) def test_uneven(self): board = [["o", "a", "a", "n"], ["e", "t", "a", "e"]] words = ["oath", "pea", "eat", "rain"] self.assertEqual(find_words(board, words), ["eat"]) def test_repeat(self): board = [["a", "a", "a"], ["a", "a", "a"], ["a", "a", "a"]] words = ["a", "aa", "aaa", "aaaa", "aaaaa"] self.assertTrue(len(find_words(board, words)) == 5) class TestGenerateAbbreviations(unittest.TestCase): def test_generate_abbreviations(self): word1 = "word" answer1 = [ "word", "wor1", "wo1d", "wo2", "w1rd", "w1r1", "w2d", "w3", "1ord", "1or1", "1o1d", "1o2", "2rd", "2r1", "3d", "4", ] self.assertEqual(sorted(generate_abbreviations(word1)), sorted(answer1)) word2 = "hello" answer2 = [ "hello", "hell1", "hel1o", "hel2", "he1lo", "he1l1", "he2o", "he3", "h1llo", "h1ll1", "h1l1o", "h1l2", "h2lo", "h2l1", "h3o", "h4", "1ello", "1ell1", "1el1o", "1el2", "1e1lo", "1e1l1", "1e2o", "1e3", "2llo", "2ll1", "2l1o", "2l2", "3lo", "3l1", "4o", "5", ] self.assertEqual(sorted(generate_abbreviations(word2)), sorted(answer2)) class TestPatternMatch(unittest.TestCase): def test_pattern_match(self): pattern1 = "abab" string1 = "redblueredblue" pattern2 = "aaaa" string2 = "asdasdasdasd" pattern3 = "aabb" string3 = "xyzabcxzyabc" self.assertTrue(pattern_match(pattern1, string1)) self.assertTrue(pattern_match(pattern2, string2)) self.assertFalse(pattern_match(pattern3, string3)) class TestGenerateParenthesis(unittest.TestCase): def test_generate_parenthesis(self): self.assertEqual(generate_parenthesis_v1(2), ["()()", "(())"]) self.assertEqual( generate_parenthesis_v1(3), ["()()()", "()(())", "(())()", "(()())", "((()))"], ) self.assertEqual(generate_parenthesis_v2(2), ["(())", "()()"]) self.assertEqual( generate_parenthesis_v2(3), ["((()))", "(()())", "(())()", "()(())", "()()()"], ) class TestLetterCombinations(unittest.TestCase): def test_letter_combinations(self): digit1 = "23" answer1 = ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"] self.assertEqual(sorted(letter_combinations(digit1)), sorted(answer1)) digit2 = "34" answer2 = ["dg", "dh", "di", "eg", "eh", "ei", "fg", "fh", "fi"] self.assertEqual(sorted(letter_combinations(digit2)), sorted(answer2)) class TestPalindromicSubstrings(unittest.TestCase): def test_palindromic_substrings(self): string1 = "abc" answer1 = [["a", "b", "c"]] self.assertEqual(palindromic_substrings(string1), sorted(answer1)) string2 = "abcba" answer2 = [["abcba"], ["a", "bcb", "a"], ["a", "b", "c", "b", "a"]] self.assertEqual(sorted(palindromic_substrings(string2)), sorted(answer2)) string3 = "abcccba" answer3 = [ ["abcccba"], ["a", "bcccb", "a"], ["a", "b", "ccc", "b", "a"], ["a", "b", "cc", "c", "b", "a"], ["a", "b", "c", "cc", "b", "a"], ["a", "b", "c", "c", "c", "b", "a"], ] self.assertEqual(sorted(palindromic_substrings(string3)), sorted(answer3)) class TestPermuteUnique(unittest.TestCase): def test_permute_unique(self): nums1 = [1, 1, 2] answer1 = [[2, 1, 1], [1, 2, 1], [1, 1, 2]] self.assertEqual(sorted(permute_unique(nums1)), sorted(answer1)) nums2 = [1, 2, 1, 3] answer2 = [ [3, 1, 2, 1], [1, 3, 2, 1], [1, 2, 3, 1], [1, 2, 1, 3], [3, 2, 1, 1], [2, 3, 1, 1], [2, 1, 3, 1], [2, 1, 1, 3], [3, 1, 1, 2], [1, 3, 1, 2], [1, 1, 3, 2], [1, 1, 2, 3], ] self.assertEqual(sorted(permute_unique(nums2)), sorted(answer2)) nums3 = [1, 2, 3] answer3 = [[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2], [1, 2, 3]] self.assertEqual(sorted(permute_unique(nums3)), sorted(answer3)) class TestPermute(unittest.TestCase): def test_permute(self): nums1 = [1, 2, 3, 4] answer1 = [ [1, 2, 3, 4], [2, 1, 3, 4], [2, 3, 1, 4], [2, 3, 4, 1], [1, 3, 2, 4], [3, 1, 2, 4], [3, 2, 1, 4], [3, 2, 4, 1], [1, 3, 4, 2], [3, 1, 4, 2], [3, 4, 1, 2], [3, 4, 2, 1], [1, 2, 4, 3], [2, 1, 4, 3], [2, 4, 1, 3], [2, 4, 3, 1], [1, 4, 2, 3], [4, 1, 2, 3], [4, 2, 1, 3], [4, 2, 3, 1], [1, 4, 3, 2], [4, 1, 3, 2], [4, 3, 1, 2], [4, 3, 2, 1], ] self.assertEqual(sorted(permute(nums1)), sorted(answer1)) nums2 = [1, 2, 3] answer2 = [[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2], [1, 2, 3]] self.assertEqual(sorted(permute(nums2)), sorted(answer2)) def test_permute_recursive(self): nums1 = [1, 2, 3, 4] answer1 = [ [1, 2, 3, 4], [2, 1, 3, 4], [2, 3, 1, 4], [2, 3, 4, 1], [1, 3, 2, 4], [3, 1, 2, 4], [3, 2, 1, 4], [3, 2, 4, 1], [1, 3, 4, 2], [3, 1, 4, 2], [3, 4, 1, 2], [3, 4, 2, 1], [1, 2, 4, 3], [2, 1, 4, 3], [2, 4, 1, 3], [2, 4, 3, 1], [1, 4, 2, 3], [4, 1, 2, 3], [4, 2, 1, 3], [4, 2, 3, 1], [1, 4, 3, 2], [4, 1, 3, 2], [4, 3, 1, 2], [4, 3, 2, 1], ] self.assertEqual(sorted(permute_recursive(nums1)), sorted(answer1)) nums2 = [1, 2, 3] answer2 = [[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2], [1, 2, 3]] self.assertEqual(sorted(permute_recursive(nums2)), sorted(answer2)) class TestSubsetsUnique(unittest.TestCase): def test_subsets_unique(self): nums1 = [1, 2, 2] answer1 = [(1, 2), (1,), (1, 2, 2), (2,), (), (2, 2)] self.assertEqual(sorted(subsets_unique(nums1)), sorted(answer1)) nums2 = [1, 2, 3, 4] answer2 = [ (1, 2), (1, 3), (1, 2, 3, 4), (1,), (2,), (3,), (1, 4), (1, 2, 3), (4,), (), (2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), (3, 4), (2, 4), ] self.assertEqual(sorted(subsets_unique(nums2)), sorted(answer2)) class TestSubsets(unittest.TestCase): def test_subsets(self): nums1 = [1, 2, 3] answer1 = [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []] self.assertEqual(sorted(subsets(nums1)), sorted(answer1)) nums2 = [1, 2, 3, 4] answer2 = [ [1, 2, 3, 4], [1, 2, 3], [1, 2, 4], [1, 2], [1, 3, 4], [1, 3], [1, 4], [1], [2, 3, 4], [2, 3], [2, 4], [2], [3, 4], [3], [4], [], ] self.assertEqual(sorted(subsets(nums2)), sorted(answer2)) def test_subsets_v2(self): nums1 = [1, 2, 3] answer1 = [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []] self.assertEqual(sorted(subsets_v2(nums1)), sorted(answer1)) nums2 = [1, 2, 3, 4] answer2 = [ [1, 2, 3, 4], [1, 2, 3], [1, 2, 4], [1, 2], [1, 3, 4], [1, 3], [1, 4], [1], [2, 3, 4], [2, 3], [2, 4], [2], [3, 4], [3], [4], [], ] self.assertEqual(sorted(subsets_v2(nums2)), sorted(answer2)) if __name__ == "__main__": unittest.main()
{ "repo_id": "keon/algorithms", "file_path": "tests/test_backtracking.py", "license": "MIT License", "lines": 434, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
keon/algorithms:algorithms/graph/a_star.py
""" A* (A-star) Search Algorithm Finds the shortest path in a weighted graph using a heuristic function. Reference: https://en.wikipedia.org/wiki/A*_search_algorithm Complexity: Time: O(E log V) with a binary heap Space: O(V) """ from __future__ import annotations import heapq from collections.abc import Callable from typing import Any def a_star( graph: dict[Any, list[tuple[Any, float]]], start: Any, goal: Any, h: Callable[[Any], float], ) -> tuple[list[Any] | None, float]: """Find the shortest path using A* search. Args: graph: Adjacency list mapping node to list of (neighbor, cost) pairs. start: Starting node. goal: Goal node. h: Heuristic function estimating cost from a node to the goal. Returns: A tuple (path, total_cost). If no path exists, returns (None, inf). Examples: >>> g = {'A': [('B', 1)], 'B': [('C', 2)], 'C': []} >>> a_star(g, 'A', 'C', lambda n: 0) (['A', 'B', 'C'], 3) """ open_set: list[tuple[float, float, Any, list[Any]]] = [] heapq.heappush(open_set, (h(start), 0, start, [start])) visited: set[Any] = set() while open_set: f_score, g_score, current, path = heapq.heappop(open_set) if current == goal: return path, g_score if current in visited: continue visited.add(current) for neighbor, cost in graph.get(current, []): if neighbor not in visited: g = g_score + cost f = g + h(neighbor) heapq.heappush(open_set, (f, g, neighbor, path + [neighbor])) return None, float("inf")
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/a_star.py", "license": "MIT License", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/graph/kahns_algorithm.py
""" Kahn's Algorithm (Topological Sort via BFS) Computes a topological ordering of a directed acyclic graph using an in-degree based BFS approach. Reference: https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm Complexity: Time: O(V + E) Space: O(V) """ from __future__ import annotations from collections import deque class Solution: """Wrapper class for Kahn's topological sort.""" def topological_sort( self, vertices: int, adj: list[list[int]] ) -> list[int]: """Return a topological ordering of the graph. Args: vertices: Number of vertices. adj: Adjacency list where adj[i] lists neighbours of vertex *i*. Returns: A list of vertices in topological order, or an empty list if a cycle is detected. Examples: >>> Solution().topological_sort(3, [[1], [2], []]) [0, 1, 2] """ in_degree = [0] * vertices for i in range(vertices): for neighbor in adj[i]: in_degree[neighbor] += 1 queue = deque( [i for i in range(vertices) if in_degree[i] == 0] ) topo_order: list[int] = [] while queue: node = queue.popleft() topo_order.append(node) for neighbor in adj[node]: in_degree[neighbor] -= 1 if in_degree[neighbor] == 0: queue.append(neighbor) if len(topo_order) != vertices: return [] return topo_order
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/kahns_algorithm.py", "license": "MIT License", "lines": 45, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/greedy/gale_shapley.py
""" Gale-Shapley Stable Matching Solves the stable matching (stable marriage) problem. Given N men and N women with ranked preferences, produces a stable matching where no pair would prefer each other over their current partners. Reference: https://en.wikipedia.org/wiki/Gale%E2%80%93Shapley_algorithm Complexity: Time: O(n^2) Space: O(n) """ from __future__ import annotations def gale_shapley( men: dict[str, list[str]], women: dict[str, list[str]], ) -> dict[str, str]: """Find a stable matching between men and women. Args: men: Mapping of each man to his preference list of women (highest to lowest). women: Mapping of each woman to her preference list of men (highest to lowest). Returns: A dict mapping each man to his matched woman. Examples: >>> men = {"M1": ["W1", "W2"], "M2": ["W1", "W2"]} >>> women = {"W1": ["M2", "M1"], "W2": ["M1", "M2"]} >>> sorted(gale_shapley(men, women).items()) [('M1', 'W2'), ('M2', 'W1')] """ men_available: list[str] = list(men.keys()) married: dict[str, str] = {} proposal_counts: dict[str, int] = {man: 0 for man in men} while men_available: man = men_available.pop(0) woman = men[man][proposal_counts[man]] proposal_counts[man] += 1 if woman not in married: married[woman] = man else: current_partner = married[woman] if women[woman].index(man) < women[woman].index(current_partner): married[woman] = man men_available.append(current_partner) else: men_available.append(man) return {man: woman for woman, man in married.items()}
{ "repo_id": "keon/algorithms", "file_path": "algorithms/greedy/gale_shapley.py", "license": "MIT License", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keras-team/keras:keras/src/export/saved_model_export_archive.py
"""Base class for SavedModel export archive.""" from keras.src import backend from keras.src import layers from keras.src import tree from keras.src.export.export_utils import make_tf_tensor_spec from keras.src.utils.module_utils import tensorflow as tf class SavedModelExportArchive: """Base class for SavedModel export archive. This class contains all the common SavedModel export logic that is shared across different backends (TensorFlow, JAX, Torch). Backend-specific implementations should extend this class and override the following methods: - `_backend_track_layer(layer)`: Track variables of a layer. - `_backend_add_endpoint(name, fn, input_signature, **kwargs)`: Backend- specific endpoint creation logic. - `_backend_init()`: Backend-specific initialization (optional). """ def __init__(self): if backend.backend() not in ("tensorflow", "jax", "torch"): raise NotImplementedError( "`ExportArchive` is only compatible with TensorFlow, JAX and " "Torch backends." ) self._endpoint_names = [] self._endpoint_signatures = {} self.tensorflow_version = tf.__version__ self._tf_trackable = tf.__internal__.tracking.AutoTrackable() self._tf_trackable.variables = [] self._tf_trackable.trainable_variables = [] self._tf_trackable.non_trainable_variables = [] # Call backend-specific initialization if defined self._backend_init() def _backend_init(self): """Backend-specific initialization. Override in subclasses.""" pass @property def variables(self): return self._tf_trackable.variables @property def trainable_variables(self): return self._tf_trackable.trainable_variables @property def non_trainable_variables(self): return self._tf_trackable.non_trainable_variables def track(self, resource): """Track the variables (of a layer or model) and other assets. By default, all variables used by an endpoint function are automatically tracked when you call `add_endpoint()`. However, non-variables assets such as lookup tables need to be tracked manually. Note that lookup tables used by built-in Keras layers (`TextVectorization`, `IntegerLookup`, `StringLookup`) are automatically tracked by `add_endpoint()`. Args: resource: A layer, model or a TensorFlow trackable resource. """ if isinstance(resource, layers.Layer) and not resource.built: raise ValueError( "The layer provided has not yet been built. " "It must be built before export." ) # Note: with the TensorFlow backend, Layers and Models fall into both # the Layer case and the Trackable case. The Trackable case is needed # for preprocessing layers in order to track lookup tables. if isinstance(resource, tf.__internal__.tracking.Trackable): if not hasattr(self, "_tracked"): self._tracked = [] self._tracked.append(resource) if isinstance(resource, layers.Layer): self._backend_track_layer(resource) elif not isinstance(resource, tf.__internal__.tracking.Trackable): raise ValueError( "Invalid resource type. Expected a Keras `Layer` or `Model` " "or a TensorFlow `Trackable` object. " f"Received object {resource} of type '{type(resource)}'. " ) def _backend_track_layer(self, layer): raise NotImplementedError( "_backend_track_layer() must be implemented in backend subclasses." ) def add_endpoint(self, name, fn, input_signature=None, **kwargs): if name in self._endpoint_names: raise ValueError(f"Endpoint name '{name}' is already taken.") if backend.backend() != "jax": if "jax2tf_kwargs" in kwargs or "is_static" in kwargs: raise ValueError( "'jax2tf_kwargs' and 'is_static' are only supported with " f"the jax backend. Current backend: {backend.backend()}" ) # The fast path if `fn` is already a `tf.function`. if input_signature is None: if isinstance(fn, tf.types.experimental.GenericFunction): if not fn._list_all_concrete_functions(): raise ValueError( f"The provided tf.function '{fn}' " "has never been called. " "To specify the expected shape and dtype " "of the function's arguments, " "you must either provide a function that " "has been called at least once, or alternatively pass " "an `input_signature` argument in `add_endpoint()`." ) decorated_fn = fn else: raise ValueError( "If the `fn` argument provided is not a `tf.function`, " "you must provide an `input_signature` argument to " "specify the shape and dtype of the function arguments. " "Example:\n\n" "export_archive.add_endpoint(\n" " name='call',\n" " fn=model.call,\n" " input_signature=[\n" " keras.InputSpec(\n" " shape=(None, 224, 224, 3),\n" " dtype='float32',\n" " )\n" " ],\n" ")" ) setattr(self._tf_trackable, name, decorated_fn) self._endpoint_names.append(name) return decorated_fn input_signature = tree.map_structure( make_tf_tensor_spec, input_signature ) decorated_fn = self._backend_add_endpoint( name, fn, input_signature, **kwargs ) self._endpoint_signatures[name] = input_signature setattr(self._tf_trackable, name, decorated_fn) self._endpoint_names.append(name) return decorated_fn def _backend_add_endpoint(self, name, fn, input_signature, **kwargs): raise NotImplementedError( "_backend_add_endpoint() must be implemented in backend subclasses." ) def track_and_add_endpoint(self, name, resource, input_signature, **kwargs): """Track the variables and register a new serving endpoint. This function combines the functionality of `track` and `add_endpoint`. It tracks the variables of the `resource` (either a layer or a model) and registers a serving endpoint using `resource.__call__`. Args: name: `str`. The name of the endpoint. resource: A trackable Keras resource, such as a layer or model. input_signature: Optional. Specifies the shape and dtype of `fn`. Can be a structure of `keras.InputSpec`, `tf.TensorSpec`, `backend.KerasTensor`, or backend tensor (see below for an example showing a `Functional` model with 2 input arguments). If not provided, `fn` must be a `tf.function` that has been called at least once. Defaults to `None`. **kwargs: Additional keyword arguments: - Specific to the JAX backend: - `is_static`: Optional `bool`. Indicates whether `fn` is static. Set to `False` if `fn` involves state updates (e.g., RNG seeds). - `jax2tf_kwargs`: Optional `dict`. Arguments for `jax2tf.convert`. See [`jax2tf.convert`]( https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md). If `native_serialization` and `polymorphic_shapes` are not provided, they are automatically computed. """ self.track(resource) return self.add_endpoint( name, resource.__call__, input_signature, **kwargs ) def add_variable_collection(self, name, variables): """Register a set of variables to be retrieved after reloading. Arguments: name: The string name for the collection. variables: A tuple/list/set of `keras.Variable` instances. Example: ```python export_archive = ExportArchive() export_archive.track(model) # Register an endpoint export_archive.add_endpoint( name="serve", fn=model.call, input_signature=[keras.InputSpec(shape=(None, 3), dtype="float32")], ) # Save a variable collection export_archive.add_variable_collection( name="optimizer_variables", variables=model.optimizer.variables) export_archive.write_out("path/to/location") # Reload the object revived_object = tf.saved_model.load("path/to/location") # Retrieve the variables optimizer_variables = revived_object.optimizer_variables ``` """ if not isinstance(variables, (list, tuple, set)): raise ValueError( "Expected `variables` to be a list/tuple/set. " f"Received instead object of type '{type(variables)}'." ) # Ensure that all variables added are either tf.Variables # or Variables created by Keras 3 with the TF or JAX backends. if not all( isinstance(v, (tf.Variable, backend.Variable)) for v in variables ): raise ValueError( "Expected all elements in `variables` to be " "`tf.Variable` instances. Found instead the following types: " f"{list(set(type(v) for v in variables))}" ) if backend.backend() == "jax": variables = tree.flatten( tree.map_structure(self._convert_to_tf_variable, variables) ) setattr(self._tf_trackable, name, list(variables)) def write_out(self, filepath, options=None, verbose=True): """Write the corresponding SavedModel to disk. Arguments: filepath: `str` or `pathlib.Path` object. Path where to save the artifact. options: `tf.saved_model.SaveOptions` object that specifies SavedModel saving options. verbose: whether to print all the variables of an exported SavedModel. **Note on TF-Serving**: all endpoints registered via `add_endpoint()` are made visible for TF-Serving in the SavedModel artifact. In addition, the first endpoint registered is made visible under the alias `"serving_default"` (unless an endpoint with the name `"serving_default"` was already registered manually), since TF-Serving requires this endpoint to be set. """ from keras.src.utils import io_utils if not self._endpoint_names: raise ValueError( "No endpoints have been set yet. Call add_endpoint()." ) self._filter_and_track_resources() signatures = {} for name in self._endpoint_names: signatures[name] = self._get_concrete_fn(name) # Add "serving_default" signature key for TFServing if "serving_default" not in self._endpoint_names: signatures["serving_default"] = self._get_concrete_fn( self._endpoint_names[0] ) tf.saved_model.save( self._tf_trackable, filepath, options=options, signatures=signatures, ) # Print out available endpoints if verbose: endpoints = "\n\n".join( _print_signature( getattr(self._tf_trackable, name), name, verbose=verbose ) for name in self._endpoint_names ) io_utils.print_msg( f"Saved artifact at '{filepath}'. " "The following endpoints are available:\n\n" f"{endpoints}" ) def _convert_to_tf_variable(self, backend_variable): if not isinstance(backend_variable, backend.Variable): raise TypeError( "`backend_variable` must be a `backend.Variable`. " f"Recevied: backend_variable={backend_variable} of type " f"({type(backend_variable)})" ) return tf.Variable( backend_variable.value, dtype=backend_variable.dtype, trainable=backend_variable.trainable, name=backend_variable.name, ) def _get_concrete_fn(self, endpoint): """Workaround for some SavedModel quirks.""" if endpoint in self._endpoint_signatures: return getattr(self._tf_trackable, endpoint) else: traces = getattr(self._tf_trackable, endpoint)._trackable_children( "saved_model" ) return list(traces.values())[0] def _get_variables_used_by_endpoints(self): fns = [self._get_concrete_fn(name) for name in self._endpoint_names] return _list_variables_used_by_fns(fns) def _filter_and_track_resources(self): """Track resources used by endpoints / referenced in `track()` calls.""" # Start by extracting variables from endpoints. fns = [self._get_concrete_fn(name) for name in self._endpoint_names] tvs, ntvs = _list_variables_used_by_fns(fns) self._tf_trackable._all_variables = list(tvs + ntvs) # `tf.train.TrackableView` hardcodes the `save_type` to "checkpoint". # We need to subclass to use a `save_type` of "savedmodel". savedmodel_cache = {} class SavedModelTrackableView(tf.train.TrackableView): @classmethod def children(cls, obj, save_type="savedmodel", **kwargs): return super().children(obj, save_type, cache=savedmodel_cache) # Next, track lookup tables. # Hopefully, one day this will be automated at the tf.function level. self._tf_trackable._misc_assets = [] from tensorflow.saved_model.experimental import TrackableResource if hasattr(self, "_tracked"): for root in self._tracked: descendants = SavedModelTrackableView(root).descendants() for trackable in descendants: if isinstance(trackable, TrackableResource): self._tf_trackable._misc_assets.append(trackable) def _print_signature(fn, name, verbose=True): concrete_fn = fn._list_all_concrete_functions()[0] pprinted_signature = concrete_fn.pretty_printed_signature(verbose=verbose) lines = pprinted_signature.split("\n") lines = [f"* Endpoint '{name}'"] + lines[1:] endpoint = "\n".join(lines) return endpoint def _list_variables_used_by_fns(fns): trainable_variables = [] non_trainable_variables = [] trainable_variables_ids = set() non_trainable_variables_ids = set() for fn in fns: if hasattr(fn, "concrete_functions"): concrete_functions = fn.concrete_functions elif hasattr(fn, "get_concrete_function"): concrete_functions = [fn.get_concrete_function()] else: concrete_functions = [fn] for concrete_fn in concrete_functions: for v in concrete_fn.trainable_variables: if id(v) not in trainable_variables_ids: trainable_variables.append(v) trainable_variables_ids.add(id(v)) for v in concrete_fn.variables: if ( id(v) not in trainable_variables_ids and id(v) not in non_trainable_variables_ids ): non_trainable_variables.append(v) non_trainable_variables_ids.add(id(v)) return trainable_variables, non_trainable_variables
{ "repo_id": "keras-team/keras", "file_path": "keras/src/export/saved_model_export_archive.py", "license": "Apache License 2.0", "lines": 338, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
keras-team/keras:integration_tests/pytorch_export_test.py
""" Integration tests for PyTorch model export with dynamic shapes. Tests the complete fix for GitHub issue #22102 where models with AveragePooling2D → Conv2D → Reshape failed to export with dynamic shapes. The fixes enable: 1. torch.export with dynamic shapes 2. ONNX export with dynamic shapes 3. TorchScript tracing with dynamic shapes """ import os os.environ["KERAS_BACKEND"] = "torch" import numpy as np import pytest from absl.testing import parameterized from keras.src import backend from keras.src import layers from keras.src import models from keras.src import testing @pytest.mark.skipif( backend.backend() != "torch", reason="Export tests require PyTorch backend", ) class TestPyTorchExportWithDynamicShapes(testing.TestCase): """Test PyTorch export methods with dynamic shapes (GitHub issue #22102).""" @parameterized.named_parameters( ("shape_3x3", (1, 3, 3, 1016), (1, 1, 512)), ("shape_5x5", (1, 5, 5, 1016), (1, 4, 512)), ("shape_7x7_batch2", (2, 7, 7, 1016), (2, 9, 512)), ) def test_issue_22102_model_inference(self, input_shape, expected_shape): """Test the exact model from issue #22102 with varying shapes.""" import torch # Create the exact model from issue #22102 inputs = layers.Input(shape=(None, None, 1016)) x = layers.AveragePooling2D(pool_size=(3, 2), strides=2)(inputs) x = layers.Conv2D(512, kernel_size=1, activation="relu")(x) x = layers.Reshape((-1, 512))(x) model = models.Model(inputs=inputs, outputs=x) # Test inference with varying shapes x_test = torch.randn(*input_shape) output = model(x_test) self.assertEqual(tuple(output.shape), expected_shape) @parameterized.named_parameters( ("torch_export", "torch_export"), ("onnx_export", "onnx_export"), ("torchscript_trace", "torchscript_trace"), ) def test_issue_22102_export_methods(self, export_method): """Test issue #22102 model with different export methods. Validates that all export methods work with dynamic shapes after the fix. """ import tempfile import torch # Create the exact model from issue #22102 inputs = layers.Input(shape=(None, None, 1016)) x = layers.AveragePooling2D(pool_size=(3, 2), strides=2)(inputs) x = layers.Conv2D(512, kernel_size=1, activation="relu")(x) x = layers.Reshape((-1, 512))(x) model = models.Model(inputs=inputs, outputs=x) sample_input = torch.randn(1, 3, 3, 1016) if export_method == "torch_export": # Test torch.export with dynamic shapes # Note: torch.export has stricter constraints than ONNX export # Skip if constraints cannot be satisfied try: batch_dim = torch.export.Dim("batch", min=1, max=1024) h_dim = torch.export.Dim("height", min=1, max=1024) w_dim = torch.export.Dim("width", min=1, max=1024) exported = torch.export.export( model, (sample_input,), dynamic_shapes=(({0: batch_dim, 1: h_dim, 2: w_dim},),), strict=False, ) # Test with different shapes for shape in [(1, 3, 3, 1016), (1, 5, 5, 1016)]: x_test = torch.randn(*shape) output = exported.module()(x_test) self.assertIsNotNone(output) except Exception as e: # torch.export has known limitations with certain # layer combinations. The important thing is that # ONNX export works (tested separately) if "Constraints violated" in str(e): pytest.skip( f"torch.export constraints not satisfiable: {e}" ) pytest.skip(f"torch.export not available: {e}") elif export_method == "onnx_export": # Test ONNX export with dynamic shapes try: import onnxruntime as ort with tempfile.NamedTemporaryFile( suffix=".onnx", delete=False ) as f: onnx_path = f.name torch.onnx.export( model, (sample_input,), onnx_path, input_names=["input"], output_names=["output"], dynamic_shapes=( ( ( torch.export.Dim.DYNAMIC, torch.export.Dim.DYNAMIC, torch.export.Dim.DYNAMIC, torch.export.Dim.STATIC, ), ), ), ) # Test with ONNX Runtime ort_session = ort.InferenceSession(onnx_path) input_name = ort_session.get_inputs()[0].name for shape in [ (1, 3, 3, 1016), (1, 5, 5, 1016), (2, 7, 7, 1016), ]: x_test = np.random.randn(*shape).astype(np.float32) keras_output = ( model(torch.from_numpy(x_test)).detach().numpy() ) onnx_output = ort_session.run(None, {input_name: x_test})[0] self.assertEqual(keras_output.shape, onnx_output.shape) max_diff = np.abs(keras_output - onnx_output).max() self.assertLess(max_diff, 1e-4) os.unlink(onnx_path) except ImportError: pytest.skip("onnxruntime not available") except Exception as e: if "Constraints violated" in str(e): self.fail(f"ONNX export failed: {e}") pytest.skip(f"ONNX export not available: {e}") elif export_method == "torchscript_trace": # Test TorchScript tracing try: traced = torch.jit.trace(model, sample_input) # Test with different shapes for shape in [(1, 3, 3, 1016), (1, 5, 5, 1016)]: x_test = torch.randn(*shape) output = traced(x_test) self.assertIsNotNone(output) except Exception as e: pytest.skip(f"TorchScript trace not available: {e}") @parameterized.named_parameters( ("global_avg_pool", "global_avg_pool"), ("reshape_flatten", "reshape_flatten"), ("combined", "combined"), ) def test_fixed_layers_export(self, layer_type): """Test that fixed layers work with PyTorch export methods. Tests the three main fixes: 1. GlobalAveragePooling2D (mean() dtype fix) 2. Reshape with -1 (dynamic reshape fix) 3. Combined scenario (variables.py SymInt fix) """ import tempfile import torch if layer_type == "global_avg_pool": # Test GlobalAveragePooling2D (mean() fix) inputs = layers.Input(shape=(None, None, 64)) x = layers.Conv2D(64, 3, padding="same")(inputs) x = layers.GlobalAveragePooling2D()(x) x = layers.Dense(10)(x) model = models.Model(inputs=inputs, outputs=x) sample_input = torch.randn(1, 8, 8, 64) test_shapes = [(1, 8, 8, 64), (2, 16, 16, 64)] elif layer_type == "reshape_flatten": # Test Reshape with -1 (reshape fix) inputs = layers.Input(shape=(None, None, 64)) x = layers.Conv2D(32, 3, padding="same")(inputs) x = layers.Reshape((-1, 32))(x) model = models.Model(inputs=inputs, outputs=x) sample_input = torch.randn(1, 8, 8, 64) test_shapes = [(1, 8, 8, 64), (1, 16, 16, 64)] else: # combined # Test combined scenario (all fixes) inputs = layers.Input(shape=(None, None, 64)) x = layers.AveragePooling2D(pool_size=2)(inputs) x = layers.Conv2D(128, 3, padding="same")(x) x = layers.GlobalAveragePooling2D()(x) x = layers.Dense(256)(x) x = layers.Dropout(0.5)(x) x = layers.Dense(10)(x) model = models.Model(inputs=inputs, outputs=x) sample_input = torch.randn(1, 8, 8, 64) test_shapes = [(1, 8, 8, 64), (2, 16, 16, 64)] # Test torch.export # Note: torch.export has stricter constraints than ONNX export # Skip if constraints cannot be satisfied try: batch_dim = torch.export.Dim("batch", min=1, max=1024) h_dim = torch.export.Dim("height", min=1, max=1024) w_dim = torch.export.Dim("width", min=1, max=1024) exported = torch.export.export( model, (sample_input,), dynamic_shapes=(({0: batch_dim, 1: h_dim, 2: w_dim},),), strict=False, ) self.assertIsNotNone(exported) except Exception as e: # torch.export has known limitations with certain layers # The important thing is that ONNX export works if "Constraints violated" in str(e): pytest.skip(f"torch.export constraints not satisfiable: {e}") pytest.skip(f"torch.export not available: {e}") # Test ONNX export try: import onnxruntime as ort with tempfile.NamedTemporaryFile(suffix=".onnx", delete=False) as f: onnx_path = f.name torch.onnx.export( model, (sample_input,), onnx_path, input_names=["input"], output_names=["output"], dynamic_shapes=( ( ( torch.export.Dim.DYNAMIC, torch.export.Dim.DYNAMIC, torch.export.Dim.DYNAMIC, torch.export.Dim.STATIC, ), ), ), ) # Verify ONNX model works with varying shapes ort_session = ort.InferenceSession(onnx_path) input_name = ort_session.get_inputs()[0].name for shape in test_shapes: x_test = np.random.randn(*shape).astype(np.float32) onnx_output = ort_session.run(None, {input_name: x_test})[0] self.assertIsNotNone(onnx_output) os.unlink(onnx_path) except ImportError: pytest.skip("onnxruntime not available") except TypeError as e: if "dtype" in str(e): self.fail( f"ONNX export failed with dtype error for {layer_type}: {e}" ) pytest.skip(f"ONNX export not available: {e}") except Exception as e: if "Constraints violated" in str(e): self.fail(f"ONNX export failed for {layer_type}: {e}") pytest.skip(f"ONNX export not available: {e}")
{ "repo_id": "keras-team/keras", "file_path": "integration_tests/pytorch_export_test.py", "license": "Apache License 2.0", "lines": 253, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
keras-team/keras:keras/src/optimizers/schedule_free_adamw.py
from keras.src import ops from keras.src.api_export import keras_export from keras.src.optimizers import optimizer @keras_export(["keras.optimizers.ScheduleFreeAdamW"]) class ScheduleFreeAdamW(optimizer.Optimizer): """Optimizer that implements the Schedule-Free AdamW algorithm. Schedule-Free learning is a method that avoids the need for a learning rate schedule by maintaining a combination of interpolation and averaging. This approach eliminates the requirement to specify stopping time in advance and typically matches or outperforms cosine and linear decay schedules. The optimizer maintains two sets of variables internally: - `momentum`: The sequence where gradient updates are applied - `x`: The averaged sequence used for evaluation During training, the model parameters are set to an interpolation between `momentum` and `x`. Args: learning_rate: A float, a `keras.optimizers.schedules.LearningRateSchedule` instance, or a callable that takes no arguments and returns the actual value to use. The learning rate. Defaults to `0.0025`. beta_1: A float value or a constant float tensor, or a callable that takes no arguments and returns the actual value to use. The exponential decay rate for the 1st moment estimates and controls the interpolation between `momentum` and `x`. Defaults to `0.9`. beta_2: A float value or a constant float tensor, or a callable that takes no arguments and returns the actual value to use. The exponential decay rate for the 2nd moment estimates. Defaults to `0.999`. epsilon: A small constant for numerical stability. Defaults to `1e-8`. warmup_steps: Number of warmup steps for learning rate warmup. During warmup, the learning rate linearly increases from 0 to the specified learning rate. Defaults to `0`. {{base_optimizer_keyword_args}} References: - [Defazio et al., 2024](https://arxiv.org/abs/2405.15682) - [Schedule-Free repository]( https://github.com/facebookresearch/schedule_free) Example: >>> optimizer = keras.optimizers.ScheduleFreeAdamW(learning_rate=0.0025) >>> model.compile(optimizer=optimizer, loss="mse") >>> model.fit(x_train, y_train) """ def __init__( self, learning_rate=0.0025, beta_1=0.9, beta_2=0.999, epsilon=1e-8, warmup_steps=0, weight_decay=None, clipnorm=None, clipvalue=None, global_clipnorm=None, use_ema=False, ema_momentum=0.99, ema_overwrite_frequency=None, loss_scale_factor=None, gradient_accumulation_steps=None, name="schedule_free_adamw", **kwargs, ): super().__init__( learning_rate=learning_rate, name=name, weight_decay=weight_decay, clipnorm=clipnorm, clipvalue=clipvalue, global_clipnorm=global_clipnorm, use_ema=use_ema, ema_momentum=ema_momentum, ema_overwrite_frequency=ema_overwrite_frequency, loss_scale_factor=loss_scale_factor, gradient_accumulation_steps=gradient_accumulation_steps, **kwargs, ) self.beta_1 = beta_1 self.beta_2 = beta_2 self.epsilon = epsilon self.warmup_steps = warmup_steps def build(self, var_list): """Initialize optimizer variables. ScheduleFreeAdamW optimizer has the following variables: - `momentum`: Auxiliary variable where gradient updates are applied - `velocity`: Exponential moving average of squared gradients (Adam) Args: var_list: list of model variables to build optimizer variables on. """ if self.built: return super().build(var_list) self._momentums, self._velocities = self.add_optimizer_variables( var_list, ["momentum", "velocity"] ) # Initialize momentum to match the initial parameter values for momentum, var in zip(self._momentums, var_list): if momentum is not None: self.assign(momentum, ops.copy(var)) def update_step(self, gradient, variable, learning_rate): """Update step given gradient and the associated model variable.""" lr = ops.cast(learning_rate, variable.dtype) gradient = ops.cast(gradient, variable.dtype) local_step = ops.cast(self.iterations + 1, variable.dtype) beta_1 = ops.cast(self.beta_1, variable.dtype) beta_2 = ops.cast(self.beta_2, variable.dtype) epsilon = ops.cast(self.epsilon, variable.dtype) # Apply warmup if self.warmup_steps > 0: warmup_steps = ops.cast(self.warmup_steps, variable.dtype) warmup_factor = ops.minimum(local_step / warmup_steps, 1.0) lr = lr * warmup_factor var_index = self._get_variable_index(variable) momentum = self._momentums[var_index] velocity = self._velocities[var_index] # Store momentum_old before any updates momentum_old = momentum.value # Bias correction for Adam's second moment bias_correction_2 = 1 - ops.power(beta_2, local_step) # Update velocity (second moment estimate) # velocity = beta_2 * velocity + (1 - beta_2) * gradient^2 self.assign_add( velocity, ops.multiply( ops.subtract(ops.square(gradient), velocity), 1 - beta_2 ), ) # Compute the denominator (RMSprop-style with bias correction) denom = ops.add(ops.sqrt(velocity / bias_correction_2), epsilon) # Update momentum: momentum = momentum - lr * gradient / denom grad_scaled = ops.divide(ops.multiply(lr, gradient), denom) self.assign_sub(momentum, grad_scaled) # Compute weight for averaging: weight = 1 / step weight = 1.0 / local_step # Recover x_old from y_old and momentum_old # x_old = (y_old - (1 - beta_1) * momentum_old) / beta_1 y_old = variable x_old = ops.divide( ops.subtract(y_old, ops.multiply(1 - beta_1, momentum_old)), beta_1, ) # x_new = lerp(x_old, momentum, weight) # x_new = (1 - weight) * x_old + weight * momentum x_new = ops.add( ops.multiply(1 - weight, x_old), ops.multiply(weight, momentum) ) # y_new = lerp(momentum, x_new, beta_1) # y_new = (1 - beta_1) * momentum + beta_1 * x_new y_new = ops.add( ops.multiply(1 - beta_1, momentum), ops.multiply(beta_1, x_new) ) self.assign(variable, y_new) def get_config(self): config = super().get_config() config.update( { "beta_1": self.beta_1, "beta_2": self.beta_2, "epsilon": self.epsilon, "warmup_steps": self.warmup_steps, } ) return config ScheduleFreeAdamW.__doc__ = ScheduleFreeAdamW.__doc__.replace( "{{base_optimizer_keyword_args}}", optimizer.base_optimizer_keyword_args )
{ "repo_id": "keras-team/keras", "file_path": "keras/src/optimizers/schedule_free_adamw.py", "license": "Apache License 2.0", "lines": 165, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
keras-team/keras:keras/src/optimizers/schedule_free_adamw_test.py
import numpy as np import pytest import keras from keras.src import backend from keras.src import ops from keras.src import testing from keras.src.optimizers.schedule_free_adamw import ScheduleFreeAdamW class ScheduleFreeAdamWTest(testing.TestCase): def test_config(self): optimizer = ScheduleFreeAdamW( learning_rate=0.005, beta_1=0.95, beta_2=0.99, epsilon=1e-6, warmup_steps=100, ) self.run_class_serialization_test(optimizer) def test_single_step(self): optimizer = ScheduleFreeAdamW(learning_rate=0.5) grads = ops.array([1.0, 6.0, 7.0, 2.0]) vars = backend.Variable([1.0, 2.0, 3.0, 4.0]) optimizer.apply_gradients(zip([grads], [vars])) # After one step, the parameters should have changed self.assertNotAllClose(vars, [1.0, 2.0, 3.0, 4.0], rtol=1e-4, atol=1e-4) def test_weight_decay(self): grads, var1, var2 = ( ops.zeros(()), backend.Variable(2.0), backend.Variable(2.0, name="exclude"), ) optimizer_1 = ScheduleFreeAdamW(learning_rate=1.0, weight_decay=0.004) optimizer_1.apply_gradients(zip([grads], [var1])) optimizer_2 = ScheduleFreeAdamW(learning_rate=1.0, weight_decay=0.004) optimizer_2.exclude_from_weight_decay(var_names=["exclude"]) optimizer_2.apply_gradients(zip([grads, grads], [var1, var2])) # var2 should be unchanged since it's excluded from weight decay self.assertAlmostEqual(var2.numpy(), 2.0, decimal=6) def test_warmup(self): """Test that warmup affects the learning rate.""" optimizer_no_warmup = ScheduleFreeAdamW( learning_rate=0.5, warmup_steps=0 ) optimizer_with_warmup = ScheduleFreeAdamW( learning_rate=0.5, warmup_steps=10 ) grads = ops.array([1.0, 1.0, 1.0]) var1 = backend.Variable([1.0, 2.0, 3.0]) var2 = backend.Variable([1.0, 2.0, 3.0]) # Apply single gradient step optimizer_no_warmup.apply_gradients(zip([grads], [var1])) optimizer_with_warmup.apply_gradients(zip([grads], [var2])) # The optimizer with warmup should have made a smaller update # because effective lr = lr * (step / warmup_steps) = 0.5 * 0.1 = 0.05 diff_no_warmup = np.abs(var1.numpy() - [1.0, 2.0, 3.0]) diff_with_warmup = np.abs(var2.numpy() - [1.0, 2.0, 3.0]) # With warmup, the update should be smaller self.assertTrue(np.all(diff_with_warmup < diff_no_warmup)) def test_multiple_steps(self): """Test that the optimizer works over multiple steps.""" optimizer = ScheduleFreeAdamW(learning_rate=0.01) var = backend.Variable([1.0, 2.0, 3.0]) for _ in range(10): grads = ops.array([0.1, 0.1, 0.1]) optimizer.apply_gradients(zip([grads], [var])) # Parameters should have decreased final_values = var.numpy() self.assertTrue(np.all(final_values < [1.0, 2.0, 3.0])) @pytest.mark.requires_trainable_backend def test_with_model(self): """Test that the optimizer works with a Keras model.""" model = keras.Sequential([keras.layers.Dense(10)]) optimizer = ScheduleFreeAdamW(learning_rate=0.01) model.compile(optimizer=optimizer, loss="mse") x = keras.ops.ones((4, 5)) y = keras.ops.zeros((4, 10)) # Training model.fit(x, y, epochs=2, verbose=0) # Evaluation loss = model.evaluate(x, y, verbose=0) self.assertIsNotNone(loss) def test_clip_norm(self): optimizer = ScheduleFreeAdamW(clipnorm=1) grad = [np.array([100.0, 100.0])] clipped_grad = optimizer._clip_gradients(grad) self.assertAllClose(clipped_grad[0], [2**0.5 / 2, 2**0.5 / 2]) def test_clip_value(self): optimizer = ScheduleFreeAdamW(clipvalue=1) grad = [np.array([100.0, 100.0])] clipped_grad = optimizer._clip_gradients(grad) self.assertAllClose(clipped_grad[0], [1.0, 1.0])
{ "repo_id": "keras-team/keras", "file_path": "keras/src/optimizers/schedule_free_adamw_test.py", "license": "Apache License 2.0", "lines": 90, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
keras-team/keras:benchmarks/layer_benchmark/random_rotation_benchmark.py
"""Benchmark RandomRotation layer.""" from absl import app from absl import flags from benchmarks.layer_benchmark.base_benchmark import LayerBenchmark FLAGS = flags.FLAGS def benchmark_random_rotation( num_samples, batch_size, jit_compile=True, ): layer_name = "RandomRotation" init_args = {"factor": 0.1} benchmark = LayerBenchmark( layer_name, init_args, input_shape=[224, 224, 3], jit_compile=jit_compile, ) # Predict is effectively a no-op for preprocessing layers, # but we still call it to follow the standard benchmark structure. benchmark.benchmark_predict( num_samples=num_samples, batch_size=batch_size, ) benchmark.benchmark_train( num_samples=num_samples, batch_size=batch_size, ) BENCHMARK_NAMES = { "benchmark_random_rotation": benchmark_random_rotation, } def main(_): benchmark_name = FLAGS.benchmark_name num_samples = FLAGS.num_samples batch_size = FLAGS.batch_size jit_compile = FLAGS.jit_compile if benchmark_name is None: for benchmark_fn in BENCHMARK_NAMES.values(): benchmark_fn(num_samples, batch_size, jit_compile) return if benchmark_name not in BENCHMARK_NAMES: raise ValueError( f"Invalid benchmark name: {benchmark_name}, " f"`benchmark_name` must be one of {BENCHMARK_NAMES.keys()}" ) BENCHMARK_NAMES[benchmark_name](num_samples, batch_size, jit_compile) if __name__ == "__main__": app.run(main)
{ "repo_id": "keras-team/keras", "file_path": "benchmarks/layer_benchmark/random_rotation_benchmark.py", "license": "Apache License 2.0", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple