zoukankan      html  css  js  c++  java
  • 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"]))
  • 相关阅读:
    10-padding(内边距)
    09-盒模型
    07-css的继承性和层叠性
    Python之路【第09章】:Python模块和包的详细说明
    Python之路【第10章】:程序异常处理
    Python之路【第09章】:Python模块
    排序算法—冒泡排序算法
    算法总结
    递归函数与二分法
    练习题
  • 原文地址:https://www.cnblogs.com/junejs/p/6915679.html
Copyright © 2011-2022 走看看