Skip to content

Commit c41bc04

Browse files
authored
sorts: type unknown_sort's merge_sort for any comparable item (#15426)
Part of #15234.
1 parent a1fb42f commit c41bc04

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

‎sorts/unknown_sort.py‎

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

8+
from typing import Protocol
89

9-
def merge_sort(collection: list) -> list:
10+
11+
class Comparable(Protocol):
12+
def __lt__(self, other: object, /) -> 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,6 +28,17 @@ def merge_sort(collection: list) -> list:
2228
2329
>>> merge_sort([-2, -5, -45])
2430
[-45, -5, -2]
31+
32+
>>> merge_sort(['d', 'a', 'b', 'e']) == sorted(['d', 'a', 'b', 'e'])
33+
True
34+
35+
>>> merge_sort([1.1, 3.3, 5.5, 2.2, 4.4])
36+
[1.1, 2.2, 3.3, 4.4, 5.5]
37+
38+
>>> merge_sort([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL
39+
Traceback (most recent call last):
40+
...
41+
TypeError: '<' not supported between instances of 'str' and 'int'
2542
"""
2643
start, end = [], []
2744
while len(collection) > 1:

‎tests/test_sorts.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
from sorts.shrink_shell_sort import shell_sort as shrink_shell_sort
5252
from sorts.stooge_sort import stooge_sort
5353
from sorts.strand_sort import strand_sort
54+
from sorts.unknown_sort import merge_sort as unknown_sort
5455

5556

5657
def test_heap_sort() -> None:
@@ -89,6 +90,7 @@ def test_heap_sort() -> None:
8990
shrink_shell_sort,
9091
stooge_sort,
9192
strand_sort,
93+
unknown_sort,
9294
)
9395

9496

@@ -160,6 +162,7 @@ def test_rec_insertion_sort(case) -> None:
160162
selection_sort,
161163
shrink_shell_sort,
162164
strand_sort,
165+
unknown_sort,
163166
],
164167
ids=lambda f: f.__name__,
165168
)

0 commit comments

Comments
 (0)