Skip to content

Commit d81528a

Browse files
Darkslayer3324jclaudecclauss
authored
Fix exponential_search recursing forever when the item is below the first element (#15384)
binary_search_by_recursion used right=-1 as its 'not given' sentinel, but the recursion legitimately reaches right=-1 when the item is smaller than every element, which reset right to len-1 and never terminated. Use None as the sentinel and add doctests for items below and above the range. Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent de56f29 commit d81528a

1 file changed

Lines changed: 14 additions & 3 deletions

File tree

‎searches/exponential_search.py‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@
1717

1818

1919
def binary_search_by_recursion(
20-
sorted_collection: list[int], item: int, left: int = 0, right: int = -1
20+
sorted_collection: list[int],
21+
item: int,
22+
left: int = 0,
23+
right: int | None = None,
2124
) -> int:
2225
"""Pure implementation of binary search algorithm in Python using recursion
2326
@@ -27,7 +30,7 @@ def binary_search_by_recursion(
2730
:param sorted_collection: some ascending sorted collection with comparable items
2831
:param item: item value to search
2932
:param left: starting index for the search
30-
:param right: ending index for the search
33+
:param right: ending index for the search (defaults to the last index)
3134
:return: index of the found item or -1 if the item is not found
3235
3336
Examples:
@@ -39,8 +42,12 @@ def binary_search_by_recursion(
3942
1
4043
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 6, 0, 4)
4144
-1
45+
>>> binary_search_by_recursion([0, 5, 7, 10, 15], -1)
46+
-1
47+
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 16)
48+
-1
4249
"""
43-
if right < 0:
50+
if right is None:
4451
right = len(sorted_collection) - 1
4552
if list(sorted_collection) != sorted(sorted_collection):
4653
raise ValueError("sorted_collection must be sorted in ascending order")
@@ -81,6 +88,10 @@ def exponential_search(sorted_collection: list[int], item: int) -> int:
8188
1
8289
>>> exponential_search([0, 5, 7, 10, 15], 6)
8390
-1
91+
>>> exponential_search([0, 5, 7, 10, 15], -3)
92+
-1
93+
>>> exponential_search([0, 5, 7, 10, 15], 20)
94+
-1
8495
"""
8596
if list(sorted_collection) != sorted(sorted_collection):
8697
raise ValueError("sorted_collection must be sorted in ascending order")

0 commit comments

Comments
 (0)