Skip to main content
 首页 » 编程设计

python之递归技术而不是python中的列表技术

2025年05月04日17softidea

我有一个函数,它的名字是 positive_negative

def positive_negative(list_changes): 
    """ (list of number) -> (number, number) tuple 
 
    list_changes contains a list of float numbers. Return a 2-item 
    tuple where the first item is the sum of the positive numbers in list_changes and 
    the second is the sum of the negative numbers in list_changes. 
 
    >>> positive_negative([0.01, 0.03, -0.02, -0.14, 0, 0, 0.10, -0.01]) 
    (0.14, -0.17) 
    """ 

我可以使用列表技术编写此函数,如下所示:

def positive_negative(list_changes): 
    pos = sum([item for item in list_changes if item > 0.0]) 
    neg = sum ([item for item in list_changes if item < 0.0])  
    return pos, neg 

这是一个很好的解决方案。 现在我的问题是如何使用递归技术来解决相同的功能,我试过下面的代码,但不幸的是有问题。

def positive_negative(list_changes): 
    pos = 0.0 
    neg = 0.0 
    if len(list_changes)== 0: 
        pos =+ 0.0 
        neg =+ 0.0 
        return pos,neg 
    else: 
        if list_changes[0] > 0.0 : 
            pos =+ list_changes[0] 
        else: 
            neg =+ list_changes[0] 
        positive_negative(list_changes[1:]) 
 
 
    return pos,neg  

你能帮我找出我的错误所在以及如何获得正确的递归函数吗。

谢谢

请您参考如下方法:

你的第一个问题是:

pos =+ list_changes[0] 

Python 没有 =+ 运算符。所以,这相当于:

pos = (+list_changes[0]) 

由于 list_changes[0] 是一个数字,而 +n 与 n 对任何数字相同(某些边缘情况除外这在这里无关紧要),你只是每次替换 pos 而不是添加它。

你可能想要这个:

pos += list_changes[0] 

但是您尝试使用 += 的事实是一个更根本的误解。堆栈中的每个 positive_negative 实例都有自己的 pos 和 neg 值。它们从 0.0 开始,然后向它们添加 0.0 或 list_changes[0],然后调用一个不影响它们的函数,然后返回它们。因此,您将最终返回 0.0, list_changes[0] 或 list_changes[0], 0.0;列表中后面出现的任何内容都不会影响结果。


如果你想让递归函数调用添加任何东西,你需要用它的返回值做一些事情。像这样:

def positive_negative(list_changes): 
    if len(list_changes)== 0: 
        return 0.0, 0.0 
    else: 
        pos, neg = positive_negative(list_changes[1:]) 
        if list_changes[0] > 0.0: 
            pos += list_changes[0] 
        else: 
            neg += list_changes[0] 
        return pos, neg 

当然,这个解决方案显然不是尾递归的……但这没关系,因为 Python 无论如何都不做尾递归优化。我认为这是最接近您要实现的目标的解决方案。