我必須撰寫一個代碼,利用遞回對串列中的數字求和,直到索引等于預先確定的整數值。IE
list = [1,4,8,9]
int = 2
sum = 1 4 (index 0 and 1)
到目前為止,下面是我的代碼,但是我在第一個 if 陳述句的邏輯上苦苦掙扎,因此它不起作用。我收到錯誤 'int' object has no attribute 'index' 任何幫助將不勝感激(PS 對編碼非常陌生 - 如果我的代碼不是最好的,請見諒)!
# Sum Recursion
def Arecursion(Alist,index):
if index > 0: # if the index point in the list matches the integer return the sum
return Alist[index] Arecursion(Alist,index-1)
else:
return 0
list_test = [1,4,6,7,10]
int_test = 2
print(Arecursion(list_test,int_test))
uj5u.com熱心網友回復:
你讓它變得更復雜,你需要。你只需要一個基本情況——當前索引太大,以及遞回——當前索引的值加上其余部分:
def sum_rec(l,max_index, i=0):
if i >= max_index or i >= len(l): # base case
return 0
return l[i] sum_rec(l, max_index, i 1) # recursion
sum_rec([1, 2, 3, 4], 0)
# 0
sum_rec([1, 2, 3, 4], 1)
# 1
sum_rec([1, 2, 3, 4], 2)
# 3
sum_rec([1, 2, 3, 4], 3)
#6
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/474872.html
上一篇:如何呼叫函式末尾回傳的變數?
