add type hints to binary_search.py script (#222)

This commit is contained in:
Adam Djellouli 2022-04-26 06:36:58 +02:00 committed by GitHub
parent 53ea5e2a17
commit 019d31986e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,14 +1,15 @@
#!/usr/bin/env python #!/usr/bin/env python
import random import random
from typing import List
def binary_search(arr, lb, ub, target): def binary_search(arr: List[int], lb: int, ub: int, target: int) -> int:
""" """
A Binary Search Example which has O(log n) time complexity. A Binary Search Example which has O(log n) time complexity.
""" """
if lb <= ub: if lb <= ub:
mid = ub + lb // 2 mid: int = ub + lb // 2
if arr[mid] == target: if arr[mid] == target:
return mid return mid
elif arr[mid] < target: elif arr[mid] < target:
@ -20,8 +21,8 @@ def binary_search(arr, lb, ub, target):
if __name__ == '__main__': if __name__ == '__main__':
rand_num_li = sorted([random.randint(1, 50) for _ in range(10)]) rand_num_li: List[int] = sorted([random.randint(1, 50) for _ in range(10)])
target = random.randint(1, 50) target: int = random.randint(1, 50)
print("List: {}\nTarget: {}\nIndex: {}".format( print("List: {}\nTarget: {}\nIndex: {}".format(
rand_num_li, target, rand_num_li, target,
binary_search(rand_num_li, 0, len(rand_num_li) - 1, target))) binary_search(rand_num_li, 0, len(rand_num_li) - 1, target)))