33from bisect import bisect_left
44from functools import total_ordering
55from heapq import merge
6+ from typing import Any , Protocol , TypeVar
67
78"""
89A pure Python implementation of the patience sort algorithm
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
2331class 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
0 commit comments