如何使用递归查找列表中偶数的乘积?

2024-09-26 22:49:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个函数,它接受一个数字列表,并使用递归返回偶数的乘积。我知道应该如何解决,但我的问题是我没有得到正确的值

这是我的密码

def prodotto_lista_pari (l):
    
    if len(l) == 1:
        return l[0]
    n = 0
    if l[n] % 2 == 0:
        return prodotto_lista_pari([l[0]]) * prodotto_lista_pari(l[1:])
    return prodotto_lista_pari(l[1:])


l = [2, 1, 5, 12, 80, 77, 15]

the output should be 1920
the ouput i get instead is 28800

任何帮助都将不胜感激


Tags: the函数密码列表outputlenreturnif
3条回答

您忘记检查基本情况是否为配对

def prodotto_lista_pari (l):
    if len(l) == 1:
        if l[0] % 2 == 0:
            return l[0]
        return 1
    n = 0
    if l[n] % 2 == 0:
        return prodotto_lista_pari([l[0]]) * prodotto_lista_pari(l[1:])

    return prodotto_lista_pari(l[1:])

l = [2, 1, 5, 12, 80, 77, 15]
print(prodotto_lista_pari(l))
>> 1920

最后一个元素15落在基本条件下 因此,将1920乘以15,得到28800

顺便说一句,在python中,您的版本很快达到最大递归深度,更好的版本会将列表一分为二,以便获得log(n)递归深度

def prodotto_lista_pari (l):
    
    if len(l) == 1:
        if l[0] % 2==0:
            return l[0]
        else:
            return 1
    n = 0
    if l[n] % 2 == 0:
        return prodotto_lista_pari([l[0]]) * prodotto_lista_pari(l[1:])

    return prodotto_lista_pari(l[1:])

l = [2, 1, 5, 12, 80, 77, 15]

对于最后一个元素,返回值时不检查偶数或奇数。所以,你得到了 错误的结果。所以您的输出是lastelement*1920=28800

我稍微修改了一下:

def prodotto_lista_pari(l):
    if not l:  # Checks if list is empty
        return 1
    n = l[0]
    if n % 2 == 0:
        return n*prodotto_lista_pari(l[1:])
    return prodotto_lista_pari(l[1:])

总的来说,您有一些问题:

  • 您没有检查最后一项是否为偶数
  • 你总是无缘无故地多打一个电话
  • 您有一个似乎未使用的变量n。正如您所看到的,我使用它来缓存第一项

相关问题 更多 >

    热门问题