Skip to content

Commit 1208665

Browse files
committed
Added Patience Sort
1 parent 5c18392 commit 1208665

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from functools import total_ordering
2+
from bisect import bisect_left
3+
from heapq import merge
4+
5+
@total_ordering
6+
class Pile(list):
7+
def __lt__(self, other): return self[-1] < other[-1]
8+
def __eq__(self, other): return self[-1] == other[-1]
9+
10+
def patience_sort(n):
11+
piles = []
12+
# sort into piles
13+
for x in n:
14+
new_pile = Pile([x])
15+
i = bisect_left(piles, new_pile)
16+
if i != len(piles):
17+
piles[i].append(x)
18+
else:
19+
piles.append(new_pile)
20+
21+
# use a heap-based merge to merge piles efficiently
22+
n[:] = merge(*[reversed(pile) for pile in piles])
23+
24+
if __name__ == "__main__":
25+
a = [4, 65, 2, -31, 0, 99, 83, 782, 1]
26+
patience_sort(a)
27+
print a

0 commit comments

Comments
 (0)