I'm trying to understand this snippet from itertools library
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)
What this function does is that it takes two arguments: a set of characters and a length of the output, then generates all possible permutations using the given set of characters. for example:
product('ab', repeat=3)
#produces
['a','a','a'],
['a','a','b'],
['a','b','a'],
['a','b','b'],
['b','a','a'],
['b','a','b'],
['b','b','a'],
['b','b','b']
all make sense to me except for this line:
for pool in pools:
result = [x+[y] for x in result for y in pool]
i tried to uncompact it to normal for loops:
for pool in pools:
for x in result:
for y in pool:
result.append(x+[y])
But i ended up with infinite loop!
How does it work?
This part is a list comprehension . You got the translation right. But in
for pool in pools:
result = [x+[y] for x in result for y in pool]
you create a list, using result
and pool
, and then assign it to result
.
In
for pool in pools:
for x in result:
for y in pool:
result.append(x+[y])
you iterate over result ( for x in result
), and add elements to it, so it keeps growing.
If you want to create for loops, you can use a temporary variable to save the previous result
, and build the new one:
for pool in pools:
result2 = result[:]
result = []
for x in result2:
for y in pool:
result.append(x+[y])
Edit: Thanks to @razzak and @GregHewgill for correcting my mistakes
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.