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