sorts: type slowsort for any comparable items (#15347)

This commit is contained in:
0x
2026-09-18 02:39:28 +02:00
committed by GitHub
parent 4d05248be3
commit 032afb52de
+17 -1
View File
@@ -11,8 +11,16 @@ Source: https://en.wikipedia.org/wiki/Slowsort
from __future__ import annotations
from typing import Protocol
def slowsort(sequence: list, start: int | None = None, end: int | None = None) -> None:
class Comparable(Protocol):
def __lt__(self, other: object, /) -> bool: ...
def slowsort[T: Comparable](
sequence: list[T], start: int | None = None, end: int | None = None
) -> None:
"""
Sorts sequence[start..end] (both inclusive) in-place.
start defaults to 0 if not given.
@@ -20,6 +28,14 @@ def slowsort(sequence: list, start: int | None = None, end: int | None = None) -
It returns None.
>>> seq = [1, 6, 2, 5, 3, 4, 4, 5]; slowsort(seq); seq
[1, 2, 3, 4, 4, 5, 5, 6]
>>> seq = ["c", "a", "b"]; slowsort(seq); seq
['a', 'b', 'c']
>>> seq = [2.5, -1, 0.0]; slowsort(seq); seq
[-1, 0.0, 2.5]
>>> slowsort([1, "a"])
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
>>> seq = []; slowsort(seq); seq
[]
>>> seq = [2]; slowsort(seq); seq