下面是计算斐波那契数列的简单代码:
def fib(n):
if n==0 or n==1:
return 1
else:
return fib(n-1)+fib(n-2)
如果 n=10,我想知道这个计算涉及多少堆栈帧。有没有办法实时获取?
最佳答案
最简单的解决方案是添加一个额外的参数,然后通过结果对其进行线程处理:
def fib(n, depth=1):
if n == 0 or n == 1:
return (1, depth)
else:
result1, depth1 = fib(n-1, depth+1)
result2, depth2 = fib(n-2, depth+1)
return (result1 + result2, max(depth1, depth2))
这将返回与递归深度配对的斐波那契数。
测试:
>>> list(map(fib, range(5)))
[(1, 1), (1, 1), (2, 2), (3, 3), (5, 4)]
关于python - 如何获取 Python 递归中使用的堆栈帧总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19918351/