Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of functional programming in Python

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is the method of functional programming in Python". In daily operation, I believe that many people have doubts about the method of functional programming in Python. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "what is the method of functional programming in Python?" Next, please follow the editor to study!

Command paradigm and function paradigm

Let's first compare the two concepts of command paradigm in programming:

In the imperative paradigm, you complete the tasks by giving the computer a sequence of tasks, and then it performs those tasks. It can change the state when executing them. For example, suppose you first set A to 5, and then you change the value of A, and you have a variable, and in this sense, the value inside the variable changes.

In a function paradigm, instead of telling the computer what to do, you tell it what it is. For example, what is the greatest common divisor of a number, what is the product from 1 to n, and so on. Therefore, the variable cannot be changed. Once you set a variable, it stays in this state all the time (note that they are not called variables in pure functional languages). The so-called "side effect" refers to the interaction between the inside and outside of the function (in the most typical case, changing the value of the global variable) to produce results other than the operation. Functional programming emphasizes that there are no "side effects", which means that the function should remain independent, all function is to return a new value, no other behavior, especially not to modify the value of external variables.

Let's look at an example of typical Python code:

A = 3 def some_func (): global an a = 5 some_func () print (a)

The output of this code is 5. In function paradigms, changing variables is a big taboo, and letting functions affect things outside their scope is also a big taboo. The only thing the function can do is calculate and return the result.

Now you might think, "No variables, no side effects?" What's the advantage of that? "

If a function is called twice with the same argument, it must return the same result. Because functions have no side effects, if you are building a computational program, you can speed up the program. If the program knows that func (2) equals 3, we can store it in a table. This prevents the program from running the same function repeatedly if we already know the answer.

Map

To understand map, let's first look at what iterables is. An iterable is anything that can be iterated over. Usually these are lists or arrays, but Python has many different types of iterators. You can even create your own objects that can be iterated using magic methods in Python. Here are two ways:

Class Counter: def _ _ init__ (self, low High): # set class attributes inside the magic method _ init__ # for "inistalise" self.current = low self.high = high def _ _ iter__ (self): # first magic method to make this object iterable return self def _ next__ (self): # second magic method if self.current > self.high: Raise StopIteration else: self.current + = 1 return self.current-1 "Magic method is python built-in method There is no need to actively call, the purpose of existence is to call the python interpreter. Almost every magic method has a corresponding built-in function or operator. When we use these functions or operators on this object, we will call the corresponding magic method in the class, which can be understood as overriding the built-in function. "

The first magic way is to return the iterative object with "_ _ iter__", which is usually used at the beginning of the loop.

If we run:

For c in Counter (3,8): print (c)

Then it will output:

345678

In Python, an iterator is an object that has only one simple magic method. This means that you can access the location in the object, but you cannot traverse the object. Some objects will use the method _ _ next__, as in the second example in the code above.

Now that we know what an iterable object is, let's go back to the map function. The map function allows us to apply a function to each item in the iterable. In general, we want to apply a function to each item in the list, but it is possible for most iterators. Map accepts two inputs, the function to apply and the object that can be iterated:

Map (function, iterable)

Suppose we have a list:

[1, 2, 3, 4, 5]

We want to square every number in the list, so we can write the code like this:

X = [1,2,3,4,5] def square (num): return num*num print (list (map (square, x)

Functions in Python are lazy. If "list ()" is not included in our code, the function will store the definition of the iteration instead of a list. We need to explicitly tell Python to "convert this to a list" so that we can use it.

It's nice to write a normal function like "square (num)" now, but it doesn't look right. Do we have to define a complete function to use it once in map? We can use the lambda (anonymous) function to define a function in map.

Lambda expression

The lambda expression is an one-line function. For example, this lambda expression squares a given number:

Square = lambda x: X * x

Run the program:

> > square (3) 9

Tell Python that this is a lambda function, the input is called x, and what you do after the colon is what you do with the input, and it automatically returns the result.

Now we can simplify the above procedure:

X = [1,2,3,4,5] print (list (map (lambda num: num * num, x)

Reduce

Reduce is a function that turns something that can be iterated into something. Typically, you perform a calculation on a list to reduce it to a number. The Reduce goes like this:

Reduce (function, list)

We can (and usually do) use lambda expressions as functions.

The product of the list is the multiplication of each individual number. To do this, you can:

Product = 1x = [1,2,3,4] for num in x: productproduct = product * num

But with reduce, you can write:

From functools import reduce product = reduce ((lambda x, y: X * y), [1,2,3,4])

Filter

The filter function takes an iterable and filters out everything that is not needed in that iterable.

Filter usually accepts a function and a list. It applies the function to each item in the list and does nothing if the function returns True. If False is returned, the item is deleted from the list.

The syntax is as follows:

Filter (function, list)

Let's take a look at a small example. Without a filter, we will write:

X = range (- 5,5) new_list = [] for num in x: if num < 0: new_list.append (num)

With the filter, it becomes:

X = range (- 5,5) all_less_than_zero = list (filter (lambda num: num < 0, x))

Higher order function

Higher-order functions can take a function as an argument and return a function. A very simple example is as follows:

Def summation (nums): return sum (nums) def action (func, numbers): return func (numbers) print (action (summation, [1,2,3]))

Partial application

Some applications (also known as closures) are a little strange, but very cool. You can call a function without providing all the parameters it needs. Let's look at an example. We want to create a function that takes two parameters, a base and an index, and returns the exponential power of the base, like this:

Def power (base, exponent): return base * * exponent

Now we want a special square function, using the power function to find the square of a number:

Def square (base): return power (base, 2)

It's possible, but what if we want a cube function? Or is it the fourth power of the function? Can we keep writing? Yes, you can. But programmers are lazy. If you repeat the same thing over and over again, it's a sign that there is a faster way to speed up and stop you from repeating it. We can use some of the applications here. Let's look at an example of a square function that uses part of the application:

From functools import partialsquare = partial (power, exponent=2) print (square (2)) at this point, the study of "what is the method of functional programming in Python" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 290

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report