Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions searches/binary_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,9 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
-1
"""
if any(a > b for a, b in pairwise(sorted_collection)):
raise ValueError("sorted_collection must be sorted in ascending order")
raise ValueError(
"Input list must be sorted in ascending order for binary search to work"
)
left = 0
right = len(sorted_collection) - 1

Expand Down Expand Up @@ -235,7 +237,9 @@ def binary_search_std_lib(sorted_collection: list[int], item: int) -> int:
-1
"""
if list(sorted_collection) != sorted(sorted_collection):
raise ValueError("sorted_collection must be sorted in ascending order")
raise ValueError(
"Input list must be sorted in ascending order for binary search to work"
)
index = bisect.bisect_left(sorted_collection, item)
if index != len(sorted_collection) and sorted_collection[index] == item:
return index
Expand Down Expand Up @@ -269,7 +273,9 @@ def binary_search_with_duplicates(sorted_collection: list[int], item: int) -> li
[]
"""
if list(sorted_collection) != sorted(sorted_collection):
raise ValueError("sorted_collection must be sorted in ascending order")
raise ValueError(
"Input list must be sorted in ascending order for binary search to work"
)

def lower_bound(sorted_collection: list[int], item: int) -> int:
"""
Expand Down Expand Up @@ -343,7 +349,9 @@ def binary_search_by_recursion(
if right < 0:
right = len(sorted_collection) - 1
if list(sorted_collection) != sorted(sorted_collection):
raise ValueError("sorted_collection must be sorted in ascending order")
raise ValueError(
"Input list must be sorted in ascending order for binary search to work"
)
if right < left:
return -1

Expand Down Expand Up @@ -382,7 +390,10 @@ def exponential_search(sorted_collection: list[int], item: int) -> int:
-1
"""
if list(sorted_collection) != sorted(sorted_collection):
raise ValueError("sorted_collection must be sorted in ascending order")
raise ValueError(
"Input list must be sorted in ascending order for binary search to work"
)

bound = 1
while bound < len(sorted_collection) and sorted_collection[bound] < item:
bound *= 2
Expand Down