Skip to content

Commit d0d5bdd

Browse files
committed
Improve binary insertion sort comparable typing
1 parent 3725b91 commit d0d5bdd

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

‎sorts/binary_insertion_sort.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,16 @@
1010
python binary_insertion_sort.py
1111
"""
1212

13+
from typing import Protocol, TypeVar
1314

14-
def binary_insertion_sort(collection: list) -> list:
15+
16+
class Comparable(Protocol):
17+
def __lt__(self, other: object, /) -> bool: ...
18+
19+
20+
T = TypeVar("T", bound=Comparable)
21+
22+
def binary_insertion_sort(collection: list[T]) -> list[T]:
1523
"""
1624
Sorts a list using the binary insertion sort algorithm.
1725
@@ -36,6 +44,10 @@ def binary_insertion_sort(collection: list) -> list:
3644
>>> collection = random.choices(string.ascii_letters + string.digits, k=100)
3745
>>> binary_insertion_sort(collection) == sorted(collection)
3846
True
47+
>>> binary_insertion_sort([1, "a"])
48+
Traceback (most recent call last):
49+
...
50+
TypeError: '<' not supported between instances of 'str' and 'int'
3951
"""
4052

4153
n = len(collection)

‎tests/test_sorts.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,3 +87,8 @@ def test_heap_sort():
8787
def test_sort_matches_builtin(sort, case):
8888
"""Each sort must reproduce the ordering of the built-in ``sorted``."""
8989
assert list(sort(list(case))) == sorted(case)
90+
91+
92+
def test_binary_insertion_sort_rejects_non_comparable_items():
93+
with pytest.raises(TypeError):
94+
binary_insertion_sort([1, "a"])

0 commit comments

Comments
 (0)