7.5.STUDY INDESIGN:MAXOFTHREE 115
max = x1x2 > maxmax = x2max = x3x3 > maxFigure7.6:Flowchartofa sequentialapproachtothemaxofthreeproblem.It shouldnotbesurprisingthatthelastsolutionscalestolargerproblems;weinventedthealgorithm
byexplicitlyconsideringhowtosolve a morecomplex problem.Infact,youcanseethatthecodeis very
repetitive.We caneasilywritea programthatallowstheusertofindthelargestofnnumbersbyfoldingour
algorithmintoa loop.Ratherthanhavingseparatevariablesforx1,x2,x3, etc.,wecanjustgetthevalues
oneat a timeandkeepreusinga singlevariablex. Eachtime,wecomparethenewestxagainstthecurrent
valueofmaxtoseeif it is larger.
program: maxn.py
Finds the maximumof a series of numbers
def main():
n = input("Howmany numbers are there? ")
# Set max to be thefirst value
max = input("Entera number >> ")# Now compare the n-1 successivevalues
for i in range(n-1):
x = input("Entera number >> ")
if x > max:
max = xprint "The largestvalue is", maxmain()
Thiscodeusesa decisionnestedinsideofa looptogetthejobdone.Oneachiterationoftheloop,max
containsthelargestvalueseensofar.