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來實現一樣的功能,只是代碼多幾行而已。app
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"]))