1

I'm writing a program that looks at every possible sum of a dice roll given X die with X sides. For example, with 2 dice with 6 sides, I need a list of elements giving all possible unique sums achievable with these dice (something like 2,3,3,4,4,4,4 etc..). I can do this for smaller sets (2 dice 6 sides is fine), but larger sets like 10 dice and 10 sides I run into mem issues. I think I've found the solution, but am having issues with implementation.

I have a list of lists containing all rolls of each individual dice. For this example, we have 3 dice that can roll a 1, 2, or 3.

dice = [[1,2,3], [1,2,3], [1,2,3]]

outcomes = list(map(sum, zip(itertools.product(*dice))))

I think the pieces are there, but I keep getting TypeError: unsupported operand type(s) for +: 'int' and 'tuple'. I've tried moving the pieces around in numerous ways but nothing has clicked. What am I doing wrong? Ultimately I'm given a number, say 6, that I have to find out what the odds are I'll roll that number. So my goal with the above code is to get a generator that I get the total times X number appeared and figure out the probability of rolling X number. I've gotten a list for smaller inputs, but like I said, once I get larger inputs the list gets too big

mtmn12
  • 23
  • 1
  • 5

2 Answers2

1

You don't need zip here. Map the sequence of tuples generated by itertools.product to sum directly and it will be the sequence of sums you're looking for:

outcomes = list(map(sum, itertools.product(*dice)))
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • That ultimately solves the problem. Now I have to figure out what to do with the generator - didn't realize that it would function much differently than a list. Thanks! – mtmn12 Apr 16 '19 at 01:26
1

For any given set of dice, you know that the minimum possible sum of the dice roll will be the min_value * num_dice. For example, if you have 2 dice with 6 sides, the minimum dice sum value will be 1 * 2 = 2. Similarly, you know that the maximum value will be max_value * num_dice. For example, if you have 2 dice with 6 sides, the max dice sum value will be 6 * 2 = 12.

Furthermore, if we can assume that the dice all have the same values and all each side has a unique number and the numbers are in the range [1, number_of_sides], then every whole number value between min_value and max_value will be accounted for.

Hence, in python, you can simply list all the unique sums of n dice with x sides as follows:

def all_possible_sums(number_of_dice: int, number_of_sides: int) -> List[int]:
    return list(range(number_of_dice, number_of_sides * number_of_dice + 1))
Mike Lane
  • 1,134
  • 7
  • 19