omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / patience-sort / oracle.py
| 1 | # Independent reference for "Sorting algorithms/Patience sort" (Python 3, standard library only). |
| 2 | # expected.txt is this program's stdout; omc never produced it. |
| 3 | import heapq |
| 4 | a = [4, 65, 2, -31, 0, 99, 83, 782, 1, 4, -31, 18] |
| 5 | print(*a) |
| 6 | piles = [] |
| 7 | for v in a: |
| 8 | for p in piles: |
| 9 | if p[-1] >= v: |
| 10 | p.append(v) |
| 11 | break |
| 12 | else: |
| 13 | piles.append([v]) |
| 14 | heap = [(p[-1], i) for i, p in enumerate(piles)] |
| 15 | heapq.heapify(heap) |
| 16 | out = [] |
| 17 | while heap: |
| 18 | v, i = heapq.heappop(heap) |
| 19 | out.append(piles[i].pop()) |
| 20 | if piles[i]: |
| 21 | heapq.heappush(heap, (piles[i][-1], i)) |
| 22 | assert out == sorted(a) |
| 23 | print(*out) |