From 9a2ea7cea8b93a85447bd31e8ea660327469f2df Mon Sep 17 00:00:00 2001 From: Scott Date: Wed, 26 Jan 2022 11:24:46 -0800 Subject: [PATCH] Sanity check list is sorted before binary search. --- list_utils.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/list_utils.py b/list_utils.py index 88c436b..1b27436 100644 --- a/list_utils.py +++ b/list_utils.py @@ -248,7 +248,18 @@ def binary_search(lst: Sequence[Any], target: Any) -> Tuple[bool, int]: >>> binary_search(a, 2) (False, 1) + >>> a.append(9) + >>> binary_search(a, 4) + Traceback (most recent call last): + ... + AssertionError + """ + last = None + for x in lst: + if last is not None: + assert x >= last # This asserts iff the list isn't sorted + last = x # in ascending order. return _binary_search(lst, target, 0, len(lst) - 1) -- 2.46.0