Itertool's cartesian product simulates the effect of multiple nested for loops.
import itertools
for x, y, z in itertools.product(range(1,10), range(1,10), range(1,10)):
product = x * y * z
if product == 36:
print "factors : {0},{1},{2}".format(x,y,z)
Result:
factors : 1,4,9
factors : 1,6,6
factors : 1,9,4
(...etc)
If the range is always the same for each of x,y, and z, you can specify it just once:
for x, y, z in itertools.product(range(1,10), repeat=3):
If you're sick of typing a zillion asterisks for the product =
line, you can use reduce
to multiply together an arbitrary number of arguments:
for factors in itertools.product(range(1,3), repeat=10):
product = reduce(lambda x, y: x*y, factors)
Once your format string becomes unwieldy, you can depend on join
to string together factors:
if product == 512:
#use `map` to turn the factors into strings, first
print "factors: " + ",".join(map(str, factors))