Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading