Python Programming: An Introduction to Computer Science

(Nora) #1
9.3.TOP-DOWNDESIGN 143

9.3.4 DesigningsimNGames.


Now thatwearegettingsomeexperiencewiththetop-downdesigntechnique,wearereadyto tryourhandat
therealproblem,simNGames. Thisonerequiresa bitmorethought.Thebasicideais tosimulatengames
andkeeptrackofhow many winsthereareforeachplayer. Well,“simulatengames”soundslike a counted
loop,andtrackingwinssoundslike thejobfora coupleofaccumulators.Usingourfamiliarpatterns,wecan
piecetogetheranalgorithm.


Initialize winsA and winsBto 0
loop n times
simulate a game
if playerA wins
Add one to winsA
else
Add one to winsB


It’s a prettyroughdesign,butthensowasourtop-level algorithm.We’ll fillinthedetailsbyturningit into
Pythoncode.
Remember, wealreadyhave thesignatureforourfunction.


def simNGames(n, probA,probB):


Simulates n gamesand returns winsA and winsB


We’ll addtothisbyinitializingthetwo accumulatorvariablesandaddingthecountedloopheading.


def simNGames(n, probA,probB):


Simulates n gamesand returns winsA and winsB


winsA = 0
winsB = 0
for i in range(n):


Thenextstepinthealgorithmcallsforsimulatinga gameofracquetball.I’mnotquitesurehowtodo
that,soasusual,I’ll putoff thedetails.Let’s justassumethere’s a functioncalledsimOneGametotake care
ofthis.
We needtofigureoutwhattheinterfaceforthisfunctionwillbe. Theinputsforthefunctionseem
straightforward.Inordertoaccuratelysimulatea game,weneedtoknow whattheprobabilitiesareforeach
player. Butwhatshouldtheoutputbe?Inthenext stepofthealgorithm,weneedto know whowonthegame.
How doyouknow whowon?Generally, youlookat thefinalscore.
Let’s havesimOneGamereturnthefinalscoresforthetwo players.We canupdateourstructurechart
toreflectthesedecisions.Theresultis showninFigure9.2.Translatingthisstructureintocodeyieldsthis
nearlycompletedfunction:


def simNGames(n, probA,probB):


Simulates n gamesand returns winsA and winsB


winsA = 0
winsB = 0
for i in range(n):
scoreA, scoreB= simOneGame(probA, probB)


Finally, weneedtocheckthescorestoseewhowonandupdatetheappropriateaccumulator. Hereis the
result.


def simNGames(n, probA,probB):
winsA = winsB = 0
for i in range(n):
scoreA, scoreB= simOneGame(probA, probB)
if scoreA > scoreB:
winsA = winsA+ 1

Free download pdf