Created
May 5, 2020 20:23
-
-
Save KKostya/05a0b9249a58c0060e1db5fba5e63d7a to your computer and use it in GitHub Desktop.
Algorithms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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