[Tutor] Re: Help understanding part of the tutorial
Lee Harr
missive@hotmail.com
Sun Jan 5 18:59:02 2003
>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
_________________________________________________________________
Help STOP SPAM: Try the new MSN 8 and get 2 months FREE*
http://join.msn.com/?page=features/junkmail