-1

How can I make a recursive function that returns a list of sum of the same index given two lists.?

I want to make it a recursive function only.

for example:

list1 = [1,2,3]
list2 = [2,4,6]

a recursive function will return a new list [3,6,9]

The language should also be python.

Thank you. I just having a hard time figuring it out.

Jakeyyyy
  • 1
  • 5

1 Answers1

0

One approach:

def recursive_sum(a, b):
    
    # if one of the list is empty return the empty list
    if not a or not b:
        return []
    # find the sum of each of the first elements
    val = a[0] + b[0]
    
    # return the concatenation of the first sum with the recursive sum for the rest of the lists 
    return [val, *recursive_sum(a[1:], b[1:])]

Output

[3, 6, 9]

As an alternative suggested by @Stef use:

def recursive_sum(a, b):
    if not a or not b:
        return []
    return [a[0] + b[0]] + recursive_sum(a[1:], b[1:])

The expression:

*recursive_sum(a[1:], b[1:])

is known as unpacking, basically one could said that [1, 2, 3] is equivalent to [1, *[2, 3]], see this link for more information.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • May I ask you a favor? Could you briefly explain what is happening in this line return [a[0] + b[0], *recursive_sum(a[1:], b[1:])] – Jakeyyyy Oct 30 '21 at 11:35
  • especially the multiply sign – Jakeyyyy Oct 30 '21 at 11:36
  • 2
    @Jakeyyyy The asterisk in this context means unpacking, not multiplication. `x = [b, c, d]; y = [a, *x]` is basically the same as `x = [b, c, d]; y = [a, b, c, d]` or `x = [b, c, d]; y = [a] + x`. So `return [a[0] + b[0], *recursive_sum(a[1:], b[1:])]` is the same as `return [a[0] + b[0]] + recursive_sum(a[1:], b[1:])` – Stef Oct 30 '21 at 12:09
  • @Stef for the last part, are you using that the asterisk is equal to the plus sign? since that is the only you changed in the original example. I tried the one that has plus sign but I got an error. – Jakeyyyy Oct 30 '21 at 12:26
  • No, the asterisk is not a plus sign. Note how I changed the brackets, too. The asterisk means unpacking. `[a, *[b, c, d]]` is the same as `[a, b, c, d]`. The result is the same as `[a] + [b, c, d]`. But the asterisk is certainly not a plus sign. – Stef Oct 30 '21 at 12:35
  • @Jakeyyyy Added a few explanations to the answer – Dani Mesejo Oct 30 '21 at 12:40