Python101: 18. Higher Order Functions

post thumb
Python
by Admin/ on 16 Jul 2021

Python101: 18. Higher Order Functions


Functional programming is now gradually accepted by the majority of the development community, more and more developers have begun to use this elegant development model, and we use functional programming is the main need to be clear:

  1. what are higher-order functions (Higher-order Functions)?
  2. what are the higher-order functions in Python? How to use them?

Higher order function concepts


In functional programming, we can freely use functions as if they were variables. A function that receives another function as an argument is called a higher-order function.

As an example.

def high_func(f, arr):
    return [f(x) for x in arr]

In the above example, high_func is a high-order function. The first argument f is a function, the second argument arr is an array, and the returned value is a list of all the values in the array after being computed by the f function. For example.

from math import factorial

def high_func(f, arr):
    return [f(x) for x in arr]

def square(n):
    return n ** 2

# Use python's own math functions
print(high_func(factorial, list(range(10))))
# print out: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]

# Use custom functions
print(high_func(square, list(range(10))))
# print out: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Python Commonly Used Higher Order Functions


As with java, scala and other languages, many of our commonly used higher-order functions are basically the same. In development we often use the most basic higher-order functions are actually a few, and we can also be based on these functions to carry out appropriate extensions, then the following begins to introduce several commonly used higher-order functions.

map

Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.

Mapping the specified sequence according to the provided function, and return the mapped sequence, defined as

map(func, *iterables) --> map object
  • function # the operation to be performed for each element of the sequence, can be an anonymous function
  • *iterables # One or more sequences

As in the previous example of the high_func function, the map function is a higher-order version of the high_func function that can be passed in a function and multiple sequences.

from math import factorial

def square(n):
    return n ** 2

# Use python's own math functions
facMap = map(factorial, list(range(10)))
print(list(facMap))
# print out: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]

# Use custom function
squareMap = map(square, list(range(10)))
print(list(squareMap))
# print out: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

You can see that the output is the same, except that unlike python2.X, which returns the map class, `python3. while the former returns a list directly.

We use anonymous functions, which can also be passed in multiple sequences, as follows

# Use anonymous functions
lamMap = map(lambda x: x * 2, list(range(10)))
print(list(lamMap))
# print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# Pass in multiple sequences
mutiMap = map(lambda x, y: x+y, list(range(10)), list(range(11, 15)))
print(list(mutiMap))
# print out: [11, 13, 15, 17]

reduce

Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.

Roughly speaking, the reduce function is passed a function with two arguments, which is then used to iterate through the sequence from left to right and generate the result, as defined below.

reduce(function, sequence[, initial]) -> value
  • function # function, the operation to be performed on each element of the sequence, can be an anonymous function
  • sequence # The sequence of operations to be performed
  • initial # optional, initial argument

Finally, the result of the function is returned, with the same initial argument type

As a brief example.

# Note that the reduce() function has now been put into the functools package.
from functools import reduce

result = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])

print(result)
# print out 15

We can see that the sequence [1, 2, 3, 4, 5] is cumulated by the anonymous function.

Set initial value.

# Set initial parameters.
s = reduce(lambda x, y: x + y, ['1', '2', '3', '4', '5'], "number = ")

print(s)
# print out: number = 12345

Note that the sequence data type needs to be the same as the initial parameters.

filter

Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.

The filter() function is used to filter the sequence for unqualified values, returning an iterator that generates those iterable items whose function (item) is true. If the function is None, then it returns the items that are true. The definition is as follows.

filter(function or None, iterable) --> filter object
  • function or None # The function that the filter operation performs
  • iterable # The sequence to be filtered

As an example.

def boy(n):
    if n % 2 == 0:
        return True
    return False

# Custom functions
filterList = filter(boy, list(range(20)))

print(list(filterList))
# print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# Custom functions
filterList2 = filter(lambda n: n % 2 == 0, list(range(20)))

print(list(filterList2))
# print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Above we can see that the data in the list that are not divisible by 2 are excluded.

sorted

Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.

The sorted function returns a new list after sorting the sequence in ascending order by default, but you can also customize the key function to sort, and set the reverse parameter to determine whether it is in ascending or descending order, if reverse = True then it is in descending order. The function definition is as follows.

def sorted(iterable: Iterable[_T], *,
           key: Optional[Callable[[_T], Any]] = ... ,
           reverse: bool = ...) -> List[_T]: ...
  • iterable # Sequence
  • key # Sorting function that can be used to compute.
  • reverse # Sorting rule, reverse = True descending, reverse = False ascending (default).

As a simple example.

list01 = [5, -1, 3, 6, -7, 8, -11, 2]
list02 = ['apple', 'pig', 'monkey', 'money']

print(sorted(list01))
# print out: [-11, -7, -1, 2, 3, 5, 6, 8]

print(sorted(list01, key=abs))
# print out: [-1, 2, 3, 5, 6, -7, 8, -11]

# Default ascending order
print(sorted(list02))
# print out: ['apple', 'money', 'monkey', 'pig']

# Descending order
print(sorted(list02, reverse=True))
# print out: ['pig', 'monkey', 'money', 'apple']

# Anonymous function sorting
print(sorted(list02, key=lambda x: len(x), reverse=True))
# print out: ['monkey', 'apple', 'money', 'pig']

Summary


Above we have briefly introduced the use of several common higher-order functions, of course, there are many higher-order functions we can study, such as the zip function, etc. I hope the introduction of this section will be helpful to you.


Reference

https://github.com/JustDoPython/python-100-day/tree/master/day-018

comments powered by Disqus