我不明白这种递归的使用

Dro*_*ans 5 python recursion

我正在阅读获得"逆转"徽章的答案,我发现了一个关于递归的问题,其中OP没有费心去做他们的大部分家庭作业.除了一些非常有趣的答案,@ machielo 在python中发布了一个答案,我必须在我的机器上运行以获得控制权.我还是不理解它.

def recursive(x):
    if x > 10:
        print recursive(x/10)
    return x%10

>>> recursive(2678)
2
6
7
8
Run Code Online (Sandbox Code Playgroud)

我尝试了我的第一个猜测,但我知道这是错的

>>> 2678/10
267
>>> 267/10
26
>>> 26/10
2
>>> 2%10
2
Run Code Online (Sandbox Code Playgroud)

好的......那是两个.这如何评估其他数字的输出x

编辑

print是我没有到达的声明.我修改了代码:

>>> 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    # ...
Run Code Online (Sandbox Code Playgroud)

我想在每次运行期间,调用print recursive(x/10)创建一个新的函数对象,每个函数对象都有自己的全新基础案例和输入...

另一个暗示,有人吗?

最后

谢谢大家.我觉得我明白这一点,现在,秘诀是没有这么多print,因为它是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
Run Code Online (Sandbox Code Playgroud)

此外,无论谁进入并更新我之前链接的初始答案...我即将赞成你的评论:

>>> def recursive(x):
if x >= 10:
    print recursive(x/10)    
return x%10
Run Code Online (Sandbox Code Playgroud)

jco*_*ado 11

我认为添加一些print语句非常有用:

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)
Run Code Online (Sandbox Code Playgroud)

输出是:

[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
Run Code Online (Sandbox Code Playgroud)


Fre*_*lio 5

单步执行伪代码示例(破折号表示递归深度):

-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
Run Code Online (Sandbox Code Playgroud)