7.5.STUDY INDESIGN:MAXOFTHREE 115
max = x1
x2 > max
max = x2
max = x3
x3 > max
Figure7.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 = x
print "The largestvalue is", max
main()
Thiscodeusesa decisionnestedinsideofa looptogetthejobdone.Oneachiterationoftheloop,max
containsthelargestvalueseensofar.