Skip to content

Commit 6029a91

Browse files
Split exponential search recursion into a flat int-only core (#15389)
Follow-up to #15384. Replace the ``right: int | None`` sentinel on the recursive path with a thin wrapper that defaults ``right`` once, then delegates to a nested ``_search(left, right)`` core whose indices are always concrete ints. This matches the wrapper/core shape already used by ``binary_search.py`` and keeps the recursion flat so the window can only shrink.
1 parent 1c21819 commit 6029a91

1 file changed

Lines changed: 19 additions & 11 deletions

File tree

searches/exponential_search.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -47,21 +47,29 @@ def binary_search_by_recursion(
4747
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 16)
4848
-1
4949
"""
50-
if right is None:
51-
right = len(sorted_collection) - 1
5250
if list(sorted_collection) != sorted(sorted_collection):
5351
raise ValueError("sorted_collection must be sorted in ascending order")
54-
if right < left:
55-
return -1
52+
if right is None:
53+
right = len(sorted_collection) - 1
5654

57-
midpoint = left + (right - left) // 2
55+
# Recursive core: ``left`` and ``right`` are always concrete indices here, so the
56+
# window can only shrink. Keeping the recursion flat (no ``None`` sentinel, no
57+
# re-expansion) is what prevents the runaway recursion when the item sits below
58+
# ``sorted_collection[0]`` and ``right`` legitimately drops below ``left``.
59+
def _search(left: int, right: int) -> int:
60+
if right < left:
61+
return -1
5862

59-
if sorted_collection[midpoint] == item:
60-
return midpoint
61-
elif sorted_collection[midpoint] > item:
62-
return binary_search_by_recursion(sorted_collection, item, left, midpoint - 1)
63-
else:
64-
return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right)
63+
midpoint = left + (right - left) // 2
64+
65+
if sorted_collection[midpoint] == item:
66+
return midpoint
67+
elif sorted_collection[midpoint] > item:
68+
return _search(left, midpoint - 1)
69+
else:
70+
return _search(midpoint + 1, right)
71+
72+
return _search(left, right)
6573

6674

6775
def exponential_search(sorted_collection: list[int], item: int) -> int:

0 commit comments

Comments
 (0)