fork(1) download
  1. # Generate successive k-length permutations. (2.00)
  2. # @see 3UOMj3
  3.  
  4. def permutations(iterable, k=None):
  5. def detail(a, i, k):
  6. if i == k:
  7. yield tuple(a[:k])
  8. else:
  9. n = len(a)
  10. j = i
  11. while True:
  12. yield from detail(a, i+1, k)
  13. j += 1
  14. if j == n:
  15. break
  16. a[i], a[j] = a[j], a[i]
  17. a.append(a.pop(i))
  18. a = list(iterable)
  19. n = len(a)
  20. k = n if k is None else k
  21. return detail(a, 0, k) if k <= n else []
  22.  
  23. # Test.
  24.  
  25. import itertools
  26. import time
  27.  
  28. n = 3
  29. a = list(range(n))
  30. for k in range(2+len(a)):
  31. print(list(permutations(a, k)))
  32. print(list(itertools.permutations(a, k)))
  33.  
  34. def test(f, a):
  35. t = time.process_time()
  36. for _ in f(a):
  37. pass
  38. t = time.process_time() - t
  39. print('Elapsed: {:.6f}s'.format(t))
  40. m = sum(1 for _ in f(a))
  41. n = sum(1 for _ in itertools.permutations(a))
  42. assert m == n
  43. for x, y in zip(f(a), itertools.permutations(a)):
  44. assert x == y
  45.  
  46. n = 8
  47. a = list(range(n))
  48. test(permutations, a)
  49. test(itertools.permutations, a)
Success #stdin #stdout 0.37s 14076KB
stdin
Standard input is empty
stdout
[()]
[()]
[(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.061983s
Elapsed: 0.004203s