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:
printIntrogetInputsprintResultsgraphResults
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 NoneExercise 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"Exercise 3: Unit testing flipCoin
Given the flipCoin function, write two more unit tests.
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"The first unit test should test the case where it is always heads. 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