Search code examples
pythonpermutationpython-itertoolsdicecartesian-product

Nested computation of Cartesian-product of dice rolls


I'm working on a Python program where I have to come up with all the ways to roll 9 4-sided dice. I've been trying to come up with a more concise way to write this line:

for n in [sum([a, b, c, d, e, f, g, h, i]) for a in range(1, 5) for b in range(1, 5) for c in range(1, 5) for d in range(1, 5) for e in range(1, 5) for f in range(1, 5) for g in range(1, 5) for h in range(1, 5) for i in range(1, 5)]:

I've seen syntax similar to:

for n in [sum([a, b, c, d, e, f, g, h, i]) for a, b, c, d, e, f, g, h, i in range(1, 5)]:

but this gives the error:

TypeError: 'int' object is not iterable

What's going on?


Solution

  • As Calum noted, you should use the built-in itertools for these common loops.

    In your case, you would want:

    import itertools
    results = [sum(x) for x in itertools.product(range(1,5),repeat=9)]
    

    range(1,5) represents the 4 sides of the die

    repeat=9 represents the 9 dice you want to roll

    See itertools.product for doc