如何获取Python中递归中使用的堆栈帧总数?

时间:2013-11-11 23:53:15

标签: python recursion fibonacci stack stackframe

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

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

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

2 个答案:

答案 0 :(得分: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))

这将返回Fibonacci数,与递归深度配对。

测试:

>>> list(map(fib, range(5)))
[(1, 1), (1, 1), (2, 2), (3, 3), (5, 4)]

答案 1 :(得分: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