Exercises for Lesson 15

Back to Lesson 15

Exercise 0: break versus continue

What values are printed in each of the following loops?

for i in range(10):
    if i == 3:
        break
    print(i)

for i in range(10):
    if i == 3:
        continue
    print(i)

Back to Lesson 15

Exercise 1: Rolling random dice

Part a: Printing results

Try out the following code. As you increase n, the results should get ever closer to an even 25% split.

import random

def rollDice(n):
    counts = [0]*4
    for i in range(n):
        val = random.randint(1,4)
        counts[val-1] += 1
    return counts

def main():
    n = 10
    diceRolls = rollDice(n)

    for i in range(len(diceRolls)):
        rollCount = diceRolls[i]
        print(i+1, rollCount, rollCount / n)

if __name__ == "__main__":
    main()

Part b: Graphing results

The library Matplotlib makes it incredibly easy to visualize data. If you don’t have it already, you can get it from the command prompt (search “cmd” in Windows or “Terminal” on a Mac), with the following command:

pip3 install matplotlib

Then, try to run this modified dice-rolling program:

import random
from matplotlib import pyplot as plt

def rollDice(n):
    counts = [0]*4
    for i in range(n):
        val = random.randint(1,4)
        counts[val-1] += 1
    return counts

def main():
    n = 10
    diceRolls = rollDice(n)

    for i in range(len(diceRolls)):
        rollCount = diceRolls[i]
        print(i+1, rollCount, rollCount / n)

    plt.figure()
    plt.pie(diceRolls, labels=[1,2,3,4], autopct="%1.2f%%")
    plt.show()

if __name__ == "__main__":
    main()

This should both print the results and display a pie chart. You can play around with the labels or the value of n to see how the pie chart changes. You can also look at Matplotlib tutorials to find out how to customize the plot with a title, legend, etc.

Here is an example pie chart:

<image: pie chart of die rolls>

Part c: A different die

How would you change the code to support a six-sided die? What about a twenty-sided die? What about drawing different subplots for different values of n?

Back to Lesson 15

Exercise 2: Weighted dice

We talked about the following function, which effectively flips an unfair coin, one that comes up heads with probability prob. Here is that flipCoin function:

def flipCoin(prob):
    val = random.random()
    if val < prob: # less than so that it is exactly prob% of the range [0,1)
        return "heads"
    else:
        return "tails"

How can you change the four-sided-dice-rolling program to allow for weighted dice? Think about it in top-down design. First, choose what you would need to provide to a function to roll a single die. Then, write that function. The dice-rolling program has been rewritten to match our top-down design paradigm, assuming a fair die.

import random
from matplotlib import pyplot as plt

def rollDie():
    """
    Rolls a single four-sided die.
    """
    return random.randint(1,4) # change to make it unfair

def rollDice(n):
    counts = [0]*4
    for i in range(n):
        val = rollDie() # top-down design: design the inputs/outputs, but write it later
        counts[val-1] += 1
    return counts

def main():
    n = 10
    diceRolls = rollDice(n)

    for i in range(len(diceRolls)):
        rollCount = diceRolls[i]
        print(i+1, rollCount, rollCount / n)

    plt.figure()
    plt.pie(diceRolls, labels=[1,2,3,4], autopct="%1.2f%%")
    plt.show()

if __name__ == "__main__":
    main()

Back to Lesson 15