Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Probably Dice by derrickding95
def probability(dice_number, sides, target):
templist = []
for i in range(1,sides+1):
templist.append(1)
result=[templist]
for i in range(1,dice_number):
x = (sides-1)*(i+1)+1
result.append([0 for j in range(x)])
for j in range(x):
if j < sides:
result[i][j] = (sum(result[i-1][0:j+1]))
elif j >= sides and j <= (i+1)*(sides-1)-sides:
result[i][j] = (sum(result[i-1][j-sides+1:j+1]))
else:
result[i][j] = (sum(result[i-1][j-sides+1:(i+1)*(sides-1)+1]))
res = result[-1]
all = float(sum(res))
if dice_number <= target <= dice_number*sides:
return res[target-dice_number]/all
else:
return 0
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 30, 2018
Comments: