Throw a dice
Let's create an infinite generator! Your task is to define the simulate_dice_throws()
generator. It generates the outcomes of a 6-sided dice tosses in the form of a dictionary out
. Each key is a possible outcome (1
, 2
, 3
, 4
, 5
, 6
). Each value is a list: the first value is the amount of realizations of an outcome and the second, the ratio of realizations to the total number of tosses total
. For example (when total = 4
):
{
1: [2, 0.5],
2: [1, 0.25],
3: [1, 0.25],
4: [0, 0.0],
5: [0, 0.0],
6: [0, 0.0]
}
Tip: use the randint()
function from the random
module (already imported). It generates a random integer in the specified interval (e.g. randint(1, 2)
can be 1
or 2
).
Diese Übung ist Teil des Kurses
Practicing Coding Interview Questions in Python
Anleitung zur Übung
- Simulate a single toss to get a new number.
- Update the number and the ratio of realization.
- Yield the updated dictionary.
- Create the generator and simulate 1000 tosses.
Interaktive Übung zum Anfassen
Probieren Sie diese Übung aus, indem Sie diesen Beispielcode ausführen.
def simulate_dice_throws():
total, out = 0, dict([(i, [0, 0]) for i in range(1, 7)])
while True:
# Simulate a single toss to get a new number
num = ____
total += 1
# Update the number and the ratio of realizations
out[num][0] = ____
for j in range(1, 7):
out[j][1] = round(____/____, 2)
# Yield the updated dictionary
____
# Create the generator and simulate 1000 tosses
dice_simulator = ____
for i in range(1, 1001):
print(str(i) + ': ' + str(____(____)))