|
| 1 | +from bisect import bisect_left |
| 2 | +from functools import total_ordering |
| 3 | +from heapq import merge |
| 4 | + |
| 5 | +""" |
| 6 | +A pure Python implementation of the patience sort algorithm |
| 7 | +
|
| 8 | +For more information: https://en.wikipedia.org/wiki/Patience_sorting |
| 9 | +
|
| 10 | +This algorithm is based on the card game patience |
| 11 | +
|
| 12 | +For doctests run following command: |
| 13 | +python3 -m doctest -v patience_sort.py |
| 14 | +
|
| 15 | +For manual testing run: |
| 16 | +python3 patience_sort.py |
| 17 | +""" |
| 18 | + |
| 19 | + |
| 20 | +@total_ordering |
| 21 | +class Stack(list): |
| 22 | + def __lt__(self, other): |
| 23 | + return self[-1] < other[-1] |
| 24 | + |
| 25 | + def __eq__(self, other): |
| 26 | + return self[-1] == other[-1] |
| 27 | + |
| 28 | + |
| 29 | +def patience_sort(collection: list) -> list: |
| 30 | + """A pure implementation of quick sort algorithm in Python |
| 31 | +
|
| 32 | + :param collection: some mutable ordered collection with heterogeneous |
| 33 | + comparable items inside |
| 34 | + :return: the same collection ordered by ascending |
| 35 | +
|
| 36 | + Examples: |
| 37 | + >>> patience_sort([1, 9, 5, 21, 17, 6]) |
| 38 | + [1, 5, 6, 9, 17, 21] |
| 39 | +
|
| 40 | + >>> patience_sort([]) |
| 41 | + [] |
| 42 | +
|
| 43 | + >>> patience_sort([-3, -17, -48]) |
| 44 | + [-48, -17, -3] |
| 45 | + """ |
| 46 | + stacks = [] |
| 47 | + # sort into stacks |
| 48 | + for element in collection: |
| 49 | + new_stacks = Stack([element]) |
| 50 | + i = bisect_left(stacks, new_stacks) |
| 51 | + if i != len(stacks): |
| 52 | + stacks[i].append(element) |
| 53 | + else: |
| 54 | + stacks.append(new_stacks) |
| 55 | + |
| 56 | + # use a heap-based merge to merge stack efficiently |
| 57 | + collection[:] = merge(*[reversed(stack) for stack in stacks]) |
| 58 | + return collection |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + user_input = input("Enter numbers separated by a comma:\n").strip() |
| 63 | + unsorted = [int(item) for item in user_input.split(",")] |
| 64 | + print(patience_sort(unsorted)) |
0 commit comments