You may not need itertools
, but you have the solution in the documentation, where itertools.permutations
is said to be roughly equivalent to:
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = list(range(n))
cycles = list(range(n, n-r, -1))
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
Or using product
:
def permutations(iterable, r=None):
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
for indices in product(range(n), repeat=r):
if len(set(indices)) == r:
yield tuple(pool[i] for i in indices)
They are both generators so you will need to call list(permutations(x))
to retrieve an actual list or substitute the yields
for l.append(v)
where l
is a list defined to accumulate results and v
is the yielded value.
For all the possible sizes ones, iterate over them:
from itertools import chain
check_string = "abcd"
all = list(chain.from_iterable(permutations(check_string , r=x)) for x in range(len(check_string )))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…