小编Ram*_*mu 的帖子

Python中的递归堆栈

我正在尝试了解以下 python 递归函数的调用堆栈。该函数给出给定集合的所有组合。

def subsets(A):
    if not A:
        yield []
    else:
        for s in subsets(A[1:]):
            yield s
            yield [A[0]] + s
l1=[1,2,3]
print(list(subsets(l1)))
Run Code Online (Sandbox Code Playgroud)

该程序正在根据需要生成输出:

[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
Run Code Online (Sandbox Code Playgroud)

但是我无法可视化调用堆栈。它怎么能打印[1,2,3]?我的理解如下

call stack 1 : values are : for s in [2,3], a[0] = 1, a = [1,2,3]
call stack 2 : values are : for s in [3], a[0] = 2, a = [2,3]
call stack 3 : values are …
Run Code Online (Sandbox Code Playgroud)

python recursion callstack

5
推荐指数
1
解决办法
97
查看次数

标签 统计

callstack ×1

python ×1

recursion ×1