Python Programming: An Introduction to Computer Science

(Nora) #1
140 CHAPTER9. SIMULATIONANDDESIGN

Thenameofthemodule(random) is thesameasthenameofthefunction,whichgivesrisetothefunny-
lookingimportline.
Ourracquetballsimulationcanmake useoftherandomfunctiontodeterminewhetherornota player
winsa serve. Let’s lookat a specificexample.Supposea player’s serviceprobabilityis 0.70.Thismeansthat
they shouldwin70%oftheirserves.Youcanimaginea decisionintheprogramsomethinglike this:


if :
score = score + 1


We needtoinserta probabilisticconditionthatwillsucceed70%ofthetime.
Supposewegeneratea randomvaluebetween0 and1.Exactly70%oftheinterval 01 is totheleftof
0.7.So70%ofthetimetherandomnumberwillbe 0.7,andit willbe 0.7theother30%ofthetime.(The
goesontheupperend,becausetherandomgeneratorcanproducea 0,butnevera 1.)Ingeneral,ifprob
representstheprobabilitythattheplayerwinsa serve, theconditionrandom() < probwillsucceedwith
justtherightprobability. Hereis how thedecisionwilllook:


if random() < prob:
score = score + 1


9.3 Top-DownDesign.


Now youhave thecompletespecificationforoursimulationandthenecessaryknowledgeofrandomnumbers
togetthejobdone.Goaheadandtake a few minutestowriteuptheprogram;I’ll wait.
OK,seriously, thisisa morecomplicatedprogramthanyou’ve probablyattemptedsofar. Youmay
notevenknowwheretobegin.If you’regoingtomake it throughwithminimalfrustration,you’ll needa
systematicapproach.
Oneproventechniquefortacklingcomplex problemsis calledtop-downdesign. Thebasicideais tostart
withthegeneralproblemandtrytoexpressa solutionintermsofsmallerproblems.Theneachofthesmaller
problemsis attackedinturnusingthesametechnique.Eventuallytheproblemsgetsosmallthatthey are
trivialtosolve. Thenyoujustputallthepiecesbacktogetherand,voil`a, you’ve gota program.


9.3.1 Top-Level Design.


Top-downdesignis easiertoillustratethanit is todefine.Let’s give it a tryonourracquetballsimulation
andseewhereit takesus.Asalways,a goodstartis tostudytheprogramspecification.Inverybroadbrush
strokes,thisprogramfollowsthebasicInput-Process-Outputpattern.We needtogetthesimulationinputs
fromtheuser, simulatea bunchofgames,andprintouta report.Hereis a basicalgorithm.


Print an Introduction
Get the inputs: probA,probB, n
Simulate n games of racquetballusing probA and probB
Print a report on the winsfor playerA and playerB


Nowthatwe’ve gotanalgorithm,we’rereadytowritea program. I knowwhatyou’rethinking:this
designis toohigh-level;youdon’t have any ideayethowit’s allgoingtowork.That’s OK.Whateverwe
don’t know how todo,we’ll justignorefornow. Imaginethatallofthecomponentsyouneedtoimplement
thealgorithmhave alreadybeenwrittenforyou. Yourjobis tofinishthistop-levelalgorithmusingthose
components.
Firstwehave to printanintroduction.I thinkI know how to dothis.It justrequiresa few printstatements,
butI don’t reallywanttobotherwithit rightnow. It seemsanunimportantpartofthealgorithm. I’ll
procrastinateandpretendthatsomeoneelsewilldoit forme.Here’s thebeginningoftheprogram.


def main():
printInstructions()

Free download pdf