Skip to content

Commit 5f40ffe

Browse files
feat(sorts): make patience_sort generic over comparables (#15234)
1 parent 52b9b91 commit 5f40ffe

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

‎sorts/patience_sort.py‎

Lines changed: 19 additions & 1 deletion
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 Any, Protocol, TypeVar
67

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

2122

23+
class Comparable(Protocol):
24+
def __lt__(self, other: Any, /) -> bool: ...
25+
26+
27+
T = TypeVar("T", bound=Comparable)
28+
29+
2230
@total_ordering
2331
class Stack(list):
2432
def __lt__(self, other):
@@ -28,7 +36,7 @@ def __eq__(self, other):
2836
return self[-1] == other[-1]
2937

3038

31-
def patience_sort(collection: list) -> list:
39+
def patience_sort[T: Comparable](collection: list[T]) -> list[T]:
3240
"""A pure implementation of patience sort algorithm in Python
3341
3442
:param collection: some mutable ordered collection with heterogeneous
@@ -44,6 +52,16 @@ def patience_sort(collection: list) -> list:
4452
4553
>>> patience_sort([-3, -17, -48])
4654
[-48, -17, -3]
55+
56+
>>> patience_sort(["c", "a", "b"]) == ["a", "b", "c"]
57+
True
58+
59+
>>> patience_sort([2.5, -1, 0.0]) == [-1, 0.0, 2.5]
60+
True
61+
62+
>>> import pytest
63+
>>> with pytest.raises(TypeError):
64+
... patience_sort([1, "a"])
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
@@ -140,6 +140,7 @@ def test_rec_insertion_sort(case) -> None:
140140
merge_sort,
141141
odd_even_sort,
142142
pancake_sort,
143+
patience_sort,
143144
selection_sort,
144145
shrink_shell_sort,
145146
strand_sort,

0 commit comments

Comments
 (0)