首页 > 代码库 > 46 Simple Python Exercises-Higher order functions and list comprehensions

46 Simple Python Exercises-Higher order functions and list comprehensions

26. Using the higher order function reduce(), write a function max_in_list() that takes a list of numbers and returns the largest one. Then ask yourself: why define and call a new function, when I can just as well call the reduce() function directly?

from functools import reduce

def max_in_list(num_list):
    def max_of_two(a, b):
        return a if a >= b else b
    biggest = float("-inf")
    return reduce(max_of_two, num_list, biggest)

print(max_in_list([100,-2,3,4,5]))

 

46 Simple Python Exercises-Higher order functions and list comprehensions