Recursion

Jakle jakle1 at hotmail.com
Sun Sep 28 20:48:29 EDT 2003


Hi all. Need alittle help here. This is an example from "How to Think Like a
Computer Scientist: Learning with Python, Chapter 5".  It's an open source
ebook, so if you feel like it you can find it here:
http://www.ibiblio.org/obp/thinkCSpy/

The example uses factorials to explain more complex recursion.

"Explanation From the Book Begins Here"++++++++++++++++++

>def factorial(n):
>    if n == 0:
>        return 1
>    else:
>        recurse = factorial(n-1)
>        result = n * recurse
>        return result
>
>    The flow of execution is as follows.
>    If we call "factorial" with the value 3:
>
>    Since 3 is not 0, we take the second branch and calculate the factorial
of n-1...
>        Since 2 is not 0, we take the second branch and calculate the
factorial of n-1...
>            Since 1 is not 0, we take the second branch and calculate the
factorial of n-1...
>                Since 0 is 0, we take the first branch and return 1 without
making any more recusive calls.
>            The return value (1) is multiplied by n, which is 1, and the
result is returned.
>        The return value (1) is multiplied by n, which is 2, and the result
is returned.
>    The return value (2) is multiplied by n, which is 3, and the result, 6,
becomes the return value of the function that started the whole process.

"Example Ends Here"++++++++++++++++++++++++++++++++

I thought I understood what was going on untill "Since 0 is 0...", but after
that I get lost. Where are the variables being stored.
And how does 1*1=2 ---> The return value (1) is multiplied by n, which is 1,
and the result is returned. The return value (1) is multiplied by n, which
is 2, and the result is returned.
Sorry if I explained my problem oddly. You can see the example in the above
link, under chapter 5.






More information about the Python-list mailing list