我正在尝试编写一个函数,该函数接受一个数字列表,并使用递归返回偶数的乘积。我有一个应该如何解决的想法,但是我的问题是我没有获得正确的价值。
这是我的代码
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
任何帮助将不胜感激
答案 0 :(得分:1)
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
答案 1 :(得分:1)
我做了一点修改:
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:])
通常,您遇到一些问题:
答案 2 :(得分:1)
您忘记检查基本情况是否为配对
9
会发生什么情况,最后一个元素 15 处于基本状态 因此,您将 1920 乘以 15 即可得到 28800
顺便说一句,您的版本在python中迅速达到了最大递归深度,更好的版本会把列表分成两半,以便获得log(n)递归深度。
答案 3 :(得分:0)
您需要检查基本情况是否为偶数/奇数,并注意处理空列表。您也可以删除 n 以引用列表中的第一项(如果这是使用它的原因) 下面是处理这些代码的代码:
def prodotto_lista_pari (l):
if len(l) == 1:
if l[0] % 2 ==0:
return l[0]
else:
return 1
if l[0] % 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))