I’m trying to learn the Python library itertools and I thought a good test would be the simulation of dice rolls. It’s easy to generate all possible rolls using product and counting the number of possible ways of doing so with the collections library. I’m trying to solve the problem that comes up in games like Monopoly: when doubles are rolled, you roll again and your final total is the sum of the two rolls.
Below is my starting attempt at solving the problem: two Counters, one for doubles and the other for not doubles. I’m not sure if there is a good way to combine them or if the two Counters are even the best way of doing it.
I’m looking for a slick way of solving (by enumeration) the dice roll problem with doubles using itertools and collections.
import numpy as np
from collections import Counter
from itertools import *
die_n = 2
max_num = 6
die = np.arange(1,max_num+1)
C0,C1 = Counter(), Counter()
for roll in product(die,repeat=die_n):
if len(set(roll)) > 1: C0[sum(roll)] += 1
else: C1[sum(roll)] += 1
Leaving out
numpyhere for the sake of simplicity:First, generate all rolls, be it single or double rolls:
Now a few tests:
and the result:
To get the totals use the special
Countercapabilities:Results:
Note: At this point, there is no way of computing the probability for the totals. You have to know if it is a double roll or a total roll to weigh correctly.