Reputation: 530
What does this part of program do (found on Nubela's guthub)?
def product(*args, **kwds):
"""
for py2.6< support (they lack itertools lib)
- http://docs.python.org/2/library/itertools.html#itertools.permutations
"""
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
And later in program:
list(set((product(*[range(2) for _ in range(length)]))))
Upvotes: 0
Views: 135
Reputation: 101919
It implements itertools.product
for backwards compatibility. See the documentation for product
:
itertools.product(*iterables[, repeat])
Cartesian product of input iterables.
Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).
The nested loops cycle like an odometer with the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, the product tuples are emitted in sorted order.
To compute the product of an iterable with itself, specify the number of repetitions with the optional repeat keyword argument. For example, product(A, repeat=4) means the same as product(A, A, A, A).
This function is equivalent to the following code, except that the actual implementation does not build up intermediate results in memory:
def product(*args, **kwds): # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod)
Note how the code in the documentation matches what you found.
I don't understand why they put in the doc a reference to itertools.permutations
...
the code:
list(set((product(*[range(2) for _ in range(length)]))))
AFAIK it is equivalent to:
list(product(*[range(2) for _ in range(length)]))
Which simply computes the product of length
range(2)
iterables.
Upvotes: 1