简体   繁体   English

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

[英]how to I get the total number of stack frames used in recursion in Python?

here is the simple code for calculating fibonacci series: 这是计算斐波那契数列的简单代码:

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

if n=10, I want to know how many stack frames are involved for this calculation. 如果n = 10,我想知道此计算涉及多少堆栈帧。 Is there a way to get in real time? 有没有一种实时获取方法?

The simplest solution is to add an extra parameter, then thread it through the result: 最简单的解决方案是添加一个额外的参数,然后将其穿过结果:

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))

This will return the Fibonacci number, paired with the recursion depth. 这将返回斐波那契数和递归深度。

Test: 测试:

>>> list(map(fib, range(5)))
[(1, 1), (1, 1), (2, 2), (3, 3), (5, 4)]
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)

eg 例如

>>> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM