Skip to content

Commit e3d13d3

Browse files
authored
Added type hints and doctests for binary_search and exponential_search functions. Improved code documentation and ensured testability.
1 parent ec85644 commit e3d13d3

File tree

1 file changed

+43
-7
lines changed

1 file changed

+43
-7
lines changed

searches/Exponential_Search.py

+43-7
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,24 @@
1-
# Python program to perform Exponential Search
2-
from bisect import bisect_left
1+
from typing import List
32

3+
def binary_search(arr: List[int], left: int, right: int, target: int) -> int:
4+
"""
5+
Perform binary search on a sorted array.
46
5-
# Binary search function
6-
def binary_search(arr, left, right, target):
7+
Parameters:
8+
arr (List[int]): The sorted list in which to search.
9+
left (int): The starting index for the search range.
10+
right (int): The ending index for the search range.
11+
target (int): The value to search for.
12+
13+
Returns:
14+
int: The index of the target if found, otherwise -1.
15+
16+
Doctest:
17+
>>> binary_search([2, 3, 4, 10, 40], 0, 4, 10)
18+
3
19+
>>> binary_search([2, 3, 4, 10, 40], 0, 4, 5)
20+
-1
21+
"""
722
while left <= right:
823
mid = left + (right - left) // 2
924
if arr[mid] == target:
@@ -15,8 +30,27 @@ def binary_search(arr, left, right, target):
1530
return -1
1631

1732

18-
# Exponential search function
19-
def exponential_search(arr, target):
33+
def exponential_search(arr: List[int], target: int) -> int:
34+
"""
35+
Perform exponential search on a sorted array.
36+
37+
Exponential search first finds a range where the target may reside
38+
by repeatedly doubling the index. It then performs binary search
39+
within that range.
40+
41+
Parameters:
42+
arr (List[int]): The sorted list in which to search.
43+
target (int): The value to search for.
44+
45+
Returns:
46+
int: The index of the target if found, otherwise -1.
47+
48+
Doctest:
49+
>>> exponential_search([2, 3, 4, 10, 40, 50, 60, 70, 80, 90, 100], 10)
50+
3
51+
>>> exponential_search([2, 3, 4, 10, 40, 50, 60, 70, 80, 90, 100], 5)
52+
-1
53+
"""
2054
n = len(arr)
2155

2256
# If the target is at the first position
@@ -32,8 +66,10 @@ def exponential_search(arr, target):
3266
return binary_search(arr, i // 2, min(i, n - 1), target)
3367

3468

35-
# Example usage
3669
if __name__ == "__main__":
70+
"""
71+
Example to demonstrate the usage of exponential_search function.
72+
"""
3773
arr = [2, 3, 4, 10, 40, 50, 60, 70, 80, 90, 100]
3874
target = 10
3975

0 commit comments

Comments
 (0)