Exercises for Lesson 13

Back to Lesson 13

Exercise 1: Rolling random dice

Part a: Reading a program

Read through the following program, trying to understand what it’s doing. (After class, type it up and run it – as you increase n, the results should get ever closer to an even 25% split.)

import random

def getInputs():
    return int(input("How many dice? "))

def rollD4():
    return random.randint(1,4)

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

def printResults(rolls):
    for i in range(len(rolls)):
        rollCount = rolls[i]
        print(i+1, rollCount, rollCount / sum(rolls))

def main():
    n = getInputs()
    diceRolls = rollDice(n)
    printResults(diceRolls)

if __name__ == "__main__":
    main()

Part b: Diagramming a program

Make a diagram showing how this program adheres to top-down design. For each function, be sure to note the types of inputs and outputs, if any.

Part c: Documenting a program

Write a docstring for one of the functions (except main) in this program.

Back to Lesson 13

Exercise 2: Rolling random dice, revisited

Part a: Updating your diagram

The following program is a modification to the program from the previous exercise. How does the diagram we drew need to change based on the changes? (Hint: Look for # new!.)

import random
from matplotlib import pyplot as plt # new!

def getInputs():
    return int(input("How many dice? "))

def rollD4():
    return random.randint(1,4)

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

def printResults(rolls):
    for i in range(len(rolls)):
        rollCount = rolls[i]
        print(i+1, rollCount, rollCount / sum(rolls))

def graphResults(rolls): # new!
    plt.figure()
    plt.pie(rolls, labels=[1,2,3,4], autopct="%1.2f%%")
    plt.show()

def main():
    n = getInputs()
    diceRolls = rollDice(n)
    printResults(diceRolls)
    graphResults(diceRolls) # new!

if __name__ == "__main__":
    main()

Part b: Graphing results

Let’s dive into these changes a bit. If you haven’t already installed Matplotlib, here is the command to type into the Terminal:

pip3 install matplotlib

Now, try to run this modified dice-rolling program. It 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 graph

How would you draw a bar graph instead of the pie chart? Explore the Matplotlib examples to find a relevant code sample.

Part d: 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 13

Exercise 3: Rolling unfair 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? Before writing any code, think carefully about which functions would need to change to support, for example, a die that comes up 4 approximately 40% of the time, and each of 1, 2, or 3 approximately 20% of the time.

Back to Lesson 13

Exercise 4: Dice games

In the game of Yahtzee, each player rolls five dice (with some re-rolls), and scores dice based on the poker-like “hand” they get. One such result is “four of a kind”, which is satisfied when at least four of the five dice have the same value. In this exercise, you’ll work your way backward relative to the previous exercise, building up such a program.

The goal of the program is to roll random hands of five six-sided dice, counting how many such hands (out of, say 1000), satisfy the “four of a kind” requirement.

Part a: Diagramming a program

Make a diagram to describe this program using top-down design.

Part b: Documenting a program

Write skeleton functions (e.g., either pass or return None or something similar) to fill in main. Write the docstring for each function you’ll need.

Part c: Write test cases

Before actually writing code, try to write down some test cases for determining whether something satisfies the “four of a kind” requirement.

Part d: Write your program

Finally, fill in each function, testing as you go!

Back to Lesson 13

Exercise 5: More dice games

Work through the same exercise from before, but for different types of hands. What do you have to change in your designs?

Part a: Yahtzee!

Modify your design and program to check for a Yahtzee, which is when all five dice are equal.

Part b: Another hand type

Modify your design and program to check for a “full house”, which is when three dice have one value, and the other two have another. For example, dice values 3,3,3,4,4 would be a full house.

Part c: More dice

Modify your design and program to change the rules of the game and have a different number of dice, for example 4 or 6. How would your code from Part (a) need to change to handle a different number of dice?

Back to Lesson 13