Skip to content

Commit d961217

Browse files
authored
sorts: type patience_sort's Stack for any comparable item (#15427)
Part of #15234.
1 parent c41bc04 commit d961217

2 files changed

Lines changed: 23 additions & 4 deletions

File tree

‎sorts/patience_sort.py‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from bisect import bisect_left
44
from functools import total_ordering
55
from heapq import merge
6+
from typing import Protocol
67

78
"""
89
A pure Python implementation of the patience sort algorithm
@@ -19,16 +20,22 @@
1920
"""
2021

2122

23+
class Comparable(Protocol):
24+
def __lt__(self, other: object, /) -> bool: ...
25+
26+
2227
@total_ordering
23-
class Stack(list):
24-
def __lt__(self, other):
28+
class Stack[T: Comparable](list[T]):
29+
def __lt__(self, other: Stack[T]) -> bool:
2530
return self[-1] < other[-1]
2631

27-
def __eq__(self, other):
32+
def __eq__(self, other: object) -> bool:
33+
if not isinstance(other, Stack):
34+
return NotImplemented
2835
return self[-1] == other[-1]
2936

3037

31-
def patience_sort(collection: list) -> list:
38+
def patience_sort[T: Comparable](collection: list[T]) -> list[T]:
3239
"""A pure implementation of patience sort algorithm in Python
3340
3441
:param collection: some mutable ordered collection with heterogeneous
@@ -44,6 +51,17 @@ def patience_sort(collection: list) -> list:
4451
4552
>>> patience_sort([-3, -17, -48])
4653
[-48, -17, -3]
54+
55+
>>> patience_sort(['d', 'a', 'b', 'e']) == sorted(['d', 'a', 'b', 'e'])
56+
True
57+
58+
>>> patience_sort([3.3, 1.1, 2.2])
59+
[1.1, 2.2, 3.3]
60+
61+
>>> patience_sort([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL
62+
Traceback (most recent call last):
63+
...
64+
TypeError: '<' not supported between instances of 'str' and 'int'
4765
"""
4866
stacks: list[Stack] = []
4967
# sort into stacks

‎tests/test_sorts.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ def test_rec_insertion_sort(case) -> None:
158158
odd_even_sort,
159159
odd_even_transposition,
160160
pancake_sort,
161+
patience_sort,
161162
reversort,
162163
selection_sort,
163164
shrink_shell_sort,

0 commit comments

Comments
 (0)