我想完成这个:
我认为这可能是:
def fold(f, v, l):
for x in l:
v = f(v, x)
return v
def biggest_even_number(xs):
l = [i for i in xs if i % 2 == 0]
return fold(l)
我知道这是错的,但我不知道如何设置它。如何使用" fold"完成上述任务?功能
答案 0 :(得分:3)
fold
功能看起来不错。你只需要用正确的参数调用它:
def biggest_even_number(xs):
l = [i for i in xs if i % 2 == 0]
return fold(max, float("-inf"), l)
如果它不是作业,你可以使用内置reduce()
基本上做同样的事情:
def biggest_even_number(xs):
l = [i for i in xs if i % 2 == 0]
return reduce(max, l, float("-inf"))
感谢@Steven Rumbalski,对于任何想要找到序列最大值的人来说,您甚至不需要reduce
:
def biggest_even_number(xs):
return max(i for i in xs if i % 2 == 0)
答案 1 :(得分:1)
执行以下操作:
def fold(l):
biggest = float("-inf")
for i in l:
biggest = max(i, biggest)
return biggest
def biggest_even_number(xs):
l = [i for i in xs if i % 2 == 0]
return fold(l)