Advertisement
here2share

# yield_combos.py

Mar 25th, 2021
1,103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.55 KB | None | 0 0
  1. # yield_combos.py
  2.  
  3. def combos(iterable, r):
  4.     iter = tuple(iterable)
  5.     n = len(iter)
  6.     if r > n:
  7.         return
  8.     indices = range(r)
  9.     yield tuple(iter[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(iter[i] for i in indices)
  20.  
  21. z = combos('ABCD', 2) # --> AB AC AD BC BD CD
  22. while 1:
  23.     try:
  24.         print next(z)
  25.     except:
  26.         break
  27. for z in combos(range(4), 3): # --> 012 013 023 123
  28.     print z
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement