Skip to content

Instantly share code, notes, and snippets.

@KKostya
Created May 5, 2020 20:23
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 KKostya/05a0b9249a58c0060e1db5fba5e63d7a to your computer and use it in GitHub Desktop.
Save KKostya/05a0b9249a58c0060e1db5fba5e63d7a to your computer and use it in GitHub Desktop.
Algorithms
# Python3 implementation of Heap's algorithm
# https://en.wikipedia.org/wiki/Heap%27s_algorithm
def heap(lst, k=None):
if k is None: k = len(lst)
if k == 1:
yield(tuple(lst))
return
yield from heap(lst, k - 1)
for i in range(k-1):
m = i if k % 2 == 0 else 0
lst[m], lst[k-1] = lst[k-1], lst[m]
yield from heap(lst, k-1)
# Test
from itertools import permutations
result = list(heap(list(range(5))))
set(permutations(list(range(5)))) == set(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment