File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1010python 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 )
Original file line number Diff line number Diff line change @@ -87,3 +87,8 @@ def test_heap_sort():
8787def 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" ])
You can’t perform that action at this time.
0 commit comments