Python Programming: An Introduction to Computer Science

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

programs,youmightnotworrytoomuchaboutbadinput;however, professionalqualitysoftwareshoulddo
whateveris feasibletoshieldusersfromunexpectedresults.


7.5 StudyinDesign:MaxofThree.


Nowthatwehave decisionsthatcanalterthecontrolflowofa program,ouralgorithmsareliberatedfrom
themonotony ofstep-by-step,strictlysequentialprocessing.Thisis botha blessinganda curse.Thepositive
sideisthatwecannowdevelopmoresophisticatedalgorithms,aswedidforourquadraticsolver. The
negative sideis thatdesigningthesemoresophisticatedalgorithmsis muchharder. Inthissection,we’ll step
throughthedesignofa moredifficultdecisionproblemtoillustratesomeofthechallengeandexcitementof
thedesignprocess.
Supposeweneedanalgorithmtofindthelargestofthreenumbers. Thisalgorithmcouldbepartofa
largerproblemsuchasdetermininggradesorcomputingtaxes,butwearenotinterestedinthefinaldetails,
justthecruxoftheproblem.Thatis,how cana computerdeterminewhichofthreeuserinputsis thelargest?
Hereis a programoutline.We needtofillinthemissingpart.


def main():
x1, x2, x3 = input("Please enter three values: ")


# missing codesets max to the value of the largest

print "The largestvalue is", max

Beforereadingthefollowinganalysis,youmightwanttotryyourhandat solvingthisproblem.


7.5.1 Strategy1:CompareEachtoAll


Obviously, thisprogrampresentsuswitha decisionproblem.We needa sequenceofstatementsthatsetsthe
valueofmaxtothelargestofthethreeinputsx1,x2, andx3. Atfirstglance,thislookslike a three-way
decision;weneedtoexecuteoneofthefollowingassignments.


max = x1
max = x2
max = x3


It wouldseemwejustneedtoprefaceeachonewiththeappropriatecondition(s),sothatit is executedonly
inthepropersituation.
Let’s considerthefirstpossibility, thatx1is thelargest.To seethatx1is actuallythelargest,wejust
needtocheckthatit is at leastaslargeastheothertwo.Hereis a firstattempt:


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


Yourfirstconcernhereshouldbewhetherthisstatementissyntacticallycorrect. Theconditionx1
x2 x3doesnotmatchthetemplateforconditionsshownabove.Mostcomputerlanguageswouldnot
acceptthisasa validexpression.It turnsoutthatPythondoesallow thiscompoundcondition, andit behaves
exactlylike themathematicalrelationsx 1  x 2  x3.Thatis,theconditionis truewhenx1is at leastaslarge
asx2andx2is at leastaslargeasx3. So,Pythonhasnoproblemwiththiscondition.
Wheneveryouwritea decision,youshouldaskyourselftwo crucialquestions.First,whenthecondition
is true,areyouabsolutelycertainthatexecutingthebodyofthedecisionis therightactiontotake?Inthis
case,theconditionclearlystatesthatx1is at leastaslargeasx2andx3, soassigningitsvaluetomaxshould
becorrect.Alwayspayparticularattentiontoborderlinevalues.Noticethatourconditionincludesequalas
wellasgreater. We shouldconvinceourselvesthatthisis correct.Supposethatx1,x2, andx3areallthe
same;thisconditionwillreturntrue.That’s OKbecauseit doesn’t matterwhichwechoose,thefirstis at least
asbigastheothers,andhence,themax.

Free download pdf