3

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)
1
  • preferably python, but any language is fine :-) Commented Nov 14, 2013 at 21:58

1 Answer 1

6

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Oscar ty vm this was driving me nuts :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.