1

I can iterate through all combinations of 1, 2, or 3 6-sided dice with loops like these:

for a in range(1, 7):  # one die
  sum = a
  dosomething(sum)

for a in range(1, 7):  # two dice
  for b in range(1, 7):
    sum = a + b
    dosomething(sum)

for a in range(1, 7):    # three dice
  for b in range(1, 7):
    for c in range(1, 7):
      sum = a + b + c
      dosomething(sum)

How can I do this for N dice using itertools?

Mark Harrison
  • 297,451
  • 125
  • 333
  • 465

1 Answers1

5

This is what itertools.product is for.

for dice in itertools.product(range(1, 7), repeat=N):
    dosomething(sum(dice))
user2357112
  • 260,549
  • 28
  • 431
  • 505