Last active
December 18, 2022 07:38
-
-
Save brianpursley/57bbaf0a8823e51012bc to your computer and use it in GitHub Desktop.
This is a Python implementation of the QuickPerm algorithm described by Phillip Paul Fuchs at http://www.quickperm.org that generates all permutations of a list without using recursion
This file contains 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
#!/usr/bin/env python | |
# | |
# This is a Python implementation of the QuickPerm algorithm described by Phillip Paul Fuchs at http://www.quickperm.org | |
# that generates all permutations of a list without using recursion. | |
# | |
a = ['a', 'b', 'c', 'd'] | |
N = len(a) | |
p = range(0, N + 1) | |
i = 1 | |
print a | |
while i < N: | |
p[i] -= 1 | |
if i % 2 == 1: | |
j = p[i] | |
else: | |
j = 0 | |
a[j], a[i] = a[i], a[j] | |
print a | |
i = 1 | |
while p[i] == 0: | |
p[i] = i | |
i += 1 |
A little modification which use only single yield (instead of two prints), so that no duplicated inline codes and look nicer to me.
def quickperm(a):
N = len(a)
p = [*range(N+1)]
i = 1
while True:
yield a
if i >= N: break
p[i] -= 1
j = 0 if i % 2 == 0 else p[i]
a[j], a[i] = a[i], a[j]
i = 1
while p[i] == 0:
p[i] = i
i += 1
does anyone have a parallel version of this, eg. using 2 or more cores ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks pretty epic bro legit 😎