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]))

【june】reduce和map是函数式编程最明显的特点,也是两个相反的过程。这个函数在真实的编程中用的并不多,完全可以用for来实现同样的功能,只是代码多几行而已。

 

27. Write a program that maps a list of words into a list of integers representing the lengths of the correponding words. Write it in three different ways: 1) using a for-loop, 2) using the higher order function map(), and 3) using list comprehensions.

# 1) use loop
def words_to_length(words):
    lens = []
    for word in words:
        lens.append(len(word))
    return lens

# 2) use map
def words_to_length(words):
    return list(map(len, words))

# 3) use list comprehension
def words_to_length(words):
    return [len(word) for word in words]

words_to_length(["i", "am", "newbie"]) 

 

28. Write a function find_longest_word() that takes a list of words and returns the length of the longest one. Use only higher order functions.

from functools import reduce

def find_longest_word(words):
    return reduce(max, map(len, words))

print(find_longest_word(["a", "student", "good"]))

 

转载于:https://www.cnblogs.com/junejs/p/6915679.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值