Skip to content

Commit d0f9b6e

Browse files
snehapriy958pre-commit-ci[bot]cclauss
authored
Improve binary insertion sort comparable typing (#15238)
* Improve binary insertion sort comparable typing * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update binary_insertion_sort function signature * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 3f4ce7a commit d0f9b6e

3 files changed

Lines changed: 20 additions & 2 deletions

File tree

‎sorts/adaptive_merge_sort.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def merge(array: list, aux: list, low: int, mid: int, high: int) -> None:
4949
for k in range(low, high + 1):
5050
array[k] = aux[k]
5151

52-
print(f"After merge: {array[low:high + 1]}")
52+
print(f"After merge: {array[low : high + 1]}")
5353

5454

5555
# Example usage

‎sorts/binary_insertion_sort.py‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,17 @@
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+
23+
def binary_insertion_sort[T: Comparable](collection: list[T]) -> list[T]:
1524
"""
1625
Sorts a list using the binary insertion sort algorithm.
1726
@@ -36,6 +45,10 @@ def binary_insertion_sort(collection: list) -> list:
3645
>>> collection = random.choices(string.ascii_letters + string.digits, k=100)
3746
>>> binary_insertion_sort(collection) == sorted(collection)
3847
True
48+
>>> binary_insertion_sort([1, "a"])
49+
Traceback (most recent call last):
50+
...
51+
TypeError: '<' not supported between instances of 'str' and 'int'
3952
"""
4053

4154
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)