Skip to content

Commit 032afb5

Browse files
authored
sorts: type slowsort for any comparable items (#15347)
1 parent 4d05248 commit 032afb5

1 file changed

Lines changed: 17 additions & 1 deletion

File tree

‎sorts/slowsort.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,31 @@
1111

1212
from __future__ import annotations
1313

14+
from typing import Protocol
1415

15-
def slowsort(sequence: list, start: int | None = None, end: int | None = None) -> None:
16+
17+
class Comparable(Protocol):
18+
def __lt__(self, other: object, /) -> bool: ...
19+
20+
21+
def slowsort[T: Comparable](
22+
sequence: list[T], start: int | None = None, end: int | None = None
23+
) -> None:
1624
"""
1725
Sorts sequence[start..end] (both inclusive) in-place.
1826
start defaults to 0 if not given.
1927
end defaults to len(sequence) - 1 if not given.
2028
It returns None.
2129
>>> seq = [1, 6, 2, 5, 3, 4, 4, 5]; slowsort(seq); seq
2230
[1, 2, 3, 4, 4, 5, 5, 6]
31+
>>> seq = ["c", "a", "b"]; slowsort(seq); seq
32+
['a', 'b', 'c']
33+
>>> seq = [2.5, -1, 0.0]; slowsort(seq); seq
34+
[-1, 0.0, 2.5]
35+
>>> slowsort([1, "a"])
36+
Traceback (most recent call last):
37+
...
38+
TypeError: '<' not supported between instances of 'str' and 'int'
2339
>>> seq = []; slowsort(seq); seq
2440
[]
2541
>>> seq = [2]; slowsort(seq); seq

0 commit comments

Comments
 (0)