我正在尝试编写一个函数,它接受一个数字列表,并使用递归返回偶数的乘积。我知道应该如何解决,但我的问题是我没有得到正确的值
这是我的密码
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
任何帮助都将不胜感激
您忘记检查基本情况是否为配对
最后一个元素15落在基本条件下 因此,将1920乘以15,得到28800
顺便说一句,在python中,您的版本很快达到最大递归深度,更好的版本会将列表一分为二,以便获得log(n)递归深度
对于最后一个元素,返回值时不检查偶数或奇数。所以,你得到了 错误的结果。所以您的输出是lastelement*1920=28800
我稍微修改了一下:
总的来说,您有一些问题:
相关问题 更多 >
编程相关推荐