Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Probably Dice by jcg
import functools
@functools.lru_cache(maxsize=1000) # memorize the 1000 last calls
def count(dice_number, sides, target) :
# counting the number of throw who hit target
# partition :
# the first dice can show d0 from 1 to sides
# the we have to count the number of throws whith (dice_number-1) dices,
# which hit target - d0
if dice_number==0 :
return 1 if target == 0 else 0
else :
if not (dice_number<=target<=dice_number*sides) :
return 0
return sum(count(dice_number-1,sides, target - d0)for d0 in range(1,sides+1))
def probability(dice_number, sides, target):
return round(count(dice_number, sides, target)/sides**dice_number,4)
if __name__ == '__main__':
#These are only used for self-checking and are not necessary for auto-testing
def almost_equal(checked, correct, significant_digits=4):
precision = 0.1 ** significant_digits
return correct - precision < checked < correct + precision
assert(almost_equal(probability(2, 6, 3), 0.0556)), "Basic example"
assert(almost_equal(probability(2, 6, 4), 0.0833)), "More points"
assert(almost_equal(probability(2, 6, 7), 0.1667)), "Maximum for two 6-sided dice"
assert(almost_equal(probability(2, 3, 5), 0.2222)), "Small dice"
assert(almost_equal(probability(2, 3, 7), 0.0000)), "Never!"
assert(almost_equal(probability(3, 6, 7), 0.0694)), "Three dice"
assert(almost_equal(probability(10, 10, 50), 0.0375)), "Many dice, many sides"
June 15, 2014
Comments: