使用递归函数返回最大值偶数

2024-04-19 09:31:48 发布

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

def max_even_list(list):
if len(list) == 1:
    if list[0] % 2 == 0:
        return list[0]
else:
    if list[0] % 2 == 0:
        return max(list[0], max_even_list(list[1:]))
    else:
        return max_even_list(list[1:])

我收到一个错误:TypeError:'>;'在'NoneType'和'int'的实例之间不支持'gt;'

有人能帮我修复这个返回列表中最大偶数的代码吗


Tags: 实例gt列表lenreturnifdef错误
3条回答

您只需关注3种情况:

  1. 当提供的数字列表为空时,返回一些值(在本例中,我选择了0。如果希望函数支持负数,可以使用-infinity
  2. 当列表的开头(xs[0])是偶数时,返回xs[0]max和列表其余部分的max_even
  3. 否则列表的开头不是偶数;返回列表其余部分的max_evenxs[1:]

这只需花费很少的精力就可以将其编码到python程序中

def max_even (xs):
  if not xs:
    return 0
  elif xs[0] % 2 == 0:
    return max(xs[0], max_even(xs[1:]))
  else:
    return max_even(xs[1:])

print(max_even([]))                 # 0
print(max_even([2,1,4,3]))          # 4
print(max_even([2,1,4,3,5,99,8,6])) # 8

len(list)1,但list[0] % 2不是0时,您不返回任何内容。所以如果list的最后一个元素是奇数,那么这个代码就不能工作了。在

如果len(list)1,但list[0] % 2不是0,则可以返回-infinity,如:

def max_even_list(list):
    if len(list) == 1:
        if list[0] % 2 == 0:
            return list[0]
        else:
            return float("-inf")
    else:
        if list[0] % 2 == 0:
            return max(list[0], max_even_list(list[1:]))
        else:
            return max_even_list(list[1:])

FWIW,这是另一种获得最大偶数的方法。在

lst = [1, 2, 2 ,6, 7, 7, 8, 10, 11]

max(filter(lambda x: x%2 == 0, lst))
# 10

参考号:Python ^{}

相关问题 更多 >