[英]Convert recursive function to for and while loop [Python]
我具有以下功能:
h(0) = 0
h(1) = 3
h(n) = h(n-1) + 2 * h(n-2), for n>= 2
我需要將其轉換為for循環,while循環和遞歸函數。 我已經弄清楚了遞歸函數,但是我似乎無法輸出正確的答案。 我在for循環中的嘗試是這樣的:
def hForLoop(n):
sum = 3
for i in range(2, n):
sum = sum + ((i - 1) + 2 * (i - 2))
return sum
我似乎無法弄清楚為什么我輸出了錯誤的答案。 一些見解將非常有用,我將不勝感激。
問題在您的for循環中,您可以通過((i - 1) + 2 * (i - 2))
增加sum
。
如果您了解原始函數,那么它實際上應該是與先前計算的值分別存儲在h(i-1)
和h(i-2)
處的增量sum
。
這是我對for循環函數的修復:
def hForLoop(n):
sum = [0,3]
for i in range(2, n+1):
sum.append((sum[i - 1]) + 2 * (sum[i - 2]))
return sum[n]
您需要為循環的下一次迭代存儲h(n-1)
和h(n-2)
的中間值,在其中您可以使用這些值來計算下一個h(n)
。
def hLoop(n):
# initally [h(2), h(1), h(0)]
h = [3, 3, 0]
# And in the following: [ h(i), h(i-1), h(i-2)]
for i in range(2, n + 1):
# calculate h(i)
h[0] = h[1] + 2 * h[2]
# move 'index' forward, h(n-1) becomes h(n-2), h(n-1) becomes h(n-0)
h[2] = h[1]
h[1] = h[0]
return h[0]
以下是僅存儲系列中最后兩個值的版本:
def hForLoop(n):
prev, cur = 0, 3
for i in range(2, n + 1):
cur, prev = cur + prev * 2, cur
return cur
具有原始功能:
h(0) = 0
h(1) = 3
h(n) = h(n-1) + 2 * h(n-2), for n>= 2
您的實際代碼是:
h(0) = 0
h(1) = 3
h(n) = Σ((n-1) + 2 * (n-2)), for n>= 2
看到不同?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.