Pure python implementation of the Heap's algorithm (recursive version), returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2,
(arr: list)
| 8 | |
| 9 | |
| 10 | def heaps(arr: list) -> list: |
| 11 | """ |
| 12 | Pure python implementation of the Heap's algorithm (recursive version), |
| 13 | returning all permutations of a list. |
| 14 | >>> heaps([]) |
| 15 | [()] |
| 16 | >>> heaps([0]) |
| 17 | [(0,)] |
| 18 | >>> heaps([-1, 1]) |
| 19 | [(-1, 1), (1, -1)] |
| 20 | >>> heaps([1, 2, 3]) |
| 21 | [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] |
| 22 | >>> from itertools import permutations |
| 23 | >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) |
| 24 | True |
| 25 | >>> all(sorted(heaps(x)) == sorted(permutations(x)) |
| 26 | ... for x in ([], [0], [-1, 1], [1, 2, 3])) |
| 27 | True |
| 28 | """ |
| 29 | |
| 30 | if len(arr) <= 1: |
| 31 | return [tuple(arr)] |
| 32 | |
| 33 | res = [] |
| 34 | |
| 35 | def generate(k: int, arr: list): |
| 36 | if k == 1: |
| 37 | res.append(tuple(arr[:])) |
| 38 | return |
| 39 | |
| 40 | generate(k - 1, arr) |
| 41 | |
| 42 | for i in range(k - 1): |
| 43 | if k % 2 == 0: # k is even |
| 44 | arr[i], arr[k - 1] = arr[k - 1], arr[i] |
| 45 | else: # k is odd |
| 46 | arr[0], arr[k - 1] = arr[k - 1], arr[0] |
| 47 | generate(k - 1, arr) |
| 48 | |
| 49 | generate(len(arr), arr) |
| 50 | return res |
| 51 | |
| 52 | |
| 53 | if __name__ == "__main__": |
no test coverage detected