progress

~/problems / Randomness / Probability and expected value

Distribution of a dice sum

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Roll n fair dice with faces 1..sides. Return exact answers as fractions.Fraction:

  1. dice_sum_distribution(n: int, sides: int) -> dict[int, Fraction]: each possible total (only those that can happen) mapped to its probability.
  2. expected_value(dist: dict[int, Fraction]) -> Fraction: Σ value · P(value) for any such distribution.
dice_sum_distribution(1, 4)   # {1: 1/4, 2: 1/4, 3: 1/4, 4: 1/4}
dice_sum_distribution(2, 3)   # {2: 1/9, 3: 2/9, 4: 3/9, 5: 2/9, 6: 1/9}
dice_sum_distribution(0, 6)   # {0: 1}   (no dice: the total is always 0)
expected_value(dice_sum_distribution(2, 6))   # Fraction(7, 1)

0 <= n <= 30, 1 <= sides <= 20.

⭐ Bonus: listing all sides ** n outcomes passes for small n; a speed test with up to 30 dice earns a star if you add one die at a time instead.

Show hint

start from {0: 1}; adding a die is a convolution: new[t + f] += old[t] * Fraction(1, sides) for every face f.

Topic: Probability and expected value. Linearity of expectation, conditioning, Markov-chain equations; answers as fractions.

0:00
Ctrl ' run · Ctrl ↵ submit
esc