Advertisement
here2share

# combopermute_unlimited_fast.py

Jul 5th, 2023
1,246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. # combopermute_unlimited_fast.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 = list(range(100))
  36. n = 30
  37. test = combopermute(l, n)
  38.  
  39. for t in test:
  40.     print(t)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement