Skip to content

Commit cd402bd

Browse files
committed
types(unknown_sort): constrain items to Comparable
Bind merge_sort's element type to a Comparable Protocol so the signature says "a list of items that can be compared with each other" instead of a bare list, and keeps the element type in the return. start/end are now annotated list[T] so the generic survives the local bindings. Adds doctests for a comparable non-int type (strings, floats) and for the failure mode: mixing non-comparable items must raise TypeError rather than silently mis-sort. The test battery picks the sort up for the shared cases and for the rejection check. It is imported under an alias because sorts/merge_sort.py already exports a merge_sort; the parametrize id therefore shows up as merge_sort0/merge_sort1, the same way shrink_shell_sort already shares the shell_sort id.
1 parent db6bf8a commit cd402bd

2 files changed

Lines changed: 23 additions & 2 deletions

File tree

‎sorts/unknown_sort.py‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,14 @@
55
already O(n)
66
"""
77

8+
from typing import Any, Protocol
89

9-
def merge_sort(collection: list) -> list:
10+
11+
class Comparable(Protocol):
12+
def __lt__(self, other: Any, /) -> bool: ...
13+
14+
15+
def merge_sort[T: Comparable](collection: list[T]) -> list[T]:
1016
"""Pure implementation of the fastest merge sort algorithm in Python
1117
1218
:param collection: some mutable ordered collection with heterogeneous
@@ -22,8 +28,20 @@ def merge_sort(collection: list) -> list:
2228
2329
>>> merge_sort([-2, -5, -45])
2430
[-45, -5, -2]
31+
32+
>>> merge_sort(["banana", "apple", "cherry"])
33+
['apple', 'banana', 'cherry']
34+
35+
>>> merge_sort([3.14, 1.5, 2.7])
36+
[1.5, 2.7, 3.14]
37+
38+
>>> merge_sort([1, "a"]) # doctest: +ELLIPSIS
39+
Traceback (most recent call last):
40+
...
41+
TypeError: ...
2542
"""
26-
start, end = [], []
43+
start: list[T] = []
44+
end: list[T] = []
2745
while len(collection) > 1:
2846
min_one, max_one = min(collection), max(collection)
2947
start.append(min_one)

‎tests/test_sorts.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
from sorts.shrink_shell_sort import shell_sort as shrink_shell_sort
5050
from sorts.stooge_sort import stooge_sort
5151
from sorts.strand_sort import strand_sort
52+
from sorts.unknown_sort import merge_sort as unknown_merge_sort
5253

5354

5455
def test_heap_sort() -> None:
@@ -85,6 +86,7 @@ def test_heap_sort() -> None:
8586
shrink_shell_sort,
8687
stooge_sort,
8788
strand_sort,
89+
unknown_merge_sort,
8890
)
8991

9092

@@ -153,6 +155,7 @@ def test_rec_insertion_sort(case) -> None:
153155
selection_sort,
154156
shrink_shell_sort,
155157
strand_sort,
158+
unknown_merge_sort,
156159
],
157160
ids=lambda f: f.__name__,
158161
)

0 commit comments

Comments
 (0)