Skip to content

Commit 04322e6

Browse files
authored
Heaps algorithm iterative (TheAlgorithms#2505)
* heap's algorithm iterative * doctest * doctest * rebuild
1 parent 9016fe1 commit 04322e6

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""
2+
Heap's (iterative) algorithm returns the list of all permutations possible from a list.
3+
It minimizes movement by generating each permutation from the previous one
4+
by swapping only two elements.
5+
More information:
6+
https://en.wikipedia.org/wiki/Heap%27s_algorithm.
7+
"""
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__":
58+
user_input = input("Enter numbers separated by a comma:\n").strip()
59+
arr = [int(item) for item in user_input.split(",")]
60+
print(heaps(arr))

0 commit comments

Comments
 (0)