python - 堆栈帧如何用于递归函数?
问题描述
我无法理解递归函数的堆栈帧。不知道这是否是正确的地方,但我已经尝试找到示例,但我仍然不明白。例如,我有一个列表的递归函数:
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
为什么会这样?堆栈框架如何查找这两个函数?感谢您的帮助!
解决方案
在您的第一个示例中,元素在我们对函数进行递归调用之前被打印出来。因此,您将看到打印的确切顺序。
而在您的第二个示例中,首先我们对函数进行递归调用,然后在递归函数完成执行后打印。因此,递归函数将首先打印,调用函数稍后再打印。因此,您会看到元素以相反的顺序打印。
下面的示例显示了函数堆栈如何增长和语句如何被任何编译器执行。
让我们为函数的每个语句分配一个数字。
示例 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`
如果我们从上到下查看打印语句的顺序。它显示了为什么元素以相反的顺序打印。
推荐阅读
- html - 如何将img放在div旁边?
- reactjs - 如何使用 React js 中的 Hooks 在网页上上传/浏览和显示图像?
- php - 执行功能不起作用它在窗口数组问题中出错
- java - 从 URL 获取 Json 中的多个 UUID
- c - 我无法连接 ATtiny85 和 EM18(RFID 阅读器)
- spring - 想按类型查找用户
- java - 在 Manjaro Linux 上运行 Java 程序
- python - 使用python在Excel中搜索字符串
- html - MediaQuery 不工作。对于桌面(超过 992 像素)全部保留在一行中,对于平板电脑,前 2 个应为 50% 宽度,第 3 个应为 100%,对于移动设备全部为 100%
- perl - 为什么这个 Perl 的斐波那契单线行得通?