diff --git a/sorts/adaptive_merge_sort.py b/sorts/adaptive_merge_sort.py index 2df5c3924a8d..157532aab98d 100644 --- a/sorts/adaptive_merge_sort.py +++ b/sorts/adaptive_merge_sort.py @@ -49,7 +49,7 @@ def merge(array: list, aux: list, low: int, mid: int, high: int) -> None: for k in range(low, high + 1): array[k] = aux[k] - print(f"After merge: {array[low:high + 1]}") + print(f"After merge: {array[low : high + 1]}") # Example usage diff --git a/sorts/binary_insertion_sort.py b/sorts/binary_insertion_sort.py index b928316a849d..f974a97f316e 100644 --- a/sorts/binary_insertion_sort.py +++ b/sorts/binary_insertion_sort.py @@ -10,8 +10,17 @@ python binary_insertion_sort.py """ +from typing import Protocol, TypeVar -def binary_insertion_sort(collection: list) -> list: + +class Comparable(Protocol): + def __lt__(self, other: object, /) -> bool: ... + + +T = TypeVar("T", bound=Comparable) + + +def binary_insertion_sort[T: Comparable](collection: list[T]) -> list[T]: """ Sorts a list using the binary insertion sort algorithm. @@ -36,6 +45,10 @@ def binary_insertion_sort(collection: list) -> list: >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> binary_insertion_sort(collection) == sorted(collection) True + >>> binary_insertion_sort([1, "a"]) + Traceback (most recent call last): + ... + TypeError: '<' not supported between instances of 'str' and 'int' """ n = len(collection) diff --git a/tests/test_sorts.py b/tests/test_sorts.py index e24f177cf72c..6de12789dd0a 100644 --- a/tests/test_sorts.py +++ b/tests/test_sorts.py @@ -87,3 +87,8 @@ def test_heap_sort(): def test_sort_matches_builtin(sort, case): """Each sort must reproduce the ordering of the built-in ``sorted``.""" assert list(sort(list(case))) == sorted(case) + + +def test_binary_insertion_sort_rejects_non_comparable_items(): + with pytest.raises(TypeError): + binary_insertion_sort([1, "a"])