How do I generate all the permutations of a list? For example:
JavaScript
x
18
18
1
permutations([])
2
[]
3
4
permutations([1])
5
[1]
6
7
permutations([1, 2])
8
[1, 2]
9
[2, 1]
10
11
permutations([1, 2, 3])
12
[1, 2, 3]
13
[1, 3, 2]
14
[2, 1, 3]
15
[2, 3, 1]
16
[3, 1, 2]
17
[3, 2, 1]
18
Advertisement
Answer
Use itertools.permutations
from the standard library:
JavaScript
1
3
1
import itertools
2
list(itertools.permutations([1, 2, 3]))
3
Adapted from here is a demonstration of how itertools.permutations
might be implemented:
JavaScript
1
9
1
def permutations(elements):
2
if len(elements) <= 1:
3
yield elements
4
return
5
for perm in permutations(elements[1:]):
6
for i in range(len(elements)):
7
# nb elements[0:1] works in both string and list contexts
8
yield perm[:i] + elements[0:1] + perm[i:]
9
A couple of alternative approaches are listed in the documentation of itertools.permutations
. Here’s one:
JavaScript
1
25
25
1
def permutations(iterable, r=None):
2
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
3
# permutations(range(3)) --> 012 021 102 120 201 210
4
pool = tuple(iterable)
5
n = len(pool)
6
r = n if r is None else r
7
if r > n:
8
return
9
indices = range(n)
10
cycles = range(n, n-r, -1)
11
yield tuple(pool[i] for i in indices[:r])
12
while n:
13
for i in reversed(range(r)):
14
cycles[i] -= 1
15
if cycles[i] == 0:
16
indices[i:] = indices[i+1:] + indices[i:i+1]
17
cycles[i] = n - i
18
else:
19
j = cycles[i]
20
indices[i], indices[-j] = indices[-j], indices[i]
21
yield tuple(pool[i] for i in indices[:r])
22
break
23
else:
24
return
25
And another, based on itertools.product
:
JavaScript
1
8
1
def permutations(iterable, r=None):
2
pool = tuple(iterable)
3
n = len(pool)
4
r = n if r is None else r
5
for indices in product(range(n), repeat=r):
6
if len(set(indices)) == r:
7
yield tuple(pool[i] for i in indices)
8