Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Room to Improve solution in Clear category for Probably Dice by zero_loss
from itertools import combinations_with_replacement
from math import factorial
from collections import Counter
def probability(dice, sides, target):
gen_die = combinations_with_replacement(range(1,sides+1), dice)
total = 0
for die in gen_die:
if sum(die) == target:
permutations = factorial(dice)
counts = Counter(die)
for item in counts:
permutations = permutations/factorial(counts[item])
total += permutations
return round(total/sides**dice, 4)
if __name__ == '__main__':
assert probability(2, 6, 3) == 0.0556 # 2 six-sided dice have a 5.56% chance of totalling 3
assert probability(2, 6, 4) == 0.0833
assert probability(2, 6, 7) == 0.1667
assert probability(2, 3, 5) == 0.2222 # 2 three-sided dice have a 22.22% chance of totalling 5
assert probability(2, 3, 7) == 0 # The maximum you can roll on 2 three-sided dice is 6
assert probability(3, 6, 7) == 0.0694
assert probability(10, 10, 50) == 0.0375
July 21, 2015
Comments: