[Tutor] recursive function example
ugajin at talktalk.net
ugajin at talktalk.net
Wed Dec 11 13:36:17 CET 2013
It is kind of you to take the trouble of trying to explain.
I see the value assigned to rest on each iteration from the debugging script that I made,
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.
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, and if it does, why? But, my question is how is rest assigned
a single argument/value?
I agree, rest equals 0 (zero) on the first iteration and 3 on the second, but as I don't see how,
I cannot understand how value = a + rest => 3+0 => 3 although I get:
value = a + rest, and I get (where rest = 0) a + rest => 3+0 and I get 3+0 => 3
What am I missing? Is it something that isn't explicit?
It seems to me that rest has two arguments, not one.
I do not understand "+>", is it a typo perhaps?
Many thanks.
-A
-----Original Message-----
From: Alan Gauld <alan.gauld at btinternet.com>
To: tutor at python.org
Sent: Wed, 11 Dec 2013 9:05
Subject: Re: [Tutor] recursive function example
On 10/12/13 14:48, ugajin at talktalk.net wrote:
OK, I'll try again, this time just walking through the code from the top.
> 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)
We print "3 * 2 = " and then call mult(3,2)
b does not equal zero so we move to the line rest = mult(a,b-1)
This calls mult(3,1)
Now in the new invocation of mult()
b does not equal zero so we move to the line rest = mult(a,b-1)
This calls mult(3,0)
Now in the new invocation of mult()
b does equal zero so we return zero
Now back in the mult(3,1) version of mult()
rest now equals zero
value = a + rest => 3+0 => 3
we return 3
Now back in the original invocation of mult()
rest = 3
value = a+rest +> 3+3 => 6
we return 6
we print 6.
End of program
Remember that each time mult() is called it creates
its own mini-world of variables independent of the
previous calls.
HTH
-- Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
_______________________________________________
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131211/397fd342/attachment-0001.html>
More information about the Tutor
mailing list