python - 了解 Python 堆栈中的递归
问题描述
我试图了解递归,当我编写一小段代码时,我不知道它是如何达到特定输出的。
x = 0
def recursion():
global x
x += 1
print(x)
while x < 5:
recursion()
recursion()
print("example")
print("test")
recursion()
输出:
1
2
3
4
5
test
6
test
example
test
7
test
example
test
8
test
example
test
9
test
example
test
如果有人可以逐步解释,我将不胜感激。
解决方案
这就是发生的事情,一步一步。第一次打电话:
def recursion():
global x
x += 1
print(x) # x ==1
while x < 5:
recursion() # on hold, executing recursion
def recursion():
global x
x += 1
print(x) # x ==2
while x < 5:
recursion() # on hold, executing recursion
.
.
.
.
def recursion():
global x
x += 1
print(x) # x == 5, skipping while loop
while x < 5:
recursion()
print('test') # printing test
现在恢复所有保持的呼叫:
def recursion():
global x
x += 1
print(x)
while x < 5:
recursion() # Called when x == 1
recursion() # Resuming, this will put x to 6 and print it, won't enter the loop, so prints test directly
print('example') # print example
def recursion():
global x
x += 1
print(x)
while x < 5:
recursion() # Called when x == 2
recursion() # Resuming, this will put x to 7 and print it, won't enter the loop, so prints test directly
print('example') # print example
直到调用 x==4
推荐阅读
- vue.js - nuxt 中间件未获得更新的存储值
- c# - 如何编写我的 Aspect 类并解决我的问题?
- android - 将 Android apk SHA256 与 SafetyNet apkCertificateDigestSha256 匹配
- html - 除导航栏外,容器流体不占用全宽
- android - 将更新推送到 Ionic 应用程序是否可行且合法?
- java - 如何更改未用@Test 标记的方法(意味着它不在当前测试类中),但由我的注释标记
- python - Pony ORM 中表格的最小值/最大值/平均值
- python - 当我定义自定义管理器时..错误:无法通过 Post 实例访问管理器
- julia - Julia:引用由其他结构定义组成的结构
- python - 管道内的 Sklearn OneHotEncoding 正在转换所有数据类型,而不仅仅是分类/对象类型