Skip to content

Commit 7bc2e3d

Browse files
committed
add style fix
1 parent c181ce9 commit 7bc2e3d

2 files changed

Lines changed: 21 additions & 2 deletions

File tree

DynamicProgramming/permutations/heap_algorithm.py renamed to permutations/heap_algorithm.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,35 @@
66
"""
77
Heap's algorithm
88
https://en.wikipedia.org/wiki/Heap%27s_algorithm
9+
https://www.geeksforgeeks.org/heaps-algorithm-for-generating-permutations/
910
"""
1011
from typing import List
1112

1213

14+
def heap_permutation(elements: List[int], size: int, res: List[List[int]]):
15+
"""Generating permutation using Heap Algorithm """
16+
# if size becomes 1 then prints the obtained
17+
# permutation
18+
if size == 1:
19+
res.append(elements[:])
20+
return
21+
for i in range(size):
22+
heap_permutation(elements, size - 1, res)
23+
# if size is odd, swap first and last
24+
# element
25+
# else If size is even, swap ith and last element
26+
if size & 1:
27+
elements[0], elements[size - 1] = elements[size - 1], elements[0]
28+
else:
29+
elements[i], elements[size - 1] = elements[size - 1], elements[i]
30+
31+
1332
def all_perms(elements: List[int], n: int):
1433
if n == 1:
1534
yield elements[:]
1635
else:
17-
for i in range(n-1):
18-
for hp in all_perms(elements, n-1):
36+
for i in range(n - 1):
37+
for hp in all_perms(elements, n - 1):
1938
yield hp
2039
if n % 2 == 0:
2140
elements[i], elements[n-1] = elements[n-1], elements[i]
File renamed without changes.

0 commit comments

Comments
 (0)