Advertisement
here2share

# combopermute.py

May 1st, 2021 (edited)
1,067
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. # combopermute.py
  2.  
  3. def combinations(iterable, r):
  4.     pool = tuple(iterable)
  5.     n = len(pool)
  6.     if r > n:
  7.         return
  8.     indices = list(range(r))
  9.     yield tuple(pool[i] for i in indices)
  10.     while True:
  11.         for i in reversed(range(r)):
  12.             if indices[i] != i + n - r:
  13.                 break
  14.         else:
  15.             return
  16.         indices[i] += 1
  17.         for j in range(i+1, r):
  18.             indices[j] = indices[j-1] + 1
  19.         yield tuple(pool[i] for i in indices)
  20.        
  21. def all_perms(elements):
  22.     if len(elements) <=1:
  23.         yield elements
  24.     else:
  25.         for perm in all_perms(elements[1:]):
  26.             for i in range(len(elements)):
  27.                 yield perm[:i] + elements[0:1] + perm[i:]
  28.        
  29. def combopermute(l, n):
  30.     for i in combinations(l, n):
  31.         for j in all_perms(i):
  32.             yield j
  33.  
  34. # speed demonstration
  35. l = [1,2,3,9]
  36. n = 3
  37. test = combopermute(l, n)
  38.  
  39. for t in test:
  40.     print(t)
  41.    
  42. (1, 2, 3)
  43. (2, 1, 3)
  44. (2, 3, 1)
  45. (1, 3, 2)
  46. (3, 1, 2)
  47. (3, 2, 1)
  48. (1, 2, 9)
  49. (2, 1, 9)
  50. (2, 9, 1)
  51. (1, 9, 2)
  52. (9, 1, 2)
  53. (9, 2, 1)
  54. (1, 3, 9)
  55. (3, 1, 9)
  56. (3, 9, 1)
  57. (1, 9, 3)
  58. (9, 1, 3)
  59. (9, 3, 1)
  60. (2, 3, 9)
  61. (3, 2, 9)
  62. (3, 9, 2)
  63. (2, 9, 3)
  64. (9, 2, 3)
  65. (9, 3, 2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement