![](/img/trans.png)
[英]check Recursively if i can create a sum of given number from a list of numbers
[英]Sum of the numbers in a list starting from the given index, RECURSIVELY
我需要找到解決這個問題的方法。 我寫了一個代碼來計算列表中給定數字的總和,從給定的索引開始。
def recsumlisti(index, alist):
if len(alist) == 0:
return 0
elif index >= len(alist):
return 0
else:
return alist[index] + recsumlisti(index + 1, alist)
這是我擁有的代碼。 當索引為正時它工作得很好,但當索引為負時它行為不端。
例如。 如果參數是recsumlisti(index= -1, alist=[1,2,3,4])而不是僅給出 4 作為輸出,則該函數遍歷所有索引直到最終索引即 index == len(alist ) 並給出總和 4 + 1 + 2 + 3 = 10。測試用例供您參考:
{'index': 2, 'alist': [], 'expected': 0},
{'index': 0, 'alist': [1, 2, 3, 4], 'expected': 10},
{'index': -1, 'alist': [1, 2, 3, 4], 'expected': 4},
我需要改進這個程序的建議,以便它適用於所有的指數,積極的和消極的。 我曾嘗試使用return alist[index] + recsumlisti(index, alist[(index + 1):])
切片方法,但它也會引發錯誤。
如果我的假設是錯誤的,並且我擁有的代碼即使對於負指數也沒有問題,請告訴我。 謝謝!
您可以檢查索引是否為負數,如果是,則將其轉換為相應的正數:
def recsumlisti(index, alist):
if index < 0:
index = index + len(alist)
if len(alist) == 0:
return 0
elif index >= len(alist):
return 0
else:
return alist[index] + recsumlisti(index + 1, alist)
其余代碼相同。 這樣 recsumListi(-1, [1,2,3,4]) 的輸出如預期的那樣是 4
您還可以添加一個三元運算符來檢查索引 +1 是否為 0,並將索引設置為len(alist)
以終止程序(如果是)
def recsumlisti(index, alist):
if len(alist) == 0:
return 0
elif index >= len(alist):
return 0
else:
nextIndex = (index + 1, len(alist))[index + 1 == 0]
return alist[index] + recsumlisti(nextIndex, alist)
其余的代碼再次保持不變
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.