Search code examples
pythonpython-3.xpython-itertoolsrandom-seed

Using itertools.product with seed value in Python3


I am in almost the exact same situation as the OP of this question: Using itertools.product and want to seed a value and I am trying to use the code given in this answer about using seed values with itertools.product. This is the original code:

from itertools import count, imap

def make_product(*values):
    def fold((n, l), v):
        (n, m) = divmod(n, len(v))
        return (n, l + [v[m]])
    def product(n):
        (n, l) = reduce(fold, values, (n, []))
        if n > 0: raise StopIteration
        return tuple(l)
    return product

def product_from(n, *values):
    return imap(make_product(*values), count(n))

print list(product_from(4, ['a','b','c'], [1,2,3]))

I removed imap from importing since this is removed in Python 3 and replaced all instances of imap with map. But I receive a syntax error with the double parenthesis

def make_product(*values):
    def fold((n, l), v):
             ^
SyntaxError: invalid syntax

How can I make this code work in Python 3 or is there a more efficient method of getting seed values from using itertools.product?


Solution

  • You can replace it with a single argument and then use tuple unpacking to create n and l:

    def fold(n_l, v):
        (n, l) = n_l
        (n, m) = divmod(n, len(v))
        return (n, l + [v[m]])