Exercises for Lesson 16
Exercise 1: 2nd-level design
Consider the following top-level function.
def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB, draws = simNGames(probA, probB, n)
printResults(winsA, winsB, draws)
graphResults(winsA, winsB, draws)
Provide implementations for the following functions:
printIntro
getInputs
printResults
graphResults
Exercise 2: Simulating a single game
We now have an idea of how to simulate n
games. We have defined a function simOneGame
that simulates a single coin-flip game. We also defined last time a function that flips a weighted coin.
def flipCoin(probHeads):
if random.random() < probHeads:
return "heads"
else:
return "tails"
Using this definition, complete the third-level design of simOneGame
:
def simOneGame(probA, probB):
# TODO
return None
Exercise 3: Unit testing flipCoin
Write two more unit tests for the flipCoin
function. The test for heads is given to you.
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"
def testFlipCoinHeads():
numPassed = 0
numTests = 20
for i in range(numTests):
expected = "heads"
actual = flipCoin(1.0) # should always be heads
if expected == actual:
numPassed += 1
print(numPassed, "out of", numTests, "passed")
The first unit test should test the case where it is always tails. The second should provide a given probability and check that over a very large number of calls to flipCoin
, the result is "heads"
with roughly that probability.
def testFlipCoinTails():
pass # TODO
def testFlipCoinRandom():
pass # TODO