我很抱歉在這里問了這樣一個微不足道的初學者問題,但每次我在理解遞回的情況下向前走兩步,我似乎都在向后走三步。我不明白為什么這個在陣列中存盤 n 個數字的簡單代碼會出現空白。我可以通過注釋部分讓它作業,但在不起作用的頂部,我假設 y 和 x 將在堆疊幀展開時填充,并且陣列應該回傳一個數字串列。有人能解釋一下我的假設有什么問題嗎?如何可視化遞回以及如何在遞回進行呼叫以及回傳值傳播回主函式時使用結果?
def nums(n,x):
if n == 0:
return n
else:
y=(nums(n-1,x))
x.append(y)
return x # output was all blanks
# nums(n-1,x)
# x.append(n)
return x # This works
x=[]
print(nums(7,x))
uj5u.com熱心網友回復:
我們通常用遞回來教這個的方法是用不同的值進行堆疊跟蹤來演示流程。
nums(0, []) => 0 # n.b., this is a scalar, not an array based on the code above
nums(1, []) =>
y = (nums(0, x)) => 0 (from above) # n.b., this might be interpreted as a tuple since we have surrounded it with parentheses, best to avoid enclosing parentheses if you don't need them
x.append(y) => x = [ 0 ]
return x => [ 0 ]
現在我們變得棘手了,因為 x 是 a list,所以它通過參考傳遞并回傳。因此,對于 n > 1,我們會將 x 附加到自身,這將導致問題
nums(2, []) =>
y = nums(1, []) =>
y = nums(0, []) =>
y = 0
x = [ 0 ]
=> [ 0 ]
x.append(x = [ 0 ]) => yields a circular reference since we are appending x to itself
您可能打算使用堆疊展開語意,但如果這是我們的意圖,我們需要新的串列作為區域變數,因為我們進行遞回:
def nums(n):
if n == 0:
return [ 0 ]
return [ n ] nums(n - 1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/475135.html
下一篇:無法理解如何為每個步驟存盤值
