sorts: type patience_sort's Stack for any comparable item (#15427)

Part of #15234.
This commit is contained in:
Fayupable
2026-09-24 16:08:14 +02:00
committed by GitHub
parent c41bc04f33
commit d961217d5f
2 changed files with 23 additions and 4 deletions
+22 -4
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
from bisect import bisect_left
from functools import total_ordering
from heapq import merge
from typing import Protocol
"""
A pure Python implementation of the patience sort algorithm
@@ -19,16 +20,22 @@ python3 patience_sort.py
"""
class Comparable(Protocol):
def __lt__(self, other: object, /) -> bool: ...
@total_ordering
class Stack(list):
def __lt__(self, other):
class Stack[T: Comparable](list[T]):
def __lt__(self, other: Stack[T]) -> bool:
return self[-1] < other[-1]
def __eq__(self, other):
def __eq__(self, other: object) -> bool:
if not isinstance(other, Stack):
return NotImplemented
return self[-1] == other[-1]
def patience_sort(collection: list) -> list:
def patience_sort[T: Comparable](collection: list[T]) -> list[T]:
"""A pure implementation of patience sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
@@ -44,6 +51,17 @@ def patience_sort(collection: list) -> list:
>>> patience_sort([-3, -17, -48])
[-48, -17, -3]
>>> patience_sort(['d', 'a', 'b', 'e']) == sorted(['d', 'a', 'b', 'e'])
True
>>> patience_sort([3.3, 1.1, 2.2])
[1.1, 2.2, 3.3]
>>> patience_sort([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
stacks: list[Stack] = []
# sort into stacks
+1
View File
@@ -158,6 +158,7 @@ def test_rec_insertion_sort(case) -> None:
odd_even_sort,
odd_even_transposition,
pancake_sort,
patience_sort,
reversort,
selection_sort,
shrink_shell_sort,