I was reading through the answers earning a "reversal" badge and I found a question regarding recursion where the OP didn't bother to do much of their homework assignment up front. Aside from some really funny answers, @machielo posted an answer in python that I had to run on my machine to get a grip on. I'm still not understanding it.
def recursive(x):
if x > 10:
print recursive(x/10)
return x%10
>>> recursive(2678)
2
6
7
8
I tried out my first guess, but I know it's wrong
>>> 2678/10
267
>>> 267/10
26
>>> 26/10
2
>>> 2%10
2
Okay...that's the two. How does this evaluate the output of the other numbers in x
?
It's the print
statement that I don't get here. I modified the code as such:
>>> def recursive(x):
if x > 10:
print x
print recursive(x/10)
return x%10
>>> #I will comment the interpreter session here...
>>> recursive(2345)
2345 # first feed in...print the raw number `x`
234 # 2345/10 does equal 234...the 5 is being held back somewhere...
23 # and each pass through the recursive loop removes the last digit...
2 # but where was it being stored at, so that each evaluation of
3 # x > 10 finally started returning False
4 # and returns the number, exiting the function
5 # ...
I'm thinking that during each run through, the call to print recursive(x/10)
creates a new function object, each with it's own brand new base case and input...
Another hint, anyone?
Thanks to everyone. I feel I understand this now...the trick wasn't so much print
as it was x%10
. 2345%10 == 5
...
>>> def recursive(x):
print "Raw `x`:", x
if x > 10:
print "Recurse `x`:", x
print recursive(x/10)
print "Last `x`:", x
return x%10
>>> recursive(2345)
Raw `x`: 2345
Recurse `x`: 2345
Raw `x`: 234
Recurse `x`: 234
Raw `x`: 23
Recurse `x`: 23
Raw `x`: 2
Last `x`: 2
2
Last `x`: 23
3
Last `x`: 234
4
Last `x`: 2345
5
Also, credit to whoever went in and updated the initial answer that I previously linked to...I'm about to upvote your comment:
>>> def recursive(x):
if x >= 10:
print recursive(x/10)
return x%10
I think that adding a few print
statements it's really helpful:
def recursive(x):
print '[start] recursive({0})'.format(x)
if x > 10:
print recursive(x/10)
print '[return] recursive({0}) = {1}'.format(x, x%10)
return x%10
print recursive(2678)
The output is:
[start] recursive(2678)
[start] recursive(267)
[start] recursive(26)
[start] recursive(2)
[return] recursive(2) = 2
2
[return] recursive(26) = 6
6
[return] recursive(267) = 7
7
[return] recursive(2678) = 8
8
Stepping through your example in pseudocode (number of dashes indicates recursion depth):
-call recursive(2678)
--2678 > 10, call recursive(267)
---267 > 10, call recursive(26)
----26 > 10, call recursive(2)
-----return 2%10 (which is 2)
----print 2, then return 26 % 10 (which is 6)
---print 6, then return 267 % 10 (which is 7)
--print 7, then return 2678 % 10 (which is 8)
-return 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With