In this part, you'll design a class to represent dice. Your class should behave as follows:
Dice
roll
method, which rolls a random number between 1 and the number of sides (inclusive) and returns that numbergetRolls
method, which returns a dictionary of counts of all the rolls that have been made so fargetSides
method, which returns the number of sides of the diceYou'll need Python's built-in random
package for the random number generator. You can import the package by typing import random
. To generate a random number between a
and b
inclusive, run random.randint(a, b)
. You cannot use any other built-in Python functions.
In [ ]:
In [ ]:
from collections import Counter
d1 = Dice()
i1 = [d1.roll() for i in range(100)]
a1 = Counter(i1)
o1 = d1.getRolls()
for k, v in a1.items():
assert v == o1[k]
d2 = Dice(2)
i2 = [d2.roll() for i in range(100)]
assert 1 in i2 or 2 in i2
assert 3 not in i2 and 0 not in i2
assert 2 == d2.getSides()
Write a function rolls_needed
which determines how many times you need to roll a single dice before a particular number comes up.
For example, if the Dice was only 1-sided and the request was the number 1
, then it would would only require 1 roll to obtain. If the dice was 2-sided and the request was the number 2
, it would take roughly 1.5 rolls to obtain (though you would return the integer count, since you're only doing this once).
If the request number is invalid for any reason, you should throw a ValueError
.
You cannot use any built-in Python functions.
In [ ]:
In [ ]:
d1 = Dice(1)
r1 = 1
assert 1 == rolls_needed(d1, r1)
d2 = Dice()
r2 = 0
try:
rolls_needed(d2, r2)
except ValueError:
assert True
else:
assert False