Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursive adding two list of integer - python

Tags:

python

list

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'"

like image 309
J.Done Avatar asked Feb 10 '26 19:02

J.Done


2 Answers

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]
like image 128
cs95 Avatar answered Feb 12 '26 10:02

cs95


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]
like image 37
thefifthjack005 Avatar answered Feb 12 '26 10:02

thefifthjack005



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!