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