fork(1) download
  1. # Generate successive k-length permutations. (4.00)
  2. # @note Rewrite of the code that appears at
  3. # docs.python.org/3/library/itertools.html#itertools.permutations
  4. # (restores indirect indexing)
  5. # @see 3UOMj3, vSELdo, cTaz9y
  6.  
  7. def permutations(iterable, k=None):
  8. pool = tuple(iterable)
  9. n = len(pool)
  10. if k is None:
  11. k = n
  12. elif k > n:
  13. return
  14. index = list(range(n))
  15. cycle = list(range(k))
  16.  
  17. while True:
  18. yield tuple(pool[i] for i in index[:k])
  19. for i in reversed(range(k)):
  20. j = cycle[i] + 1
  21. if j < n:
  22. cycle[i] = j
  23. index[i], index[j] = index[j], index[i]
  24. break
  25. cycle[i] = i
  26. index.append(index.pop(i))
  27. else:
  28. return
  29.  
  30. # Test.
  31.  
  32. import itertools
  33. import time
  34.  
  35. n = 3
  36. a = list(range(n))
  37. for k in range(2+len(a)):
  38. print(list(permutations(a, k)))
  39. print(list(itertools.permutations(a, k)))
  40.  
  41. def test(f, a):
  42. t = time.process_time()
  43. for _ in f(a):
  44. pass
  45. t = time.process_time() - t
  46. print('Elapsed: {:.6f}s'.format(t))
  47. m = sum(1 for _ in f(a))
  48. n = sum(1 for _ in itertools.permutations(a))
  49. assert m == n
  50. for x, y in zip(f(a), itertools.permutations(a)):
  51. assert x == y
  52.  
  53. n = 8
  54. a = list(range(n))
  55. test(permutations, a)
  56. test(itertools.permutations, a)
Success #stdin #stdout 0.31s 14080KB
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.065700s
Elapsed: 0.004203s