1. Learn
  2. /
  3. Courses
  4. /
  5. Practicing Coding Interview Questions in Python

Connected

Exercise

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).

Instructions

100 XP
  • 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.