Skip to content

Commit d95d643

Browse files
authored
Heaps algorithm (TheAlgorithms#2475)
* heaps_algorithm: new algo * typo * correction doctest * doctests: compare with itertools.permutations * doctest: sorted instead of set * doctest * doctest * rebuild
1 parent 04322e6 commit d95d643

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

divide_and_conquer/heaps_algorithm.py

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
"""
2+
Heap's 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 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__":
54+
user_input = input("Enter numbers separated by a comma:\n").strip()
55+
arr = [int(item) for item in user_input.split(",")]
56+
print(heaps(arr))

0 commit comments

Comments
 (0)