Адаптированная из здесь демонстрация того, как itertools.permutations может быть реализована:
defpermutations(elements): iflen(elements) <= 1: yield elements return for perm in permutations(elements[1:]): for i inrange(len(elements)): # nb elements[0:1] works in both string and list contexts yield perm[:i] + elements[0:1] + perm[i:]
Пара альтернативных подходов перечислены в документации itertools.permutations. Вот один:
defpermutations(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 isNoneelse r if r > n: return indices = range(n) cycles = range(n, n-r, -1) yieldtuple(pool[i] for i in indices[:r]) while n: for i inreversed(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] yieldtuple(pool[i] for i in indices[:r]) break else: return
И еще один, основанный на itertools.product:
defpermutations(iterable, r=None): pool = tuple(iterable) n = len(pool) r = n if r isNoneelse r for indices in product(range(n), repeat=r): iflen(set(indices)) == r: yieldtuple(pool[i] for i in indices)