我需要帮助创建一个递归函数,该函数接受数字列表/数组并返回元组或类似格式(a,b) where a是偶数之和并且b是奇数之和...
例如:
input: [1, 2, 3, 4, 5]
return: (6, 9)
在Python中,你可以尝试这个:
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