2017-10-22 41 views
3

我有整,這兩個名單:遞歸增加大於2名的整數列表 - 蟒蛇

A=[1,5,3] 
B=[4,5,9,8] 

我想用遞歸的方法Ø獲得這兩個的總和,和額外的整數只是追加到的結果。 所以我應該得到:

[5,10,12,8] 

這裏是我的功能:

def sum(A,B): 
    a = len(A) 
    b = len(B) 

    if a == 0 : 
     return B 
    elif b == 0 : 
     return A 
    elif a >= b : 

     return A[0] + B[0] + sum(A[1:b],B[1:])+ **list1[(b+1):]** 
    else: 
     return A[0] +B[0] + sum(A[1:],B[1:a])+**list2[(a+1):]** 

對於「****」大膽的一部分,我不知道我是否正確與否, 進而(A [1:b],B [1:])+ A [(b + 1):]

當我運行程序時,我得到了 「return A [0] + B [0] + sum

TypeError: unsupported operand type(s) for +: 'int' and 'list'"

回答

3

您的遞歸案例不正確,您應該退回g列表總和,這意味着您的A[0] + B[0]必須添加爲單個元素列表。基本上,這是你在做什麼:

In [559]: 1 + [123] 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-559-01aa05245fd1> in <module>() 
----> 1 1 + [123] 

TypeError: unsupported operand type(s) for +: 'int' and 'list' 

而且這是你應該做的事情:

In [560]: [1] + [123] 
Out[560]: [1, 123] 

這裏的遞歸情況下的工作版本,小幅整理好。

In [555]: def sum(A, B): 
    ...:  if not len(A): 
    ...:   return B 
    ...:  elif not len(B): 
    ...:   return A 
    ...: 
    ...:  return [A[0] + B[0]] + sum(A[1:], B[1:]) 
    ...: 

In [556]: sum(A, B) 
Out[556]: [5, 10, 12, 8] 

有趣的事實,可以縮短這個函數一行。

In [557]: def sum(A, B): 
    ...:  return A if not len(B) \ 
         else (B if not len(A) \ 
         else ([A[0] + B[0]] + sum(A[1:], B[1:]))) 
    ...: 

In [558]: sum(A, B) 
Out[558]: [5, 10, 12, 8] 
+0

但是當我運行程序還是有這個問題:類型錯誤:不支持的操作數類型(S)爲+: 'int'和'list'。 –

+0

@ J.Done我不認爲你保存了你的文件。 OMG! –

+0

非常感謝 !! –

0

你可以試試這個:

def the_sum(a, b, c): 
    if not a[1:] and b[1:]: 
     c.append(b[0]+a[0]) 
     return the_sum(a, b[1:], c) 
    if not b[1:]: 
     c.append(b[0]) 
     return c 
    if a[1:] and b[1:]: 
     c.append(a[0]+b[0]) 
     return the_sum(a[1:], b[1:], c) 

print(the_sum([1,5,3], [4,5,9,8], [])) 

輸出:

[5, 10, 12, 8] 
0

高清總和(L1,L2,結果=無,ID = 0):

if result is None: 
    result = [] 
if id < min(len(l1), len(l2)): 
    result.append(l1[id] + l2[id]) 
    return sum(l1, l2, result, id + 1) 
else: 
    if len(l1)>len(l2): 
     biggest=l1 
    else: 
     biggest=l2 

    return result+biggest[id:] 

輸入

r=sum([1,5,3,2],[4,5,9,8,15]) 

輸出

[5, 10, 12, 10, 15] 
1

的非遞歸的方式做到這一點:

>>> import itertools 
>>> a = [1,5,3] 
>>> b = [4,5,9,8] 
>>> [sum(i) for i in itertools.zip_longest(a,b,fillvalue=0)] 
[5, 10, 12, 8]