12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

6.6. Leap of faith 57__main__factorialn 3 recurse 2result66factorialn 2recurse 1result22factorialn 1recurse 1result11factorialn 01The return values are shown being passed back up the stack. In each frame, the return value is thevalue ofresult,which isthe product ofnandrecurse.In the last frame, the local variables recurse and result do not exist, because the branch thatcreates them does not execute.6.6 Leapof faithFollowingtheflowofexecutionisonewaytoreadprograms,butitcanquicklybecomelabyrinthine.An alternative is what I call the “leap of faith.” When you come to a function call, instead offollowing the flow of execution, you assume that the function works correctly and returns the rightresult.In fact, you are already practicing this leap of faith when you use built-in functions. When you callmath.cosormath.exp,youdon’texaminethebodiesofthosefunctions. Youjustassumethattheyworkbecause thepeople who wrotethe built-infunctions weregood programmers.The same is true when you call one of your own functions. For example, in Section 6.4, we wrotea function called is_divisible that determines whether one number is divisible by another. Oncewe have convinced ourselves that this function is correct—by examining the code and testing—wecan usethe function without looking at the body again.The same is true of recursive programs. When you get to the recursive call, instead of followingtheflowofexecution,youshouldassumethattherecursivecallworks(yieldsthecorrectresult)andthenaskyourself,“AssumingthatIcanfindthefactorialofn−1,canIcomputethefactorialofn?”Inthiscase, itisclear that you can, bymultiplying by n.Of course, it’s a bit strange to assume that the function works correctly when you haven’t finishedwritingit,but that’swhy it’scalled a leap offaith!6.7 OnemoreexampleAfter factorial, the most common example of a recursively defined mathematical function isfibonacci,which has thefollowing definition 1 :1 Seewikipedia.org/wiki/Fibonacci_number.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!