On 07/11/2010 04:59 PM, Dominik Danter wrote:
Hello

As en exercise I wrote the following function:


def recursfac(x,carryover=1):
    print 'x:',x,'carryover:', carryover
    if x > 1:
        carryover *= x
        recursfac(x-1, carryover)
    else:
        return carryover

print recursfac(3)

Very much to my surprise I get the following output:

x: 3 carryover: 1
x: 2 carryover: 3
x: 1 carryover: 6
None

Where did I go wrong?

Your problem is that you expect the "return" to exit the recursion altogether. Instead, carryover is passed to the previous level of the recursion, which has nothing more to execute and returns None.

So the first step to fix this would be to make sure that your function returns carryover no matter what:

def recursfac(x,carryover=1):
    print 'x:',x,'carryover:', carryover
    if x > 1:
        carryover *= x
        recursfac(x-1, carryover)
        return carryover
    else:
        return carryover

Or simply (to remove the code duplication):

def recursfac(x,carryover=1):
    print 'x:',x,'carryover:', carryover
    if x > 1:
        carryover *= x
        recursfac(x-1, carryover)
    return carryover

Now there's still one more problem. The output is this:

x: 3 carryover: 1
x: 2 carryover: 3
x: 1 carryover: 6
3

Why is it returning 3 istead of 6?

Well, the function didn't catch the returned carryover value on the way up, so it's just returns what it knows: the value of carryover that it self has computed.
Instead, you have to do this:

def recursfac(x,carryover=1):
    print 'x:',x,'carryover:', carryover
    if x > 1:
        carryover *= x
        carryover = recursfac(x-1, carryover)
    return carryover

And this returns
x: 3 carryover: 1
x: 2 carryover: 3
x: 1 carryover: 6
6

Done!

What you should learn from this is that, when doing recursion, figuring out what your function should do on the way up is as crucial as what you want it to do on the way down.

Nick


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to