add and subtract the elements in python

The two list always have the same number of elements, I would like to know how to get the sum and the difference of the elements with the same index using a recursive function in python. The sum and the difference will be in the new list. There's a list for the sum and a list for the difference. I'm still learning python, so I am not that proficient with other functions yet. Here are the two lists.

l1 = [1,2,3]
l2 = [7,8,9]

here's the expected output:

for sum of the elements with the same index: 
l3 = [8,10,12]

for the difference of the elements with the same index:
l4 = [-6,-6,-6]

Upvotes: 0

Views: 210

Answers (2)

The_spider
The_spider

Reputation: 1255

Here's a recursive function able to do that:

def sum(l1,l2):
   if len(l1)==len(l2)==1:
      return [l1[0]+l2[0]]
   else:
      return [l1[0]+l2[0]]+sum(l1[1:],l2[1:])

For the difference, you have to change the first two + signs into -. But of course the iterative approach is a lot easier:

def sum(l1,l2):
    return [l1[x]+l2[x] for x in range(len(l1))]

Note: both of these functions assume that the two lists are of the same length.

Upvotes: 0

I'mahdi
I'mahdi

Reputation: 24049

If you want recursion you can try this:

(if l1 and l2 have same length)

def rec_sum(l1,l2):
    if (len(l1) == 1) and (len(l2) == 1):
        return [l1[0] + l2[0]]
    return [l1[0]+l2[0]] + rec_sum(l1[1:],l2[1:])

def rec_sub(l1,l2):
    if (len(l1) == 1) and (len(l2) == 1):
        return [l1[0] - l2[0]]
    return [l1[0]-l2[0]] + rec_sub(l1[1:],l2[1:])

Output:

>>> l1 = [1,2,3]
>>> l2 = [7,8,9]
>>> rec_sum(l1,l2)
[8,10,12]

>>> rec_sub(l1,l2)
[-6,-6,-6]

But You can use zip like below:

>>> [a+b for a,b in zip(l1,l2)]
[8,10,12]

>>> [a-b for a,b in zip(l1,l2)]
[-6,-6,-6]

Are you wanting recursion?!!!

Upvotes: 1

Related Questions