首页 > 解决方案 > 堆栈帧如何用于递归函数?

问题描述

我无法理解递归函数的堆栈帧。不知道这是否是正确的地方,但我已经尝试找到示例,但我仍然不明白。例如,我有一个列表的递归函数:

def printout(list):
    if len(list) > 0:
        print(list[0])
        printout(list[1:])

list1 = [5,6,7,8,9] 打印输出看起来像这样:

5 6 7 8 9

然后,如果我像这样更改和的"print(list[0])"位置 "printout(list[1:])"

def printout(list):
    if len(list) > 0:
        printout(list[1:])
        print(list[0])

打印输出将是相反的:

9 8 7 6 5

为什么会这样?堆栈框架如何查找这两个函数?感谢您的帮助!

标签: pythonalgorithmrecursionstack-frame

解决方案


在您的第一个示例中,元素在我们对函数进行递归调用之前被打印出来。因此,您将看到打印的确切顺序。

而在您的第二个示例中,首先我们对函数进行递归调用,然后在递归函数完成执行后打印。因此,递归函数将首先打印,调用函数稍后再打印。因此,您会看到元素以相反的顺序打印。

下面的示例显示了函数堆栈如何增长和语句如何被任何编译器执行。

让我们为函数的每个语句分配一个数字。

示例 1:

def printout(list):
    if len(list) > 0:       # 1
        print(list[0])      # 2
        printout(list[1:])  # 3


Explanation:
printout([5, 6, 7, 8, 9])
    1. check if condition
    2. print(5)                    -> `prints 5 on the console`
    3. printout([6, 7, 8, 9])
        1. check if condition
        2. print(6)                -> `prints 6 on the console`
        3. printout([7, 8, 9])
            1. check if condition
            2. print(7)            -> `prints 7 on the console`
            3. printout([8, 9])
                1. check if condition
                2. print(8)        -> `prints 8 on the console`
                3. printout([9])
                    1. check if condition
                    2. print(9)    -> `prints 9 on the console`
                    3. printout([])
                        1. check if condition
                        return

如果我们从上到下查看打印语句的顺序。它以给定的顺序打印元素。

示例 2:

def printout(list):
    if len(list) > 0:           # 1
        printout(list[1:])      # 1
        print(list[0])          # 2

Explanation:
printout([5, 6, 7, 8, 9])
    1. check if condition
    2. printout([6, 7, 8, 9])
        1. check if condition
        2. printout([7, 8, 9])
            1. check if condition
            2. printout([8, 9])
                1. check if condition
                2. printout([9])
                    1. check if condition
                    2. printout([])
                        1. check if condition
                        return
                    3. print(9)    -> `prints 9 on the console`
                3. print(8)        -> `prints 8 on the console`
            3. print(7)            -> `prints 7 on the console`
        3. print(6)                -> `prints 6 on the console`
    3. print(5)                    -> `prints 5 on the console`

如果我们从上到下查看打印语句的顺序。它显示了为什么元素以相反的顺序打印。


推荐阅读