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"]))
  • 相关阅读:
    Thread的run方法和start方法
    35. Search Insert Position
    Error:(1, 1) java: 非法字符: 'ufeff'
    final修饰的变量是引用不可变,还是对象不可变
    数组与练习
    java反射机制【转】
    Socket
    面向对象的设计原则和设计模式
    多线程
    为什么有时候修改了css文件,页面的样式却没有改变?
  • 原文地址:https://www.cnblogs.com/junejs/p/6915679.html
Copyright © 2011-2022 走看看