我试图绕过递归,当我编写一小段代码时,我不知道例如它如何到达特定的输出。
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
如果有人可以逐步解释它,我将不胜感激。
答案 0 :(得分:1)
这是逐步发生的情况。首次通话时:
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的呼叫
答案 1 :(得分:0)
我同意@abarnert关于使用交互式可视化工具的建议。但是,此代码段足够短,我们可以对其进行全面检测:
indent = 0
print('\t' * indent, "x = 0"); x = 0
def recursion(indent):
global x; indent += 1
print('\t' * indent, "x += 1"); x += 1
print('\t' * indent, 'print(x)'); print(x)
while x < 5:
print('\t' * indent, "while x < 5:")
print('\t', '\t' * indent, "recursion()"); recursion(indent + 1)
print('\t', '\t' * indent, "recursion()"); recursion(indent + 1)
print('\t', '\t' * indent, 'print("example")'); print("example")
print('\t' * indent, 'print("test")'); print("test")
print('\t' * indent, "recursion()"); recursion(indent)
运行它,我们将在左侧显示您的结果,并缩进该程序在每个步骤中所做的工作:
> python3 test.py
x = 0
recursion()
x += 1
print(x)
1
while x < 5:
recursion()
x += 1
print(x)
2
while x < 5:
recursion()
x += 1
print(x)
3
while x < 5:
recursion()
x += 1
print(x)
4
while x < 5:
recursion()
x += 1
print(x)
5
print("test")
test
recursion()
x += 1
print(x)
6
print("test")
test
print("example")
example
print("test")
test
recursion()
x += 1
print(x)
7
print("test")
test
print("example")
example
print("test")
test
recursion()
x += 1
print(x)
8
print("test")
test
print("example")
example
print("test")
test
recursion()
x += 1
print(x)
9
print("test")
test
print("example")
example
print("test")
test
>
很显然,仅对小例子有用。 (但是值得在学习递归过程中至少做一次!)本质上,这是交互式可视化工具会为您执行的操作,从而节省了很多时间和麻烦。