- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathpatience_sort.py
66 lines (48 loc) · 1.65 KB
/
patience_sort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from __future__ importannotations
frombisectimportbisect_left
fromfunctoolsimporttotal_ordering
fromheapqimportmerge
"""
A pure Python implementation of the patience sort algorithm
For more information: https://en.wikipedia.org/wiki/Patience_sorting
This algorithm is based on the card game patience
For doctests run following command:
python3 -m doctest -v patience_sort.py
For manual testing run:
python3 patience_sort.py
"""
@total_ordering
classStack(list):
def__lt__(self, other):
returnself[-1] <other[-1]
def__eq__(self, other):
returnself[-1] ==other[-1]
defpatience_sort(collection: list) ->list:
"""A pure implementation of patience sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> patience_sort([1, 9, 5, 21, 17, 6])
[1, 5, 6, 9, 17, 21]
>>> patience_sort([])
[]
>>> patience_sort([-3, -17, -48])
[-48, -17, -3]
"""
stacks: list[Stack] = []
# sort into stacks
forelementincollection:
new_stacks=Stack([element])
i=bisect_left(stacks, new_stacks)
ifi!=len(stacks):
stacks[i].append(element)
else:
stacks.append(new_stacks)
# use a heap-based merge to merge stack efficiently
collection[:] =merge(*(reversed(stack) forstackinstacks))
returncollection
if__name__=="__main__":
user_input=input("Enter numbers separated by a comma:\n").strip()
unsorted= [int(item) foriteminuser_input.split(",")]
print(patience_sort(unsorted))