1

这是计算斐波那契数列的简单代码:

def fib(n):
    if n==0 or n==1:
       return 1
    else:
      return fib(n-1)+fib(n-2)

如果 n=10,我想知道这个计算涉及多少堆栈帧。有没有办法实时获取?

4

2 回答 2

3

最简单的解决方案是添加一个额外的参数,然后将其贯穿结果:

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)]
于 2013-11-11T23:58:49.960 回答
2
import inspect
def fib(n):
    fib.calls += 1
    print "depth =", len(inspect.stack())
    print "calls =", fib.calls
    if n == 0 or n == 1:
        return 1
    else:
        return fib(n - 1) + fib(n - 2)

例如

>>> fib.calls = 0
>>> fib(5)
depth = 2
calls = 1
depth = 3
calls = 2
depth = 4
calls = 3
depth = 5
calls = 4
depth = 6
calls = 5
depth = 6
calls = 6
depth = 5
calls = 7
depth = 4
calls = 8
depth = 5
calls = 9
depth = 5
calls = 10
depth = 3
calls = 11
depth = 4
calls = 12
depth = 5
calls = 13
depth = 5
calls = 14
depth = 4
calls = 15
8
于 2013-11-12T00:13:28.957 回答