|
| 1 | +import random |
| 2 | +from typing import List |
| 3 | + |
| 4 | +class Dice: |
| 5 | + NUM_SIDES = 6 |
| 6 | + |
| 7 | + def __init__(self): |
| 8 | + """ Initialize a six sided dice """ |
| 9 | + self.sides = list(range(1, Dice.NUM_SIDES + 1)) |
| 10 | + |
| 11 | + def roll(self): |
| 12 | + return random.choice(self.sides) |
| 13 | + |
| 14 | + def _str_(self): |
| 15 | + return "Fair Dice" |
| 16 | + |
| 17 | + |
| 18 | +def throw_dice(num_throws: int, num_dice: int=2) -> List[float]: |
| 19 | + """ |
| 20 | + Return probability list of all possible sums when throwing dice. |
| 21 | +
|
| 22 | + >>> random.seed(0) |
| 23 | + >>> throw_dice(10, 1) |
| 24 | + [10.0, 0.0, 30.0, 50.0, 10.0, 0.0] |
| 25 | + >>> throw_dice(100, 1) |
| 26 | + [19.0, 17.0, 17.0, 11.0, 23.0, 13.0] |
| 27 | + >>> throw_dice(1000, 1) |
| 28 | + [18.8, 15.5, 16.3, 17.6, 14.2, 17.6] |
| 29 | + >>> throw_dice(10000, 1) |
| 30 | + [16.35, 16.89, 16.93, 16.6, 16.52, 16.71] |
| 31 | + >>> throw_dice(10000, 2) |
| 32 | + [2.74, 5.6, 7.99, 11.26, 13.92, 16.7, 14.44, 10.63, 8.05, 5.92, 2.75] |
| 33 | + """ |
| 34 | + dices = [Dice() for i in range(num_dice)] |
| 35 | + count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1) |
| 36 | + for i in range(num_throws): |
| 37 | + count_of_sum[sum([dice.roll() for dice in dices])] += 1 |
| 38 | + probability = [round((count * 100) / num_throws, 2) for count in count_of_sum] |
| 39 | + return probability[num_dice:] # remove probability of sums that never appear |
| 40 | + |
| 41 | + |
| 42 | +if __name__ == "__main__": |
| 43 | + import doctest |
| 44 | + |
| 45 | + doctest.testmod() |
0 commit comments