Skip to content

Commit 80e645c

Browse files
committed
feat(sorts): make recursive quick sort generic over comparable items
Add a Comparable Protocol + TypeVar bound to recursive_quick_sort's quick_sort() so it is typed list[T] instead of a bare list, matching the pattern in insertion_sort.py. Adds a doctest asserting TypeError on non-comparable mixed-type input and registers it (aliased to recursive_quick_sort to avoid colliding with sorts.quick_sort.quick_sort) in the shared test battery and in test_sort_rejects_non_comparable_items. Part of #15234
1 parent db6bf8a commit 80e645c

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

‎sorts/recursive_quick_sort.py‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,25 @@
1-
def quick_sort(data: list) -> list:
1+
from typing import Any, Protocol, TypeVar
2+
3+
4+
class Comparable(Protocol):
5+
def __lt__(self, other: Any, /) -> bool: ...
6+
7+
8+
T = TypeVar("T", bound=Comparable)
9+
10+
11+
def quick_sort[T: Comparable](data: list[T]) -> list[T]:
212
"""
313
>>> for data in ([2, 1, 0], [2.2, 1.1, 0], "quick_sort"):
414
... quick_sort(data) == sorted(data)
515
True
616
True
717
True
18+
19+
>>> quick_sort([1, "a"])
20+
Traceback (most recent call last):
21+
...
22+
TypeError: '<=' not supported between instances of 'str' and 'int'
823
"""
924
if len(data) <= 1:
1025
return data

‎tests/test_sorts.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
from sorts.quick_sort import quick_sort
4444
from sorts.recursive_insertion_sort import rec_insertion_sort
4545
from sorts.recursive_mergesort_array import merge
46+
from sorts.recursive_quick_sort import quick_sort as recursive_quick_sort
4647
from sorts.reversort import reversort
4748
from sorts.selection_sort import selection_sort
4849
from sorts.shell_sort import shell_sort
@@ -79,6 +80,7 @@ def test_heap_sort() -> None:
7980
pancake_sort,
8081
patience_sort,
8182
quick_sort,
83+
recursive_quick_sort,
8284
reversort,
8385
selection_sort,
8486
shell_sort,
@@ -149,6 +151,7 @@ def test_rec_insertion_sort(case) -> None:
149151
odd_even_sort,
150152
odd_even_transposition,
151153
pancake_sort,
154+
recursive_quick_sort,
152155
reversort,
153156
selection_sort,
154157
shrink_shell_sort,

0 commit comments

Comments
 (0)