Reputation: 89
I have these two lists of integer:
A=[1,5,3]
B=[4,5,9,8]
I want to use the recursive method o get the sum of these two , and extra integer just appends to the result. So I should get:
[5,10,12,8]
Here are my functions:
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):]**
For the "****" bold part, i am not sure whether i am correct or not, and furthermore, when i ran the program, i got "return A[0] + B[0] + sum(A[1:b],B[1:])+A[(b+1):]
TypeError: unsupported operand type(s) for +: 'int' and 'list'"
Upvotes: 3
Views: 1499
Reputation: 638
def sum(l1, l2, result = None, 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:]
Input
r=sum([1,5,3,2],[4,5,9,8,15])
Output
[5, 10, 12, 10, 15]
Upvotes: 2
Reputation: 174624
The non-recursive way to do this:
>>> 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]
Upvotes: 1
Reputation: 71451
You can try this:
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], []))
Output:
[5, 10, 12, 8]
Upvotes: 0
Reputation: 402443
Your recursive case isn't correct. You should be returning a list sum, meaning your A[0] + B[0]
must be added as a single element list. Basically, this is what you're doing:
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'
And this is what you should be doing:
In [560]: [1] + [123]
Out[560]: [1, 123]
Here's a working version of the recursive case, slightly tidied up.
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]
Fun fact, you can shorten this function to a single line.
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]
Upvotes: 3