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

标签 python recursion fibonacci stack stack-frame

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

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/

相关文章:

python - Python语法错误

python - 有没有办法限制 Python SEaborn 条形图(或任何图表)的结果数量?

python - 如何使用 .loc 通过 groupby pandas 标记新列

recursion - 编译器如何理解递归?

c - 斐波那契!递归打印

c - 递归和斐波那契数列

python - 单击 python 我如何从命令行读取 json 之类的参数

sql-server-2005 - T-SQL CTE错误: Types don't match between the anchor and the recursive part

c++ - 幂集 ~ 递归 ~ Hasse 图

algorithm - 快速计算斐波那契数列的方法