[Tutor] Re: Help understanding part of the tutorial

Mike P mcp.bov@insightbb.com
Tue Jan 7 16:23:24 2003


Message: 5
From: "Lee Harr" <missive@hotmail.com>
To: tutor@python.org
Date: Sun, 05 Jan 2003 23:46:30 +0000
Subject: [Tutor] Re: Help understanding part of the tutorial

>def mult(a,b):
>    if b == 0:
>        return 0
>    rest = mult(a,b - 1)
>    value = a + rest
>    return value
>
>print "3*2 = ",mult(3,2)
>
>My question is that I don't get how mult(a,b-1) returns a value
>


Sometimes when debugging, or just trying to understand a piece
of code, it helps to move through the code step by step thinking
(or writing down) what the computer will do at each step:


ok, I am going to call mult(3, 2)
a = 3, b = 2
is b == 0? nope, so
rest = mult(3, 1)

ok, I am going to call mult(3, 1)
a = 3, b = 1
is b == 0? nope, so
rest = mult(3, 0)
# note that rest here is different from the rest up above,
# rest is "local" to this function call and is completely
# independent of the rest in the mult(3, 2) call.

ok, I am going to call mult(3, 0)
a = 3, b = 0
is b == 0? YES, so
return 0
# but, return 0 to where? who called this?
# ah, yes, it was the call to mult(3, 1), so

# back in the call to mult(3, 1)
a = 3, b = 1, rest = 0
value = 3 + 0
return 3
# return to who?
# to the mult(3, 2) call, so

# back in the call to mult(3, 2)
a = 3, b = 2, rest = 3
value = 3 + 3
return 6
# to who?
# mult(3, 2) was the original call, so we're finished


This is called a "recursive" function definition.
(which means that the function calls itself in the process
  of calculating a final answer, and sets some kind of a
  condition for ending the stack of recursive calls)

I am pretty sure that any recursive function can be written
in a non-recursive way. For instance:

def mult(a,b):
    total = 0
    while a:
        total += b
        a -= 1
    return total

or, of course

def mult(a, b):
    return a * b
-----------------------------------------

I'm still learning Python and wondered if there was a reason
I'm not seeing to use:
def mult(a,b):
    if b == 0:
        return 0
    rest = mult(a,b - 1)
    value = a + rest
    return value

Instead of:
def mult(a, b):
    return a * b

Regards,
Mike P.


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.435 / Virus Database: 244 - Release Date: 12/30/2002