为什么通过改变print语句的位置,在斐波那契模式中,在递归中,输出的顺序改变了?



# method 1

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块中,在递归函数下面给出了print函数。因此,我们得到了斐波那契级数,但顺序相反(从大到小)。

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]

在第二种方法中,我们得到了相同的斐波那契模式,但这次是按照原来的顺序(从小到大)。

唯一的区别是print语句在else语句块的最开始。

这怎么可能??

如何通过改变print语句的位置来改变整个顺序?

我们知道,在递归中,当堆栈减少时,值从内存中取出,并打印输出。(从较大的值到堆栈深度处的最小值)因此,对于这两种情况,打印输出的顺序应该保持相同,不是吗?

请告诉我,改变else块中print语句的位置是如何改变输出顺序的

你的推理是正确的,但是考虑到你在第一个方法中做的每个递归调用(在调用fib后打印),你将首先进行递归,直到你达到退出条件。这将打印"第一个打印语句",然后,它将在调用fib后使用最后计算的值执行打印。然后我们在递归层上,这样就反过来打印了fibonaci序列。

一种观察的方法是想象盒子在另一个盒子里。如果在调用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

最新更新