Python Programming: An Introduction to Computer Science

(Nora) #1
116 CHAPTER7. CONTROLSTRUCTURES,PART 1

7.5.4 Strategy4:UsePython.


Beforeleavingthisproblem,I reallyshouldmentionthatnoneofthealgorithmdevelopmentwehave so
painstakinglypursuedwasnecessary. Pythonactuallyhasa built-infunctioncalledmaxthatreturns the
largestofitsparameters.Hereis thesimplestversionofourprogram.


def main():
x1, x2, x3 = input("Please enter three values: ")
print "The largestvalue is", max(x1, x2, x3)


Ofcourse,thisversiondidn’t requireany algorithmdevelopmentat all,whichratherdefeatsthepointofthe
exercise!SometimesPythonis justtoosimpleforourowngood....


7.5.5 SomeLessons


Themaxofthreeproblemisnotparticularlyearthshattering,buttheattempttosolve thisproblemhas
illustratedsomeimportantideasinalgorithmandprogramdesign.


 Thereis morethanonewaytodoit.Forany non-trivialcomputingproblem,therearemany waysto
approachtheproblem.Whilethismayseemobvious,many beginningprogrammersdonotreallytake
thispointto heart.Whatdoesthismeanforyou?Don’t rushto codeupthefirstideathatpopsintoyour
head.Thinkaboutyourdesign,askyourselfif thereis a betterwaytoapproachtheproblem.Once
youhave writtenthecode,askyourselfagainif theremightbea betterway. Yourfirsttaskis tofind
a correctalgorithm.Afterthat,strive forclarity, simplicity, efficiency, scalabilityandelegance.Good
algorithmsandprogramsarelike poemsoflogic.They area pleasuretoreadandmaintain.
Bethecomputer. Especiallyforbeginningprogrammers,oneofthebestwaysto formulateanalgorithm
is tosimplyaskyourselfhow youwouldsolve theproblem.Thereareothertechniquesfordesigning
goodalgorithms(seeChapter13);however, thestraightforwardapproachisoftensimple,clearand
efficientenough.
Generalityis good.We arrivedat thebestsolutionto themaxofthreeproblembyconsideringthemore
generalmaxofnproblem.It is notunusualthatconsiderationofa moregeneralproblemcanleadto
a bettersolutionforsomespecialcase.Don’t beafraidtostepbackandthinkabouttheoverarching
problem.Similarly, whendesigningprograms,youshouldalwayshave aneyetowardmakingyour
programmoregenerallyuseful.If themaxofnprogramis justaseasytowriteasmaxofthree,you
mayaswellwritethemoregeneralprogrambecauseit is morelikelytobeusefulinothersituations.
Thatwayyougetthemaximumutilityfromyourprogrammingeffort.
Don’t reinventthewheel.OurfourthsolutionwastousePython’smaxfunction.Youmaythinkthat
wascheating,butthisexampleillustratesanimportantpoint.Alotofverysmartprogrammershave
designedcountlessgoodalgorithmsandprograms.If theproblemyouaretryingtosolve seemstobe
onethatlotsofothersmusthave encountered,youmightbeginbyfindingoutif theproblemhasalready
beensolvedforyou.Asyouarelearningtoprogram,designingfromscratchis greatexperience.Truly
expertprogrammers,however, know whentoborrow.

7.6 Exercises



  1. Explainthefollowingpatternsinyourownwords.


(a)simpledecision
(b)two-waydecision
(c)multi-waydecision


  1. Thefollowingis a (silly)decisionstructure.

Free download pdf