为什么通过更改打印语句的位置,在斐波那契模式中,在递归中,输出顺序会发生变化?
Why by changing the position of print statement, in Fibonacci pattern, in recursion, the order of output changes?
#方法一
def fib(a,b,c,i,x):
if i==x:
c = a+b
print(c, "first print statement") # first print statement [21]
return c # c = 21, returns to the function itself
else:
c=a+b
a=b
b =c
fib(a,b,c,i+1,x)
print(c,a,i) # recurssive prive statements [13,8,5,3,2,1]
return i
print(fib(0,1,1,0,6), "final print statement") # final print statement [0]
在第一种方法中,在else块中,在递归函数下面给出打印函数。因此我们得到了一个斐波那契数列,但顺序相反(从大到小)。
def fib(a,b,c,i,x):
if i==x:
c = a+b
print(a, "first print statement") # first print statement [21]
return c # c = 21, returns to the function itself
else:
print(a,i)
c=a+b
a=b
b =c
fib(a,b,c,i+1,x)
# recurssive prive statements [13,8,5,3,2,1]
return i
print(fib(0,1,1,0,6),"last print statement") # final print statement [0]
在方法二中,我们得到了相同的斐波那契模式,但这次是按照原来的顺序(从小到大)。
唯一的区别是打印语句位于 else 块的最开头。
这怎么可能??
如何通过改变打印语句的位置来改变整个顺序?
我们知道在递归中,当堆栈下降时,值从内存中出来,并打印输出。 (从较大的值到堆栈深度中存在的最小值) 所以打印输出的顺序应该在两种情况下都保持不变,不是吗?
请帮助我知道,改变 else 块中 print 语句的位置如何改变输出顺序。
您的推理是正确的,但是考虑到您在第一种方法中进行的每次递归调用(调用 fib 后打印),您将首先进行递归直到达到退出条件.这将打印 'first print statement' 然后,它将在调用 fib 后使用最后一个计算值执行打印。然后我们进入递归层,从而反向打印斐波那契数列。
一种观看方式是想象盒子在另一个盒子里。在调用 fib 之后使用 print,您将从最后一个值打印到第一个值,而在调用 fib 之前使用 print,您将从第一个值打印到最后一个。
您可以试试这个演示递归层次的小程序:
def recursive_function(level):
if level >= 5:
print('[ Level', level, ']-You reached the bottom of the call stack. Time to go back up in reverse')
else:
print('[ Level', level, ']-I get printed first and then you move down to level', level+1, 'of the call stack')
recursive_function(level+1)
print('[ Level', level, ']-I won\'t get printed unless you return from the level', level+1)
if __name__ == '__main__':
recursive_function(0)
打印:
[ Level 0 ]-I get printed first and then you move down to level 1 of the call stack
[ Level 1 ]-I get printed first and then you move down to level 2 of the call stack
[ Level 2 ]-I get printed first and then you move down to level 3 of the call stack
[ Level 3 ]-I get printed first and then you move down to level 4 of the call stack
[ Level 4 ]-I get printed first and then you move down to level 5 of the call stack
[ Level 5 ]-You reached the bottom of the call stack. Time to go back up in reverse
[ Level 4 ]-I won't get printed unless you return from the level 5
[ Level 3 ]-I won't get printed unless you return from the level 4
[ Level 2 ]-I won't get printed unless you return from the level 3
[ Level 1 ]-I won't get printed unless you return from the level 2
[ Level 0 ]-I won't get printed unless you return from the level 1