Python Programming: An Introduction to Computer Science

(Nora) #1
148 CHAPTER9. SIMULATIONANDDESIGN

n = winsA + winsB
print "\nGamessimulated:", n
print "Wins for A: %d (%0.1f%%)"% (winsA, float(winsA)/n*100)
print "Wins for B: %d (%0.1f%%)"% (winsB, float(winsB)/n*100)

if name == ’main’:main()


Youmighttake noticeofthestringformattinginprintSummary. Sincea percentsignnormallymarksthe
beginningofa slotspecifier, togeta normalpercentsignat theend,I hadtousea doublepercent%%.


9.3.7 SummaryoftheDesignProcess


Youhave justseenanexampleoftop-downdesignin action.Now youcanreallyseewhyit’s calledtop-down
design.We startedatthehighestlevelofourstructurechartandworkedourwaydown.Ateachlevel,we
beganwitha generalalgorithmandthengraduallyrefinedit intoprecisecode.Thisapproachis sometimes
calledstep-wiserefinement. Thewholeprocesscanbesummarizedinfoursteps:



  1. Expressthealgorithmasa seriesofsmallerproblems.

  2. Developaninterfaceforeachofthesmallproblems.

  3. Detailthealgorithmbyexpressingit intermsofitsinterfaceswiththesmallerproblems.

  4. Repeattheprocessforeachsmallerproblem.


Top-downdesignis aninvaluabletoolfordevelopingcomplex algorithms.Theprocessmayseemeasy,
sinceI’ve walkedyouthroughit step-by-step.Whenyoufirsttryit outforyourself,though,thingsprobably
won’t goquitesosmoothly. Staywithit—themoreyoudoit,theeasierit willget.Initially, youmaythink
writingallofthosefunctionsis a lotoftrouble.Thetruthis,developingany sophisticatedsystemis virtually
impossiblewithouta modularapproach. Keepatit,andsoonexpressingyourownprogramsintermsof
cooperatingfunctionswillbecomesecondnature.


9.4 Bottom-UpImplementation.


Now thatwe’ve gota programinhand,yourinclinationmightbetorunoff, typethewholethingin,andgive
it a try. If youdothat,theresultwillprobablybedisappointmentandfrustration.Eventhoughwehave been
verycarefulin ourdesign,thereis noguaranteethatwehaven’t introducedsomesillyerrors.Evenif thecode
is flawless,you’ll probablymake somemistakeswhenyouenterit.Justasdesigninga programonepieceat
a timeis easierthantryingtotacklethewholeproblemat once,implementationis bestapproachedinsmall
doses.


9.4.1 UnitTesting.


Agoodwaytoapproachtheimplementationofa modestsizeprogramis tostartatthelowerlevelsofthe
structurechartandworkyourwayup,testingeachcomponentasyoucompleteit. Lookingbackatthe
structurechartforoursimulation,wecouldstartwiththegameOverfunction.Oncethisfunctionis typed
intoa modulefile,wecanimmediatelyimportthefileandtestit.Hereis a samplesessiontestingoutjustthis
function.





import rball
rball1.gameOver(0,0)
0
rball1.gameOver(5,10)
0
rball1.gameOver(15,3)
1




Free download pdf