Skip to content

Instantly share code, notes, and snippets.

@andyg0808
Created May 31, 2020 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyg0808/33dba710ccd0f8289a05c5d1893586d2 to your computer and use it in GitHub Desktop.
Save andyg0808/33dba710ccd0f8289a05c5d1893586d2 to your computer and use it in GitHub Desktop.
Heap's algorithm in Python
from typing import List
def swap(A, i, j):
temp = A[i]
A[i] = A[j]
A[j] = temp
def generate(k: int, A: List):
if k == 1:
return [A.copy()]
else:
res = generate(k - 1, A)
for i in range(k - 1):
if k % 2 == 0:
swap(A, i, k - 1)
else:
swap(A, 0, k - 1)
res = res + generate(k - 1, A)
return res
def yield_generate(k: int, A: List):
if k == 1:
yield A.copy()
else:
yield from generate(k - 1, A)
for i in range(k - 1):
if k % 2 == 0:
swap(A, i, k - 1)
else:
swap(A, 0, k - 1)
yield from generate(k - 1, A)
l = list(range(14))
val = yield_generate(len(l), l)
for i in val:
print(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment