tyrion

product.py

Oct 24th, 2014
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | None | 0 0
  1. def product(*iterables):
  2.     if iterables:
  3.         first, *others = iterables
  4.         for x in first:
  5.             for xs in product(*others):
  6.                 yield [x] + xs
  7.     else:
  8.         yield []
  9.  
  10. def product(*iterables):
  11.     if not iterables:
  12.         return
  13.     iters = [iter(xs) for xs in iterables]
  14.     last = len(iters)-1
  15.     i = 0
  16.     row = [0] * len(iters)
  17.     while True:
  18.         try:
  19.             n = next(iters[i])
  20.         except StopIteration:
  21.             if i == 0:
  22.                 return
  23.             iters[i] = iter(iterables[i])
  24.             i -= 1
  25.         else:
  26.             row[i] = n
  27.             if i == last:
  28.                 yield list(row)
  29.             else:
  30.                 i += 1
Advertisement
Add Comment
Please, Sign In to add comment