[Tutor] recursive function example
Alan Gauld
alan.gauld at btinternet.com
Thu Dec 12 09:50:01 CET 2013
On 12/12/13 04:18, ugajin at talktalk.net wrote:
>
> In a way,it may help to identify the issue
> def multiply(a,b)
> return a*b
> clearly returns the product of the two arguments, a and b
> I presume it returns a+a rather than b+b+b
It depends on how multiplication is implemented in the CPU microcode.
But thats none of our concern, it uses Python multiplication.
> mult(a, b-1) also has two arguments.
> and rest takes the value of the two arguments,
No it doesn't.
I don't know why you think that but rest takes the
*return* value of mult(). It is no different to the
multiply() case.
> I do not see an instruction to multiply the arguments
That's what mult() is. It is a function that multiplies
it's arguments by successive addition. It just happens
to do that using recursion. But you have to "trust"
that it will multiply the two arguments.
> How in the original def mult(a, b) . . .,
> does mult(a, b-1) say return the product of a and b-1?
It says return 'value'. And value is the addition of
the first argument and the product of (a * b-1)
Let's go back a couple of steps.
Do you understand how it works for this case:
mult(3,0)
It returns zero because b is zero, right?
Now consider what it does for
mult(3,1)
It checks if b is zero, it's not, so it executes
rest = 3 + mult(3,0)
But you know that mult(3,0) returns zero, so
rest = 3 + 0
ie rest = 3.
Do you understand this far?
--
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