A Brief Analysis of Python Functional Programming Strings and Tuples Function Classification and Higher order Functions

  • 2021-11-30 00:55:18
  • OfStack

Contrast any (), all (), len (), sum (); Study zip (), reversed (), enumerate (); Higher-order function max and min (); map function filter function sorted function with 1 requirement

String in Functional Programming

In functional programming, Python string is often used because it is an immutable data structure.

The string itself is an object with many object methods, which are different from the common sense use of functions, such as the following code


my_str = "xiangpica"
print(my_str.upper())
print(len(my_str.upper()))

Among them len() Function is called prewriting, and my_str.upper() It is called post-writing, which can easily lead to the understanding problem of functional programming, so it is necessary to solve this problem systematically.

If the above code can be modified to len(upper(my_str)) , becomes relatively easy to understand.


#  Type  Text  Yes  str  Alias of 
from typing import Text
my_str = "xiangpica"
def upper(str: Text) -> Text:
    return str.upper()
print(upper(my_str))
print(len(upper(my_str)))

The above code redefines a function with a previous usage upper Used to solve the problem of analogy in functional programming, which often occurs in subsequent code.

Invariant type tuple

In addition to strings, another immutable data type in Python is tuple, which is divided into ordinary tuple and named tuple.

Declaration and Access of Ordinary Tuples

In the previous article, the basic knowledge of tuples has been explained, so you can review it a little, and then enter the study of this article.

Look at the code first, and then judge whether it can be understood.


from typing import Tuple, Text, Callable
LANGUAGE = Tuple[Text, Text, Text]
python: Callable[[LANGUAGE], Text] = lambda languages: languages[1]
items = ("c","python","js")
a = python(items)
print(a)

The above code defines 1 new type LANGUAGE The type is a 1 tuple with 3 elements.

python Type annotation is Callable[[LANGUAGE], Text] That is, its parameters are LANGUAGE Type, and the return value is a string type.

Attention typing The addition of modules will not affect the operation of the program will not report formal errors, only as a type check, to prevent runtime parameters, return value types do not match, developers consult.

In addition to the above, you can also use named tuples.


from collections import  namedtuple
Language = namedtuple("Language",("name1", "name2", "name3"))
l = Language("c", "python", "js")
print(l)
print(l.name1)

Or use it directly typing Modular my_str.upper()0 You can.


from typing import NamedTuple, Text
class Language(NamedTuple):
    name: Text
    description: Text
l = Language("C", "C Language ")
print(l)
print(l.name)
print(l.description)

Classification of functional expressions

There are two major categories of functions:

Scalar function: the return result of the function is 1 value; Set function: The result of a function is an iterable set.

Aggregate functions can also be subdivided:

Reduction/accumulation function: the elements in the set are accumulated and calculated, and finally a value is obtained; Mapping function: apply scalar function to each element of several, and finally get a new set with the same length as the original set; Filter function: Apply scalar function to each element, keep 1 part and get 1 subset.

With the above concepts, the understanding of functional programming can go one step further.

Comparative learning of any (), all (), len () and sum ()

any And all The two functions are reduced functions, and the operation they perform is called Boolean reduction, that is, the elements of a set are reduced to True or False. all All values are required to be True, any As long as one value is True.

len And sum Is also a reduction function, which represents the number of all values in the calculated set and the summary value, respectively.

zip (), reversed (), enumerate ()

zip The function can cross-combine the data between multiple iterable objects or sequences, that is, convert the iterable objects of n elements into n tuples, and then return a generator.

If zip Function has no input parameters, it will return 1 empty list [] .


a = zip()
print(list(a))

reversed The () function is used to change the order of a sequence, that is, to reverse

enumerate Function gets the subscript value of a sequence or iterable object, and converts it into a conceptual description, which maps iterable objects to 2-tuple sequences (with serial numbers). In each 2-tuple sequence, the first element is the subscript value and the second element is the value itself.

Higher order function

Learning Python functional programming can not avoid the learning of higher-order functions, which take functions as parameters or return values as functions.

Functions max and min ()

The above two functions are reduced functions, that is, the input is a set and the output is a single value, and the main purpose is to find the extreme value.

When learning, we can regard the two as ordinary functions, and can also be used for higher-order functions, mainly for the difference of parameter positions.

The simplest usage is:


max_num = max(1, 2, 3, 4)
min_num = min(1, 2, 3, 4)
print(max_num)
print(min_num)

Next is the realization of its high-order function mode, and customize the comparison rules.


#  No. 1 1 Compare string lengths 
max_num = max("a", "abc", "ceda", "aaaaa", key=lambda x: len(x))
min_num = min("a", "abc", "ceda", "aaaaa", key=lambda x: len(x))
print(max_num)
print(min_num)
#  No. 1 2 Compare string lengths 
max_num = max(["a", "abc", "ceda", "aaaaa"], key=lambda x: len(x))
min_num = min(["a", "abc", "ceda", "aaaaa"], key=lambda x: len(x))
print(max_num)
print(min_num)

Of the above code key Is an optional parameter, and the default value is None.

map function

map The function is used to map one set to another, for example, to convert every item in a list of strings to an integer.


data = ["1", "2", "3"]
print(map(int, data))
print(list(map(int, data)))

Code map(int, data) The meaning of is to put int Function acts on data Every 1 item in.

map The first parameter of the function can also be used lambda Instead of.


data = ["1", "2", "3"]
print(map(lambda x: int(x), data))
print(list(map(int, data)))

filter function

filter The function is mainly used to use a * * decision function (predicate function) * * for every 1 element of the set, and finally get a result set that satisfies the decision function. The test code is as follows:


#  Type  Text  Yes  str  Alias of 
from typing import Text
my_str = "xiangpica"
def upper(str: Text) -> Text:
    return str.upper()
print(upper(my_str))
print(len(upper(my_str)))
0

sorted function

upper0 Functions also support higher-order functions key Parameter customization rules.


#  Type  Text  Yes  str  Alias of 
from typing import Text
my_str = "xiangpica"
def upper(str: Text) -> Text:
    return str.upper()
print(upper(my_str))
print(len(upper(my_str)))
1

Different efficiency problems of the same demand

Pass map Functions, generator expressions, and generator functions with iterators are tested with a list of 100 million more data respectively.


#  Type  Text  Yes  str  Alias of 
from typing import Text
my_str = "xiangpica"
def upper(str: Text) -> Text:
    return str.upper()
print(upper(my_str))
print(len(upper(my_str)))
2

The result is that map It's the fastest, so it's finished with it.

The above is a brief analysis of Python functional programming strings and tuples and function classification and higher-order functions in detail, more about Python functional programming information please pay attention to other related articles on this site!


Related articles: