142 CHAPTER9. SIMULATIONANDDESIGN
probabilities,it musthandbackthecorrectnumberofwinsforeachplayer. Themainfunctiononlycares
whateach(sub-)functiondoes.
Ourworksofar canberepresentedasastructure chart(alsocalledamodulehierarchychart). Figure9.1
illustrates.Eachcomponentinthedesignis a rectangle.A lineconnectingtwo rectanglesindicatesthatthe
oneabove usestheonebelow. Thearrowsandannotationsshowtheinterfacesbetweenthecomponentsin
termsofinformationflow.
probA
probB
n
probA
probB
n winsAwinsB
winsA
winsB
main
printIntro getInputs simNGames printSummary
Figure9.1:First-level structurechartforracquetballsimulation.
Ateachlevel ofa design,theinterfacetellsuswhichdetailsofthelowerlevel areimportant.Anything
elsecanbeignored(forthemoment). Thegeneralprocessofdeterminingtheimportantcharacteristicsof
somethingandignoringotherdetailsis calledabstraction. Abstractionisthefundamentaltoolofdesign.You
mightview theentireprocessoftop-downdesignasa systematicmethodfordiscoveringusefulabstractions.
9.3.3 Second-Level Design.
Nowallweneedtodois repeatthedesignprocessforeachoftheremainingcomponents.Let’s take them
inorder. TheprintIntrofunctionshouldprintanintroductiontotheprogram.Let’s composea suitable
sequenceofprintstatements.
def printIntro():
print "This programsimulates a game of racquetball betweentwo"
print ’playerscalled "A" and "B". The abilities of eachplayer is’
print "indicatedby a probability (a number between 0 and 1) that"
print "the playerwins the point when serving. Player A always"
print "has the firstserve."
Noticethesecondline.I wantedtoputdoublequotesaround“A” and“B,” sotheentirestringis enclosedin
apostrophes.Thisfunctioncomprisesonlyprimitive Pythoninstructions.Sincewedidn’t introduceany new
functions,thereis nochangetoourstructurechart.
Nowlet’s tacklegetInputs. We needtopromptforandgetthreevalues,whicharereturnedtothe
mainprogram.Again,thisis simpletocode.
def getInputs():
RETURNS the threesimulation parameters probA, probB and n
a = input("Whatis the prob. player A wins a serve? ")
b = input("Whatis the prob. player B wins a serve? ")
n = input("Howmany games to simulate? ")
return a, b, n
NoticethatI have takensomeshortcutswiththevariablenames.Remember, variablesinsideofa function
arelocaltothatfunction.Thisfunctionis soshort,it’s veryeasytoseewhatthethreevaluesrepresent.The
mainconcernhereis tomake surethevaluesarereturnedinthecorrectordertomatchwiththeinterfacewe
establishedbetweengetInputsandmain.