[Tutor] Problem with python

Wayne Werner waynejwerner at gmail.com
Wed Oct 20 01:39:17 CEST 2010

```On Tue, Oct 19, 2010 at 4:02 PM, Matthew Nunes <matthewnunes at hotmail.com>wrote:

>  To whom it may concern,
>
>                                    Hi, I've just started learning how to
> program in python using Allan B. Downy's book "How to think like a computer
> scientist" and it explained something in the recursion chapter which have
> still been unable to understand. It wrote a piece of code for the factorial
> function in math for example 3! is 3 * 2 * 1. I cannot understand the how it
> claimed the code executed, and  logically it makes no sense to me. Please
> explain it to me, as I have spent hours trying to get my head around it, as
> the book(in my opinion) did not explain it well. Here it is:
>

That's a pretty solid book. This example uses recursion - for a great
example of recursion, search Google for recursion

But we can examine the code:

This is a function that takes one parameter named n

> def factorial(n):
>
If n is 0 then return 1 (since 0! = 1)

>     if n == 0:
>
>         return 1
>
>     else:
>
If n > 0 then the definition of a factorial is n * factorial(n-1) - which we
do here in two steps

>          recurse = factorial(n-1)
>
>         result = n * recurse
>
And then we return the result

>         return result
>
> If there is and easier piece of code that you know of that can be used for
> factorial, if you could please also tell me that.
>

This is probably the very easiest recursive example to get your head around
because the definition of factorial is recursive. However, it's a *terribly*
inefficient way to compute the factorial of a number.

The most efficient way for something like 3 is this:

import math
math.factorial(3)

Using the built-in functions are always better.

However, if you're wanting a code example you can do this one:

def factorial(n):
if n == 0:
n = 1
fact = 1
for x in xrange(1, n+1):
fact = fact * x         # This could be replaced by fact *= x
return fact

Or you could do something a little more advanced:

def factorial(n):
if n == 0:
n = 1
return reduce(lambda x,y: x*y, xrange(1,n+1))

But that's probably a little beyond your comprehension level at this point.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101019/ccf062fb/attachment.html>
```