python - 我不明白递归的这种用法

标签 python recursion

我正在阅读获得“逆转”徽章的答案,我发现了一个关于递归的问题,其中 OP 没有费心去预先完成他们的大部分家庭作业。除了一些非常有趣的答案,@machielo 发布了 an answer在 python 中,我必须在我的机器上运行才能掌握。我还是不明白。

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

>>> recursive(2678)
2
6
7
8

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

>>> 2678/10
267
>>> 267/10
26
>>> 26/10
2
>>> 2%10
2

好吧……就是这两个。这如何评估 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    # ...

我认为在每次运行期间,对 print recursive(x/10) 的调用都会创建一个新的函数对象,每个对象都有自己全新的基本情况和输入...

另一个提示,有人吗?

最后

谢谢大家。我觉得我现在明白了……技巧与其说是print,不如说是x%102345%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

此外,感谢所有进入并更新了 I previously linked to 的初始答案的人...我即将赞成您的评论:

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

最佳答案

我认为添加一些 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)

输出是:

[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

关于python - 我不明白递归的这种用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8706191/

相关文章:

python - 使用 Python 的 os.path,我如何上一个目录?

python - AppEngine HTTPS CName 似乎挂起

c++ - 递归下降解析和语法树

R编程: Level of allowed recursion depth differs when calling a local helper function

在矩阵中搜索值的算法设计

java - 即使递归调用后也不会发生递归

python - 我可以使用我心爱的 % 格式化程序实现可变填充字符和可变宽度吗?

python - 如何在 thrift python 客户端中设置 rpc 超时?

python - 使用 xml.etree.ElementTree 搜索 XML 元素树的属性

function - Lisp &rest 参数和递归调用