Variable Number Of Nested For Loops With Fixed Range
Solution 1:
It's important for one to develop the skills to reason about these problems. In this case, Python includes itertools.product but what happens the next time you need to write a behaviour specific to your program? Will there be another magical built-in function? Maybe someone else will have published a 3rd party library to solve your problem?
Below, we design product as a simple recursive function that accepts 1 or more lists.
defproduct (first, *rest):
ifnot rest:
for x in first:
yield (x,)
else:
for p in product (*rest):
for x in first:
yield (x, *p)
for p in product (range(2), range(2), range(2)):
print ('x: %d, y: %d z: %d' % p)
# x: 0, y: 0 z: 0# x: 1, y: 0 z: 0# x: 0, y: 1 z: 0# x: 1, y: 1 z: 0# x: 0, y: 0 z: 1# x: 1, y: 0 z: 1# x: 0, y: 1 z: 1# x: 1, y: 1 z: 1Assuming you want a more conventional iteration ordering, you can accomplish do so by using an auxiliary loop helper
defproduct (first, *rest):
defloop (acc, first, *rest):
ifnot rest:
for x in first:
yield (*acc, x)
else:
for x in first:
yieldfrom loop ((*acc, x), *rest)
return loop ((), first, *rest)
for p in product (range(2), range(2), range(2)):
print ('x: %d, y: %d z: %d' % p)
# x: 0, y: 0 z: 0# x: 0, y: 0 z: 1# x: 0, y: 1 z: 0# x: 0, y: 1 z: 1# x: 1, y: 0 z: 0# x: 1, y: 0 z: 1# x: 1, y: 1 z: 0# x: 1, y: 1 z: 1Solution 2:
Something like this should work:
import itertools
n=3
fixed=26
p = list(itertools.product(range(fixed), repeat=n))
This solution uses the optimized functions of itertools, so it should be quite fast.
Mind that itertools.product returns an iterator, so one needs to transform it to get an array.
Post a Comment for "Variable Number Of Nested For Loops With Fixed Range"