Python Programming: An Introduction to Computer Science

(Nora) #1
3.3.ACCUMULATINGRESULTS:FACTORIAL 29

Python Mathematics English
pi π Anapproximationofpi.
e e Anapproximationofe.
sin(x) sinx Thesineofx.
cos(x) cosx Thecosineofx.
tan(x) tanx Thetangentofx.
asin(x) arcsinx Theinverseofsinex.
acos(x) arccosx Theinverseofcosinex.
atan(x) arctanx Theinverseoftangentx.
log(x) lnx Thenatural(basee) logarithmofx
log10(x) log 10 x Thecommon(base10)logarithmofx.
exp(x) ex Theexponentialofx.
ceil(x) x Thesmallestwholenumber x
floor(x) x Thelargestwholenumber x

Table3.2:Somemathlibraryfunctions.

Let’s writea programthatwillcomputethefactorialofa numberenteredbytheuser. Thebasicoutline
ofourprogramfollowsanInput-Process-Outputpattern.


Input number to takefactorial of, n
Compute factorial of n, fact
Output fact


Obviously, thetricky parthereis inthesecondstep.
Howdoweactuallycomputethefactorial? Let’s tryonebyhandtogetanideafortheprocess. In
computingthefactorialof6,wefirstmultiply 6 5 30.Thenwetake thatresultanddoanothermultipli-
cation 30 4 120.Thisresultis multipliedbythree 120 3 360.Finally, thisresultis multipliedby 2
360 2 720.Accordingtothedefinition,wethenmultiplythisresultby1,butthatwon’t changethefinal
valueof720.
Now let’s trytothinkaboutthealgorithmmoregenerally. Whatis actuallygoingonhere?We aredoing
repeatedmultiplications,andaswegoalong,wekeeptrackoftherunningproduct.Thisis a verycommon
algorithmicpatterncalledanaccumulator. We buildup,oraccumulate,a finalvaluepiecebypiece.To
accomplishthisina program,wewilluseanaccumulatorvariableanda loopstructure.Thegeneralpattern
lookslike this.


Initialize the accumulatorvariable
Loop until final resultis reached
update the valueof accumulator variable


Realizingthisis thepatternthatsolvesthefactorialproblem,wejustneedtofillinthedetails.We will
beaccumulatingthefactorial.Let’s keepit ina variablecalledfact. Eachtimethroughtheloop,weneed
tomultiplyfactbyoneofthefactorsn


n 1 1.It lookslike weshoulduseaforloopthatiterates
over thissequenceoffactors.Forexample,tocomputethefactorialof6, weneeda loopthatworkslike this.


fact = 1
for factor in [6,5,4,3,2,1]:
fact = fact * factor


Take a minutetotracethroughtheexecutionofthisloopandconvinceyourselfthatit works.Whenthe
loopbodyfirstexecutes,facthasthevalue 1 andfactoris 6. So,thenew valueoffactis 1 6 6.
Thenext timethroughtheloop,factorwillbe 5 , andfactis updatedto 6 5 30.Thepatterncontinues
foreachsuccessive factoruntilthefinalresultof 720 hasbeenaccumulated.
Theinitialassignmentof 1 tofactbeforetheloopisessentialtogettheloopstarted. Eachtime
throughtheloopbody(includingthefirst),thecurrentvalueoffactis usedtocomputethenextvalue.The

Free download pdf