I don't think I would use a class here. you just generate the dice roll and then check to see if the dice roll should be counted or not. In this case, I'd use a Counter
to do the counting just to make the code a little more clean:
from collections import Counter
from random import randint
def roll(ndice,nsides=9):
return [randint(1,nsides) for _ in range(ndice)]
def count_it():
c = Counter(roll(5))
return c.most_common(1)[0][1] >= 3
ntries = 100000
print (sum(1 for _ in range(ntries) if count_it())/ntries)
It looks to me like you have about a 10% chance. The trick with Monte-Carlo is determining whether you've converged or not. You can do this a few times with different numbers of ntries
. The bigger your make ntries
, the smaller the spread will be in your output. Eventually, when the spread is small enough, you say you've converged on the solution with some certainty.