You've already forked devops-exercises
mirror of
https://github.com/bregman-arie/devops-exercises.git
synced 2025-07-09 23:45:42 +02:00
Convert binary search to iterative, add helper functions and main with complexity docstring while preserving functionality (#10552)
Co-authored-by: Arie Bregman <bregman.arie@gmail.com>
This commit is contained in:
@ -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 0
|
||||
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()
|
||||
|
Reference in New Issue
Block a user