Python Programming: An Introduction to Computer Science

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

yes no

yes no yes no

max = x1 max = x3 max = x2 max = x3

x1 >= x3 x2 > =x3

x1 >= x2

Figure7.5:Flowchartofthedecisiontreeapproachtomaxofthree

7.5.3 Strategy3:SequentialProcessing


Sofar, wehave designedtwo verydifferentalgorithms,butneitheroneseemsparticularlyelegant.Perhaps
thereis yeta thirdway. Whendesigninganalgorithm,a goodstartingplaceis to askyourselfhow youwould
solve theproblemif youwereaskedtodothejob. Forfindingthemaxofthreenumbers,youprobablydon’t
have a verygoodintuitionaboutthestepsyougothrough.You’d justlookat thenumbersandknowwhichis
thelargest.Butwhatif youwerehandeda bookcontaininghundredsofnumbersinnoparticularorder. How
wouldyoufindthelargestinthiscollection?
Whenconfrontedwiththelargerproblem,mostpeopledevelopa simplestrategy. Scanthroughthe
numbersuntilyoufinda bigone,andputyourfingeronit.Continuescanning;if youfinda numberbigger
thantheoneyourfingeris on,move yourfingertothenewone.Whenyougettotheendofthelist,your
fingerwillremainonthelargestvalue.Ina nutshell,thisstrategyhasuslookthroughthelistsequentially,
keepingtrackofthelargestnumberseensofar.
Acomputerdoesn’t have fingers,butwecanusea variabletokeeptrackofthemaxsofar. Infact,the
easiestapproachisjusttousemaxtodothisjob. Thatway, whenwegettotheend,maxautomatically
containsthevalueofthelargest.A flowchartdepictingthisstrategyforthemaxofthreeproblemis shownin
Figure7.6.Hereis thetranslationintoPythoncode:


max = x1
if x2 > max:
max = x2
if x3 > max:
max = x3


Clearly, thesequentialapproachisthebestofourthreealgorithms. Thecodeitselfisquitesimple,
containingonlytwo simpledecisions,andthesequencingis easiertounderstandthanthenestingusedinthe
previousalgorithm.Furthermore,theideascaleswelltolargerproblems;addinga fourthitemaddsonlyone
morestatement.


max = x1
if x2 > max:
max = x2
if x3 > max:
max = x3
if x4 > max:
max = x4

Free download pdf