python递归程序中的困惑



嘿,有人能向我解释一下输出吗?

不明白为什么它又倒计时了。

def kaboom(i):
print("first Print: ", i)
if i < 3:
kaboom(i+1)
print("second Print: ", i)

输出:

first Print:  1
first Print:  2
first Print:  3
second Print:  3
second Print:  2
second Print:  1

Second Print倒计时,因为对于您对kaboom(i+1(的每一次调用,该调用都被放在调用堆栈的顶部。一旦i>=3,堆栈停止增长,调用从停止的地方弹出。因此打印3,kaboom(2+1(的执行结束。然后,对kaboom(1+1(的调用从停止的地方继续,打印2并结束。最后kaboom(1(继续并打印1。

您的函数是diving到最远的调用,然后返回并打印second Print

call 1 --> i = 1             back to call 1 --> second Print, i it is still 1
↓                        ↑
call 2 --> i = 2         back to call 2 --> second Print, i it is still 2 
↓                        ↑
cal 3 --> i = 3 (end of call chain, it goes back)
要理解这一点,您需要了解递归是如何工作的。它基于堆栈的概念。您可以查看以下链接,以获得清晰的了解:https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/

如果是i<3,您将再次调用相同的函数,因此它将打印第一个打印,依此类推。但在返回后,执行不会立即结束。它必须执行该方法的其余部分,即第二次打印。

递归策略使用的堆栈起到后进先出的作用。在你的情况下,如果我是对的,你的基本条件只在3时满足,在此之前,它被存储在堆栈中,然后被打印。

这样想:每次调用kaboom时,都会创建一个新的kaboom。卡博姆第一次被称为我是一个。第一个被打印,kaboom(2(被调用。第一个被打印出来,kaboom(3(被调用。第一个被打印出来,kaboom不再被调用,因为i=3。但是kaboom(3(、kaboom、和kaboom还没有完成,因为它们还需要第二次打印。因为kaboom(3(是最近打开的,它必须先关闭,所以第二个3必须先打印。然后kaboom(2(打印第二个2,最后kaboom的(1(最后打印第二的1。

最新更新