2017-06-29 33 views
-5

我毫不留情,但毫無結果地試圖理解遞歸如何工作。我有一個教程的例子('用算法和數據結構解決問題')。爲什麼在遞歸發生後,它會再次增加5個「額外的」步驟,並且變量的值會上升?遞歸如何處理Python的作用域?

代碼:

def tree(branchLen): 
    if branchLen >= 5: 
     print(branchLen, '#it is pretty understandable') 
     tree(branchLen-15) 
     print(branchLen, '#stop! Why rising (get backward)?') 

tree(75) 

輸出:

75 #it is pretty understandable 
60 #it is pretty understandable 
45 #it is pretty understandable 
30 #it is pretty understandable 
15 #it is pretty understandable 
15 #stop! Why rising (get backward)? 
30 #stop! Why rising (get backward)? 
45 #stop! Why rising (get backward)? 
60 #stop! Why rising (get backward)? 
75 #stop! Why rising (get backward)? 

的問題已經被編輯過幾次,以提供更多的可讀性(按說明)。問題和答案之間可能存在一些差異。

+0

遞歸剛表示函數調用自己多次,你可以在條件和參數混合 – citizen2077

+0

這是基本的遞歸問題。 Python必須處理函數的所有行。所以一旦它在'tree()'內部調用'tree()'並且完成了第二個'tree()',它就必須返回到第一個,並且結束處理到函數結束。 (PS:你的算法做了5次,因爲有5次調用'tree()') – Nuageux

+0

只要'branchLen> 1'執行遞歸。這意味着最後一個「非常容易理解」的行稱爲「tree(0,t)」。此時您停止遞歸併開始返回,並開始查看第二個輸出。請注意,在之前的遞歸中,您沒有更改'branchLen',因此您會再次看到以前的值。 –

回答

0

您需要了解scope rules in python和遞歸的概念。函數調用流程如下:

樹(75,t) - >樹(60,t) - >樹(45,t) - >樹(30,t) - - > tree(15,t) - > tree(0,t)

;然後if條件失敗,並且範圍返回到函數被調用的函數,即「父函數」。
所以,tree(branchLen-15,t)tree(15, t)範圍執行後,遞歸調用簡單地返回和print(branchLen, '#stop! Why rising (get backward)?')線獲取的tree(15, t)範圍執行,則該函數結束,範圍返回到父功能(其稱爲tree(15, t)),即。 tree(30, t),循環繼續,直到完成第一次遞歸調用的tree(75, t)
理解遞歸的最佳方法是通過堆棧,請參閱here以獲得很好的解釋。

+0

非常感謝!這有助於讓我瞭解以何種方式思考...... –