Improve sorted input validation in binary search (#14074)

* Improve sorted input validation in binary search

* Update binary_search.py

* Update binary_search.py

* Update binary_search.py

---------

Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
This commit is contained in:
Yaswanth Naga Sai K
2026-03-09 11:25:03 +05:30
committed by GitHub
parent 589d12972d
commit 7af5aba250

View File

@@ -10,9 +10,8 @@ For manual testing run:
python3 binary_search.py
"""
from __future__ import annotations
import bisect
from itertools import pairwise
def bisect_left(
@@ -198,7 +197,7 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
>>> binary_search([0, 5, 7, 10, 15], 6)
-1
"""
if list(sorted_collection) != sorted(sorted_collection):
if any(a > b for a, b in pairwise(sorted_collection)):
raise ValueError("sorted_collection must be sorted in ascending order")
left = 0
right = len(sorted_collection) - 1