Sanity check list is sorted before binary search.
authorScott <[email protected]>
Wed, 26 Jan 2022 19:24:46 +0000 (11:24 -0800)
committerScott <[email protected]>
Wed, 26 Jan 2022 19:24:46 +0000 (11:24 -0800)
list_utils.py

index 88c436be24f88e73093f2c6f509a157e181ed6f9..1b27436021cc6ab17a9b264e22737d07f3a1ec3c 100644 (file)
@@ -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)