3

我需要帮助创建一个递归函数,该函数接受一个数字列表/数组并返回一个元组或类似格式(a,b),其中a偶数之和b是奇数之和......例如:

input: [1, 2, 3, 4, 5] 

return: (6, 9)
4

1 回答 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)
于 2013-11-14T22:02:01.190 回答