Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Only those for which the target is achievable solution in Clear category for Probably Dice by Oleg_Domokeev
def probability(dice_number, sides, target):
# check if the target is possible
if target not in range(dice_number, sides * dice_number + 1):
return 0
# only for convenience - probability for each side for one dice and distribution before throwing the dices:
# the only result zero with 100%
p, prob_table = 1 / sides, {0: 1}
# we throw the dices one by one
for i in range(1, dice_number + 1):
# on every step we don't need determine probabilities for all possible summ of points
# from one hand after i dices the result must be found in range from i to i*sides
# from the other hand it is obligatory to achieve the target with the last dice that
# after the last by one dice the result is in range from target-sides to target-1 and so
# after i dices the range of point that can affect the result is from target - sides * (dice_number - i)
# to target - dice_number + i. So we have two restrictions and can determine the boundes of range of results on each step
left, right = max(target - sides * (dice_number - i), i), min(target - dice_number + i, sides * i)
# for this range of point we determine the probabilities on the base of previous step
prob_table = {n: p * sum(prob for point, prob in prob_table.copy().items()
if n - point in range(1, sides + 1)) for n in range(left, right + 1)}
# on the last throw we have the distribution of the probabilities whis the only element - taget
return round(prob_table[target], 4)
Jan. 24, 2019
Comments: