Exercises for 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)
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):
vals = [0]*4
for i in range(n):
val = random.randint(1,4)
vals[val-1] += 1
return vals
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. 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):
vals = [0]*4
for i in range(n):
val = random.randint(1,4)
vals[val-1] += 1
return vals
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 documentation to find out how to customize the plot with a title, legend, etc.
Here is an example pie chart:
Part c: A different die
How would you change the code to support a six-sided die? What about a twenty-sided die?
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):
if random.random() < 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-roling 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 fair four-sided die.
"""
return random.randint(1,4)
def rollDice(n):
vals = [0]*4
for i in range(n):
val = rollDie() # top-down design: design the inputs/outputs, but write it later
vals[val-1] += 1
return vals
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()