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

最新文章

  1. BZOJ1853 [Scoi2010]幸运数字
  2. [设计模式] javascript 之 桥接模式
  3. php实用函数整理
  4. js经验1
  5. 数据库sql整体整理
  6. Common Lisp 编译器IDE环境搭建
  7. inet_addr() inet_ntoa() inet_pton inet_ntop sockaddr_in
  8. Android N安装apk报错:android.os.FileUriExposedException
  9. Google官方MVP模式示例项目解析 todo-mvp
  10. TypeScript入门知识一(字符串特性)
  11. Touch Handling in Cocos2D 3.x(二)
  12. openhtmltopdf 支持自定义字体、粗体
  13. LeetCode: Gas Station 解题报告
  14. C# Http方式下载文件到本地类改进版
  15. 解决WinForm(C#)中MDI子窗体最大化跑偏的问题
  16. Spring DI
  17. Buildroot make网卡interfaces文件被修改
  18. Controller类的方法上的RequestMapping一定要写在Controller类里吗?
  19. Access denied for user 'xxx'@'localhost' 问题的解决方法
  20. Solidworks如何保存为网页可以浏览的3D格式

热门文章

  1. poj 1469 COURSES 解题报告
  2. hdu 超级楼梯 解题报告
  3. BZOJ_2726_[SDOI2012]任务安排_斜率优化+二分
  4. Watir: Watir-WebDriver对打开的浏览器attach操作
  5. Android之APP模块编译
  6. Spring 3.1新特性之一:使用Spring Profile和Mybatis进行多个数据源(H2和Mysql)的切换
  7. 常用的Ant风格书写
  8. android调用第三方库——第二篇——编写库android程序直接调用第三方库libhello.so (转载)
  9. 家庭wifi,如何组网最合适
  10. Gradle技术之四 - Gradle的Task详解