我在使用遞回添加陣列的每個元素并生成另一個包含它們總和的串列時遇到問題。
def add(l1,l2,n,counter): # define new user function named add
if c >= n: # base case
# if counter is now greater than the length of the list then return empty array
return []
return l1[c] l2[c], add(l1,l2,n,c 1) # recursion
list1 = [7,8,9] # list 1
list2 = [10,11,12] # list 2
print(add(list1,list2,3,0)) # prompt the output of the add() function
在這種情況下, add() 函式的函式應該回傳一個值為[17,19,21]的串列。相反,它回傳一個值為(17, (19, (21, [ ]))) 的元組。
有人可以告訴我我可以在代碼中改進什么嗎?感謝您提供的任何幫助。
uj5u.com熱心網友回復:
首先,這個問題根本不需要遞回。但是考慮到這是您的問題,您可以做的是回傳一個串列而不是元組。所以而不是這個
return l1[c] l2[c], add(l1,l2,n,c 1) # recursion
你可以退回這個
return [l1[c] l2[c], add(l1,l2,n,c 1)] # recursion
但這會給你 [17, [19, [21, []]]] 作為結果,因為在每次遞回時你都會回傳一個串列。
為了克服這個問題,您應該在每次迭代時傳播回傳的串列。最終代碼如下所示:
return [l1[c] l2[c], *add(l1,l2,n,c 1)] # recursion
* 運算子展開回傳的串列,結果您得到一個串列。
uj5u.com熱心網友回復:
我個人會像下面這樣寫,這不關心串列的長度,甚至允許一個串列比另一個長等等。它檢查兩個串列是否為空,如果是,則回傳一個空串列,否則它從每個串列中獲取第一個值,如果串列沒有更多值,則默認為 0。然后使用每個串列中的剩余值再次呼叫該函式。等等。
def add(l1, l2): # define new user function named add
if len(l1) == 0 and len(l2) == 0:
return []
n1 = l1[0] if l1 else 0
n2 = l2[0] if l2 else 0
t = n1 n2
return [t] add(l1[1:], l2[1:]) # recursion
list1 = [7, 8, 9, 50] # list 1
list2 = [10, 11, 12] # list 2
print(add(list1, list2))
輸出
[17, 19, 21, 50]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/356404.html
上一篇:Python遞回更新陣列
