The following code computes the probability distribution of outcomes of rolling two dice with a variable number of equal sides:
def compute_probability_distribution(sides):
dist = {x+y: 0 for x in range(1, sides+1) for y in range(1, sides+1)}
for die_1 in range(1, sides+1):
for die_2 in range(1, sides+1):
dist[die_1+die_2] = dist[die_1+die_2] + 1
probs = dist.items()
print "Prob dist: ", probs
E.g., for ordinary 6-sided dice the prob dist is [(2,6),(3,2),(4,3),(5,4),(6,5),(7,6),(8,5),)(9,4),(10,3),(11,2),(12,1)], where the first element of each tuple is the sum of the 2 dice, and the second element is the number of ways it can occur on one roll. Can anyone tell me how to sort the above prob dist list by the second element of each tuple so I can output the top (1 or 3) most likely occurrences? I am thinking of using the built-in list sort with some sort of comparison function.
probs = [(2,6),(3,2),(4,3),(5,4),(6,5),(7,6),(8,5),(9,4),(10,3),(11,2),(12,1)]
>>> sorted(probs, key=lambda x: x[1]) # x[1] is second element of tuple pair.
[(12, 1),
(3, 2),
(11, 2),
(4, 3),
(10, 3),
(5, 4),
(9, 4),
(6, 5),
(8, 5),
(2, 6),
(7, 6)]