150 CHAPTER9. SIMULATIONANDDESIGN
has the first serve.
What is the prob. playerA wins a serve? .65
What is the prob. playerB wins a serve? .6
How many games to simulate? 5000
Games simulated: 5000
Wins for A: 3360 (67.2%)
Wins for B: 1640 (32.8%)
Eventhoughthereis onlya smalldifferenceinability, Denny shouldwinonlyaboutoneinthreegames.His
chancesofwinninga three-orfive-gamematchareprettyslim.ApparentlyDenny is winninghisshare.He
shouldskiptheshrinkandworkharderonhisgame.
Speakingofmatches,expandingthisprogramtocomputetheprobabilityofwinningmulti-gamematches
wouldbea greatexercise.Whydon’t yougive it a try?
9.5 OtherDesignTechniques.
Top-downdesignis a verypowerfultechniqueforprogramdesign,butit isnottheonlywaytogoabout
creatinga program.Sometimesyoumaygetstuckat a stepandnotknow how togoaboutrefiningit.Orthe
originalspecificationmightbesocomplicatedthatrefiningit level-by-level is justtoodaunting.
9.5.1 PrototypingandSpiralDevelopment.
Anotherapproachtodesignis tostartwitha simpleversionofa programorprogramcomponentandthen
trytograduallyaddfeaturesuntilit meetsthefullspecification.Theinitialstripped-downversionis called
aprototype. Prototypingoftenleadstoa sortofspiraldevelopmentprocess. Ratherthantakingtheentire
problemandproceedingthroughspecification,design,implementationandtesting,wefirstdesign,implement
andtesta prototype.Thennew featuresaredesigned,implementedandtested.We make many mini-cycles
throughthedevelopmentprocessastheprototypeis incrementallyexpandedintothefinalprogram.
Asanexample,considerhow wemighthave approachedtheracquetballsimulation.Theveryessenceof
theproblemis simulatinga gameofracquetball.We mighthave startedwithjustthesimOneGamefunction.
Simplifyingevenfurther, ourprototypecouldassumethateachplayerhasa 50-50chanceofwinningany
givenpointandjustplaya seriesof 30 rallies.Thatleavesthecruxoftheproblem,whichis handlingthe
awardingofpointsandchangeofservice.Hereis anexampleprototype:
from random importrandom
def simOneGame():
scoreA = 0
scoreB = 0
serving = "A"
for i in range(30):
if serving== "A":
if random()< .5:
scoreA = scoreA+ 1
else:
serving= "B"
else:
if random()< .5:
scoreB = scoreB+ 1
else:
serving= "A"
print scoreA,scoreB