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):
"""
Flips an unfair coin.
Inputs:
* probHeads: the fraction of the time the coin should say heads;
a float in the range [0,1)
Returns: "heads" or "tails" (strings)
"""
val = random.random()
if val < probHeads: # exactly probHeads% of the range [0,1)
return "heads"
else:
return "tails"
Using this definition, complete the third-level design of simOneGame:
def simOneGame(probA, probB):
"""
Simulates a single coin-tossing game using unfair coins.
Inputs:
* probA: likelihood of getting "heads" for player A (float)
* probB: likelihood of getting "heads" for player B (float)
Returns: "A" or "B" or "draw" (strings); who won the game
"""
# TODO
return None