[Tutor] recursive function example

Alan Gauld alan.gauld at btinternet.com
Wed Dec 11 19:15:11 CET 2013


On 11/12/13 12:36, ugajin at talktalk.net wrote:

> What I do not see is how?
>
> Clearly, a = 3, it is constant throughout each iteration, and
> if rest is equal to 3, then a + rest must be equal to 6.

Correct and the return value from the second invocation of mul() is 3.

> You spoke of drilling down, and I see that mult(3, 2) drills down until
> b == 0, I am less clear how it then begins to ascend,

It returns a value to the previous invocation of mul()
Remember we are calling mul() several times, each with a new set of values.

So mul(3,2) calls mul(3,1)
and mul(3,1) calls mul(3,0)

mul(3.0) returns 0 to mul(3,1)
mul(3,1) then returns 3+0 => 3 to mul(3,2)
mul(3,2) returns 3+3 => 6.

Let me try one more time but this time I will remove the recursion
and substitute the equivalent code with modified variable names.

> how is rest assigned a single argument/value?

rest = a + mul(a,b-1)

rest takes on the sum of a and the return value from the
new call to mul()

> I agree, rest equals 0 (zero) on the first iteration

No it doesn't. rest is never created in the b=0 case.
mul just returns 0 directly. See below...

> It seems to me that rest has two arguments, not one.
> I do not understand "+>", is it a typo perhaps?

Yes it was supposed to be => as in 3+2 => 5

Here goes breakdown number 2.

def mult1(a1, b1):
     if b1 == 0:
         return 0
     rest1 = mult2(a1, b1 - 1)
     value1 = a1 + rest1
     return value1

def mult2(a2, b2):
     if b2 == 0:
         return 0
     rest2 = mult3(a2, b2 - 1)
     value2 = a2 + rest2
     return value2

def mult3(a3, b3):
     if b3 == 0:
         return 0

mult1(3,2)

Try working through that set.
Then look at the code inside each function.
It is identical... So we only really need
one function mult().

Does that help?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list