Pure python implementation of the iterative Heap's algorithm, 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, 3, 1), (3,
(arr: list)
| 8 | |
| 9 | |
| 10 | def heaps(arr: list) -> list: |
| 11 | """ |
| 12 | Pure python implementation of the iterative Heap's algorithm, |
| 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(n: int, arr: list): |
| 36 | c = [0] * n |
| 37 | res.append(tuple(arr)) |
| 38 | |
| 39 | i = 0 |
| 40 | while i < n: |
| 41 | if c[i] < i: |
| 42 | if i % 2 == 0: |
| 43 | arr[0], arr[i] = arr[i], arr[0] |
| 44 | else: |
| 45 | arr[c[i]], arr[i] = arr[i], arr[c[i]] |
| 46 | res.append(tuple(arr)) |
| 47 | c[i] += 1 |
| 48 | i = 0 |
| 49 | else: |
| 50 | c[i] = 0 |
| 51 | i += 1 |
| 52 | |
| 53 | generate(len(arr), arr) |
| 54 | return res |
| 55 | |
| 56 | |
| 57 | if __name__ == "__main__": |
no test coverage detected