&[21] Python higher order function

Posted by salih0vicX on Mon, 08 Nov 2021 06:30:44 +0100

Reference:

Pure smile: http://www.ityouknow.com/python.html

Functional programming is now gradually accepted by the majority of development groups. More and more developers begin to use this elegant development mode, and the most important thing for us to use functional programming is to understand:

  1. What are higher order functions?
  2. What are the higher-order functions in Python? How do I use it?

Higher order function concept

In functional programming, we can use functions as freely as variables. A function that takes another function as a parameter is called a higher-order function.

for instance:

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

In the above example, high_func is a higher-order function. The first parameter f is a function, the second parameter arr is an array, and the returned value is a list of all the values in the array calculated 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):
    # Here * * represents the power of n
    return n ** 2


# Use python's own mathematical functions
# Factorial is the factorial of an integer, representing the product of all positive integers less than or equal to the number, and the factorial of 0 is 1 (specified in Mathematics). Namely: n= one × two × three ×...× n. 
print(high_func(factorial, list(range(10))))
# print out: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]

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

Python common high-order functions

Like java, scala and other languages, many of our commonly used high-order functions are basically the same. In fact, there are only a few basic high-order functions that we often use in development, and we can also extend them appropriately based on these functions. Here are some common high-order functions.

map

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

Map the specified sequence according to the provided function and return the mapped sequence. Definition:

map(func, *iterables) --> map object
  • The operations to be performed by each element in the function # sequence can be anonymous functions
  • *iterables # one or more sequences

As in the previous example, high_func function, map function is high_func function higher-order version, you can pass in a function and multiple sequences.

from math import factorial


def square(n):
    return n ** 2


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

# Using custom functions
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 same result is output.

We can also pass in multiple sequences using anonymous functions, 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]

# Incoming 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.

Generally speaking, the reduce function needs to pass in a function with two parameters, and then use this function to traverse the sequence from left to right and generate results. The definition is as follows:

reduce(function, sequence[, initial]) -> value
  • Function # function, the operation to be performed by each element in the sequence, which can be an anonymous function
  • Sequence # the sequence of operations to be performed
  • Initial # optional, initial parameter

Finally, the calculation result of the return function is the same as the initial parameter type

example:

# Notice that the reduce() function is now in the functools package.
from functools import reduce


def add(x, y):  # Add two numbers
    return x + y


sum1 = reduce(add, [1, 2, 3, 4, 5])  # Calculation list and: 1 + 2 + 3 + 4 + 5
sum2 = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])  # Using lambda anonymous functions
print(sum1)  # Output 15
print(sum2)  # Output 15

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

Set initial value:

from functools import reduce

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

print(s)
# print out: number = 12345

It should be noted that the sequence data type should be consistent with 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 unqualified values in the sequence and return an iterator that generates iterable items whose functions (items) are true. If the function is None, the item returned as true. It is defined as follows:

filter(function or None, iterable) --> filter object
  • function or None # filter the functions performed by the operation
  • iterable # the sequence to be filtered

example:

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


# Custom function
filterList = filter(boy, list(range(20)))
print(list(filterList))
# print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# Custom function
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]

As we can see above, all data in the list that cannot be divided 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 the sequence is sorted in ascending order by default. You can also customize the key function to sort. You can also set the reverse parameter to determine whether it is in ascending or descending order. If reverse = True, it is in descending order. The function is defined as follows:

def sorted(iterable: Iterable[_T], *,
           key: Optional[Callable[[_T], Any]] = ...,
           reverse: bool = ...) -> List[_T]: ...
  • iterable # sequence
  • key # can be used to calculate sorting functions.
  • Reverse # collation, reverse = True descending, reverse = False ascending (default).

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))
# The abs function returns the absolute value of x (number).
# 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']

other

This paper briefly introduces the use of several commonly used high-order functions. Of course, there are many high-order functions that we can study, such as zip functions

Topics: Python