Meri Khurshudyan
Meri Khurshudyan

Reputation: 92

Theoretical Probability of Rolling N Dice in Python

I am trying to plot an ideal case situation of rolling N dice in python to compare it to experimental values, I am able to create the number of various combinations that the dice will produce but I can't sum the tuples to figure out how many of the rolls will for example result in the number 7 or 8 to generate a normal distribution (ex when rolling two dice 7 is a more likely outcome than 2)

from itertools import product
t = [list(range(1,7)) for x in range(2)]
r = list(product(*t))
print(r)

this code will print [(1,1),(1,2),(2,1),(2,2).....] what I need is for it to print the sum [2,3,3,4.....]

any ideas?

thanks!

Upvotes: 0

Views: 285

Answers (2)

PaSTE
PaSTE

Reputation: 4548

You can sum them in a list comprehension when defining r rather than simply building a list:

from itertools import product
t = [list(range(1,7)) for x in range(2)]
r = [sum(pair) for pair in product(*t)]
# r = [2, 3, 4, 5, ...]

This gives you an array that is a little out of order from what you requested. The elements of r are [(1+1), (1+2), ..., (1+6), (2+1), ...], but you can sort them as necessary:

r.sort()
# r = [2, 3, 3, 4, ...]

But itertools has some even more useful iterators that can help you here. One that might be worth looking into is permutations, which when coupled with the built-in map function can build the list a little more concisely:

from itertools import permutations
t = permutations(range(1, 7), 2) # iterate through all permutations of 2 elements from the list [1,2,3,4,5,6]
r = list(map(sum, t)) # map the sum function to each permutation

Or, as a one-liner:

r = list(map(sum, permutations(range(1, 7), 2)))

Upvotes: 2

Riptide
Riptide

Reputation: 416

You can try something like this

list1, list2 = [], []

for i in range(1, 7):
    for j in range(1, 7):
        list1.append((i, j))
        list2.append(i + j)

It produces the following output

>>> list1
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)]

>>> list2
[2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 10, 6, 7, 8, 9, 10, 11, 7, 8, 9, 10, 11, 12]

Index i of list2 is the sum of numbers in the tuple at index i of list1

Upvotes: 1

Related Questions