Roll n fair dice with faces 1..sides. Return exact answers as fractions.Fraction:
dice_sum_distribution(n: int, sides: int) -> dict[int, Fraction]: each possible total (only those that can happen) mapped to its probability.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.