From 0e048271c10d77f5942048bee8373be3b46948a3 Mon Sep 17 00:00:00 2001 From: Adam Djellouli <37275728+djeada@users.noreply.github.com> Date: Thu, 9 Jan 2025 22:48:48 +0100 Subject: [PATCH] Convert binary search to iterative, add helper functions and main with complexity docstring while preserving functionality --- coding/python/binary_search.py | 40 +++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/coding/python/binary_search.py b/coding/python/binary_search.py index d1937e6e9..7a66c848a 100644 --- a/coding/python/binary_search.py +++ b/coding/python/binary_search.py @@ -1,28 +1,42 @@ #!/usr/bin/env python import random -from typing import List +from typing import List, Optional -def binary_search(arr: List[int], lb: int, ub: int, target: int) -> int: +def binary_search(arr: List[int], lb: int, ub: int, target: int) -> Optional[int]: """ A Binary Search Example which has O(log n) time complexity. """ - if lb <= ub: - mid: int = lb + (ub - lb) // 2 + while lb <= ub: + mid = lb + (ub - lb) // 2 if arr[mid] == target: return mid elif arr[mid] < target: - return binary_search(arr, mid + 1, ub, target) + lb = mid + 1 else: - return binary_search(arr, lb, mid - 1, target) - else: - return -1 + ub = mid - 1 + return -1 + + +def generate_random_list(size: int = 10, lower: int = 1, upper: int = 50) -> List[int]: + return sorted(random.randint(lower, upper) for _ in range(size)) + + +def find_target_in_list(target: int, lst: List[int]) -> int: + return binary_search(lst, 0, len(lst) - 1, target) + + +def main(): + """ + Executes the binary search algorithm with a randomly generated list. + Time Complexity: O(log n) + """ + rand_num_li = generate_random_list() + target = random.randint(1, 50) + index = find_target_in_list(target, rand_num_li) + print(f"List: {rand_num_li}\nTarget: {target}\nIndex: {index}") if __name__ == '__main__': - rand_num_li: List[int] = sorted([random.randint(1, 50) for _ in range(10)]) - target: int = random.randint(1, 50) - print("List: {}\nTarget: {}\nIndex: {}".format( - rand_num_li, target, - binary_search(rand_num_li, 0, len(rand_num_li) - 1, target))) + main()