i need help creating a recursive function that takes a list/array of numbers and returns a tuple or similar format (a,b) where a is sum of even numbers and b is sum of odd ones...
For example:
input: [1, 2, 3, 4, 5]
return: (6, 9)
i need help creating a recursive function that takes a list/array of numbers and returns a tuple or similar format (a,b) where a is sum of even numbers and b is sum of odd ones...
For example:
input: [1, 2, 3, 4, 5]
return: (6, 9)
In Python, you can try this:
def sum_even_odd(lst):
if not lst: # empty list, we're done
return (0, 0) # counters are zero for empty list
elif lst[0] % 2 == 0: # current value is even
x, y = sum_even_odd(lst[1:]) # recursive call
return (lst[0] + x, y) # increment even counter
else: # current value is odd
x, y = sum_even_odd(lst[1:]) # recursive call
return (x, lst[0] + y) # increment odd counter
Notice how the base case returns (0, 0), and from that point on, each successive recursive call increments the right value in the tuple depending on the current value in the list, if it's even or odd. It works as expected:
sum_even_odd([1, 2, 3, 4, 5])
=> (6, 9)