Instantly share code, notes, and snippets.

# brianpursley/quickperm.py

Last active December 18, 2022 07:38
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

### Fate1405 commented Mar 21, 2022

thanks pretty epic bro legit 😎

### jackhftang commented Apr 6, 2022 • edited

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```

### lydonchandra commented Dec 18, 2022

does anyone have a parallel version of this, eg. using 2 or more cores ?