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.

56 Chapter 6. Fruitful functionsIfyousaw thatdefinition inthedictionary, you mightbeannoyed. Ontheother hand, ifyoulookedup the definition of the factorial function, denoted with the symbol !, you might get something likethis:0!=1n!=n(n−1)!Thisdefinitionsaysthatthefactorialof0is1,andthefactorialofanyothervalue,n,isnmultipliedby thefactorial of n−1.So3!is3times2!,whichis2times1!,whichis1times0!. Puttingitalltogether,3!equals3times2times 1times1, which is 6.If you can write a recursive definition of something, you can usually write a <strong>Python</strong> program toevaluate it. The first step is to decide what the parameters should be. In this case it should be clearthatfactorialtakes an integer:def factorial(n):Iftheargument happens tobe 0, all wehave todo isreturn1:def factorial(n):if n == 0:return 1Otherwise, and this is the interesting part, we have to make a recursive call to find the factorial ofn−1and then multiply itby n:def factorial(n):if n == 0:return 1else:recurse = factorial(n-1)result = n * recursereturn resultTheflowofexecutionforthisprogramissimilartotheflowofcountdowninSection5.8. Ifwecallfactorialwiththevalue 3:Since 3 isnot 0, wetake the second branch and calculate the factorial ofn-1...Since 2isnot 0, we take thesecond branch and calculate thefactorial ofn-1...Since 1 is not 0, we take the second branch and calculate the factorial ofn-1...Since 0 is 0, we take the first branch and return 1 without makingany more recursive calls.Thereturnvalue(1)ismultipliedbyn,whichis1,andtheresultisreturned.The return value (1) ismultipliedby n, which is2, and the resultisreturned.Thereturnvalue(2)ismultipliedbyn,whichis3,andtheresult,6,becomesthereturnvalueofthefunction call that startedthe whole process.Here iswhat the stackdiagram looks likeforthis sequence of function calls:

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

Saved successfully!

Ooh no, something went wrong!