如何使用递归求和数组的偶数和奇数 [英] how to sum even and odd numbers of an array using recursion

查看:158
本文介绍了如何使用递归求和数组的偶数和奇数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

推荐答案

在 Python 中,你可以试试这个:

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

注意基本情况如何返回 (0, 0),从那时起,每个连续的递归调用都会根据列表中的当前值递增元组中的正确值,如果它是偶数或奇数.它按预期工作:

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)

这篇关于如何使用递归求和数组的偶数和奇数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆