Reputation: 127
How can I do this, but with a changeable number of dice? Which means that all_dices
can have any length.
for first_dice_number in all_dices[0]:
for second_dice_number in all_dices[1]:
for thrird_dice_number in all_dices[2]:
result = first_dice_number+second_dice_number+thrird_dice_number
results.append(result)
For clarification, all_dices
looks like:
[[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6]]
This most likely is a noob question but I just can't figure it out.
The problem is that I don't want to put a 100 for
loops inside each other.
Upvotes: 2
Views: 63
Reputation: 52008
The itertools
solution is probably the best in Python, but another way to handle dice is to think about enumerating possible rolls of n
dice as counting from 0 to 6^n -1 in base 6 (but using "digits" 1 to 6 rather than 0 to 5):
def decode(dice_code, num_dice):
dice = []
for _ in range(num_dice):
dice_code,r = divmod(dice_code,6)
dice.append(1+r)
return dice
For example, decode(0,5)
is [1,1,1,1,1]
and decode(7775,5)
is [6,6,6,6,6]
. Just loop over range(6**n)
, decoding as needed.
Upvotes: 0
Reputation: 670
Recursion is made for those things, put one loop in a function, and keep calling yourself until you do not have dices
all_dices=[range(1,6),range(1,6),range(1,6),range(1,6)]
def flip(dicenum,totaluntilhere):
if dicenum>len(all_dices)
results.append(totaluntilhere+all_dices[dicenum]
else
for dice in all_dices[dicenum+1]:
flip(dicenum+1,totaluntilhere+dice)
flip(-1,0)
I am not so good in python, but that's the idea
Upvotes: 0
Reputation: 532023
You want a (Cartesian) product of the sets of values.
from itertools import product
results = [sum(numbers) for numbers in product(*all_dices)]
For example:
>>> list(product([1,2,3], [1,2,3,4]))
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4)]
Upvotes: 5