我是 Python 的新手。我正在嘗試執行一個遞回函式,在該函式中我將一個數字串列作為輸入。并且它應該給出子串列的數字(計數器)作為輸出,這些子串列的小計是它們內部數字的結果。我嘗試構建一個遞回函式,當我得出我認為應該是基本情況的結果時,我在counter 中得到了正確的結果(在除錯時,在某些時候)。但是在函式結束時,我的計數器的值只是 0。我知道這是因為退出呼叫,但還沒有真正理解這是如何作業的。我的代碼有什么問題,我該如何糾正?
def count (lista,i,j,accumulatore,counter):
if i > len(lista)-1: return counter
else:
if accumulatore < subtotal :
if j > len(lista)-1:
i =1
count (lista,i,i,0,counter)
else:
accumulatore = lista[j]
j =1
count(lista,i,j,accumulatore,counter)
elif accumulatore == subtotal:
counter =1
if j > len(lista)-1:
i =1
count(lista,i,i,0,counter)
else:
accumulatore =lista[j]
j =1
count(lista,i,j,accumulatore,counter)
else: #accumulator > subtotal
i =1
count(lista,i,i,0,counter)
uj5u.com熱心網友回復:
您的基本問題是代碼中的這些呼叫:
count (lista,i,i,0,counter)
請注意,您正在呼叫, count但除了基本情況外,您不會在任何地方回傳值。因此,當您的else子句結束時,該函式回傳一個 default None。
有點不清楚您期望的輸入和輸出是什么,但您幾乎可以肯定可以簡化此功能。請記住,遞回的基本思想是減小問題的大小,直到遇到某個基本情況,然后使用下一個最小問題輸出的回應來構建您自己的輸出。
因此,累加器通常不是正確部署的遞回解決方案的一部分。
uj5u.com熱心網友回復:
我更正了它,它正在作業!在這種情況下,小計必須在外部定義
def conta (lista,i,j,accumulatore,contatore):
if i > len(lista)-1: return contatore
else:
if accumulatore < subtotal :
if j > len(lista)-1:
return conta (lista,i 1,i 1,0,contatore)
else:
return conta(lista,i,j 1,accumulatore lista[j],contatore)
elif accumulatore == subtotal:
if j > len(lista)-1:
return conta(lista,i 1,i 1,0,contatore 1)
else:
return conta(lista,i,j 1,accumulatore lista[j],contatore 1)
else: #caso in cui accumulatore > subtotale
return conta(lista,i 1,i 1,0,contatore)
編輯:我遇到遞回限制問題并將其轉換為迭代函式
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/326811.html
