Home > Mobile >  Is is possible to use recursion to find the sum of each elements of an array using Python?
Is is possible to use recursion to find the sum of each elements of an array using Python?

Time:11-09

I am having a problem using recursions to add each element of an array and produce another list that contains their sum.

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

The function of the add() function, in this case, should return a list with the value of [17,19,21]. Instead, it is returning a tuple with the value of (17, (19, (21, [ ]))).

Can someone tell me what I can improve in my code? I appreciate any help you can provide.

CodePudding user response:

First of all, this problem does not require recursion at all. But considering that is your question, what you can do is you can return a list instead of a tuple. So instead of this

return l1[c] l2[c], add(l1,l2,n,c 1) # recursion

You can return this

return [l1[c] l2[c], add(l1,l2,n,c 1)] # recursion

But this will give you [17, [19, [21, []]]] as a result, because at each recursion you are returning a list.

To overcome this, you should spread the returned list at each iteration. The final code looks like:

return [l1[c] l2[c], *add(l1,l2,n,c 1)] # recursion

The * operator spreads the returned list, and you get a single list as a result.

CodePudding user response:

Personally I would write it like below, this doesn't care about the lengths of the lists and even allows for one list to be longer than the other etc. It checks if both lists are empty and if so it returns an empty list, otherwise it gets the first value out of each list, or default to 0 if the list has no more values. it then calls the function again with the remaining values in each list. and so on.

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))

OUTPUT

[17, 19, 21, 50]
  • Related