# Generate successive k-length permutations. def permutations(iterable, k=None): def detail(a, k): if k == 0: yield () else: for i, first in enumerate(a): for rest in detail(a[:i] + a[i+1:], k-1): yield (first, *rest) a = list(iterable) return detail(a, len(a) if k is None else k) # Test. import itertools import time n = 3 a = list(range(n)) for k in range(2+len(a)): print(list(permutations(a, k))) print(list(itertools.permutations(a, k))) def test(f, a): t = time.process_time() for _ in f(a): pass t = time.process_time() - t print('Elapsed: {:.6f}s'.format(t)) m = sum(1 for _ in f(a)) n = sum(1 for _ in itertools.permutations(a)) assert m == n for x, y in zip(f(a), itertools.permutations(a)): assert x == y n = 8 a = list(range(n)) test(permutations, a) test(itertools.permutations, a)
Standard input is empty
[()] [()] [(0,), (1,), (2,)] [(0,), (1,), (2,)] [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)] [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)] [] [] Elapsed: 0.143499s Elapsed: 0.002776s