From: Scott Date: Wed, 26 Jan 2022 19:24:46 +0000 (-0800) Subject: Sanity check list is sorted before binary search. X-Git-Url: https://wannabe.guru.org/gitweb/?a=commitdiff_plain;h=9a2ea7cea8b93a85447bd31e8ea660327469f2df;hp=4c86d98e337703016afc7122cd165bb2498b88bc;p=python_utils.git Sanity check list is sorted before binary search. --- 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)