current position:Home>Talk about ordinary functions and higher-order functions in Python
Talk about ordinary functions and higher-order functions in Python
2022-01-30 19:25:24 【Lei Xuewei】
Little knowledge , Great challenge ! This article is participating in 「 A programmer must have a little knowledge 」 Creative activities
This article has participated in 「 Digging force Star Program 」 , Win a creative gift bag , Challenge creation incentive fund .
ceremonial Python Column No 25 piece , Classmate, stop , Don't miss this from 0 The beginning of the article !
Today, the school committee is writing code , Wrote a lot of , Let's talk again this time python The function in
What is a function
Every language has functions , Even people use Excel There are also functions , We used to learn many kinds of functions in Mathematics .
Python The same goes for functions in .
def f(x):
print(" Parameter is :",x)
return x
Copy code
Functions here y = f(x), In mathematics, it is expressed as a slope of 1 The straight line of .
Nested calls to functions
def z(x):
pass
def f(x):
print(" Parameter is :",x)
return z(x)
Copy code
like this , We are f(x) Called in z(x) function ( It's used here pass keyword , Implementation without writing , For display purposes only )
Can we not define z(x) Just define a function and call other functions ?
It's like realizing the square of a number , Functional ‘ square ’, About that .
Higher order function
def f(z):
return z()
Copy code
This is the higher order function ,f The function needs an external parameter , This parameter must be a function .
In the use of f(z) When , We can't give one f(2), f(3) So the value of the . Or there's a function like d(x) Returns a result that is not a function value , We can't call... Like this :f(d(1)).
The school committee has prepared the following code , From a simple function to a higher-order function :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/10/24 11:39 Afternoon
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: Lei Xuewei
# @XueWeiTag: CodingDemo
# @File : func_demo2.py
# @Project : hello
def f1(x):
return x
def f2(x, z=100):
return x + z / 10
def f3(x, z=100, *dynamic_args):
sum = 0
for arg in dynamic_args:
sum += arg
return x + z / 10 + sum / 10000.0
def dummy_sum(*args):
return 0
def f4(x, z=100, sum_func=dummy_sum):
return x + z / 10 + sum_func() / 10000.0
print(f1(100))
print(f2(100, z=50))
print(f3(100, 50, 4, 5, 6))
def sum_g(*dynamic_args):
def sum_func():
sum = 0
for arg in dynamic_args:
sum += arg
return sum
return sum_func
print(f4(100, 50, sum_g(4, 5, 6)))
Copy code
Here we see the function f1, f2, f3, f4.
Add a point of knowledge : *dynamic_args It's a dynamic parameter , Parameters of indefinite length .
That is to say f3 Clearly stated 3 Parameters , Finally, we gave 5 Parameters .
here f3 Think x=100, z=50, dynamic_args = [4, 5, 6]
Let's look at the output first :
f3 and f4 It looks the same .
But the nature is completely different , The reader can think for ten seconds .
f4 Very elastic , Because the third parameter is .
Higher order functions can help us calculate ‘ Dimension reduction ’( Three dimensional becomes two-dimensional , Two to one ).
Let's think about calculating the area of a circle and a square
I believe you can write the following two functions with your eyes closed :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/10/24 11:39 Afternoon
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: Lei Xuewei
# @XueWeiTag: CodingDemo
# @File : func_demo2.py
# @Project : hello
import math
def circle_area(r):
return math.pi * r * r
def rectangle_area(a, b):
return a * b
Copy code
This is the mathematical formula for the circular area :
This is the mathematical formula of rectangular area :
We see that there are 1 Parameters , Some have two ways to become higher-order functions ?
Readers can think for a while .
Here is the code :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/10/24 11:39 Afternoon
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: Lei Xuewei
# @XueWeiTag: CodingDemo
# @File : func_demo2.py
# @Project : hello
import math
def circle_area(r):
return math.pi * r * r
def rectangle_area(a, b):
return a * b
def area(x, linear, factor):
return x * linear(x, factor)
def relation(x, factor):
return x * factor
a = 10
b = 20
print(" Rectangular area :", rectangle_area(a, b))
print(" Circular area :", circle_area(a))
print(" Rectangular area :", area(a, relation, factor=b / a))
print(" Circular area :", area(a, relation, factor=math.pi))
Copy code
The results are as follows :
This is just a solution .
You can see that from the code , We regard both a circle and a rectangle as a reference ( radius / One side ) The square of , Multiply by a factor .
below , Let's add... To the square area calculation :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/10/24 11:39 Afternoon
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: Lei Xuewei
# @XueWeiTag: CodingDemo
# @File : func_demo2.py
# @Project : hello
import math
def circle_area(r):
return math.pi * r * r
def square_area(a):
return a * a
def rectangle_area(a, b):
return a * b
def area(x, linear, factor):
return x * linear(x, factor)
def relation(x, factor):
return x * factor
a = 10
b = 20
print(" Rectangular area :", rectangle_area(a, b))
print(" Square area :", square_area(a))
print(" Circular area :", circle_area(a))
print(" Rectangular area :", area(a, relation, factor=b / a))
print(" Square area :", area(a, relation, factor=1))
print(" Circular area :", area(a, relation, factor=math.pi))
Copy code
The result of the above code execution is as follows :
This is the magic of higher-order functions , Let's think from the perspective of a square .
Just one area Functions and relation function , Neither of these functions need to be modified , Just give one factor( Empirical factor ), You can quickly calculate its area .
Why higher-order functions can reduce the dimension
A function of the area calculated from the distance above , We can see how to calculate circles and rectangles , Can be regarded as a one-dimensional function .
Then take the square area as the reference , Quickly estimate the area of circles and squares .
Of course, the radius is used to calculate the circular area above , It's not intuitive enough , Readers can change it to diameter , such factor = math.pi / 4.
This will be more appropriate in feeling .
summary
In addition to the functions described above , Parameters , Higher order function . We can also use lambda function :
lambda Parameters 1, Parameters 2,..., The first n Parameters : Calculation expression
Copy code
The function above relation Functions can be omitted without writing , Finally, the call is changed to :
print(" Rectangular area :", area(a, lambda x, f: x * f, factor=b / a))
print(" Square area :", area(a, lambda x, f: x * f, factor=1))
print(" Circular area :", area(a, lambda x, f: x * f, factor=math.pi))
Copy code
by the way , like Python Friend, , Please pay attention to Python Basic column or Python From getting started to mastering the big column
Continuous learning and continuous development , I'm Lei Xuewei !
Programming is fun , The key is to understand the technology thoroughly .
Welcome to wechat , Like support collection !
copyright notice
author[Lei Xuewei],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301925206689.html
The sidebar is recommended
- Exploratory data analysis (EDA) in Python using SQL and Seaborn (SNS).
- Turn audio into shareable video with Python and ffmpeg
- Using rbind in python (equivalent to R)
- Pandas: how to create an empty data frame with column names
- Talk about quantifying investment using Python
- Python, image restoration in opencv - CV2 inpaint
- Python notes (14): advanced technologies such as object-oriented programming
- Python notes (13): operations such as object-oriented programming
- Python notes (12): inheritance such as object-oriented programming
- Chapter 2: Fundamentals of python-5 Boolean
guess what you like
-
Python notes (11): encapsulation such as object-oriented programming
-
Python notes (10): concepts such as object-oriented programming
-
Gradient lifting method and its implementation in Python
-
Van * Python | simple crawling of a site course
-
Chapter 1 preliminary knowledge of pandas (list derivation and conditional assignment, anonymous function and map method, zip object and enumerate method, NP basis)
-
Nanny tutorial! Build VIM into an IDE (Python)
-
Fourier transform of Python OpenCV image processing, lesson 52
-
Introduction to python (III) network request and analysis
-
China Merchants Bank credit card number recognition project (Part I), python OpenCV image processing journey, Part 53
-
Introduction to python (IV) dynamic web page analysis and capture
Random recommended
- Python practice - capture 58 rental information and store it in MySQL database
- leetcode 119. Pascal's Triangle II(python)
- leetcode 31. Next Permutation(python)
- [algorithm learning] 807 Maintain the city skyline (Java / C / C + + / Python / go / trust)
- The rich woman's best friend asked me to write her a Taobao double 11 rush purchase script in Python, which can only be arranged
- Glom module of Python data analysis module (1)
- Python crawler actual combat, requests module, python realizes the full set of skin to capture the glory of the king
- Summarize some common mistakes of novices in Python development
- Python libraries you may not know
- [Python crawler] detailed explanation of selenium from introduction to actual combat [2]
- This is what you should do to quickly create a list in Python
- On the 55th day of the journey, python opencv perspective transformation front knowledge contour coordinate points
- Python OpenCV image area contour mark, which can be used to frame various small notes
- How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04
- Initial Python tuple
- Introduction to Python urllib module
- Advanced Python Basics: from functions to advanced magic methods
- Python Foundation: data structure summary
- Python Basics: from variables to exception handling
- Python notes (22): time module and calendar module
- Python notes (20): built in high-order functions
- Python notes (17): closure
- Python notes (18): decorator
- Python notes (16): generators and iterators
- Python notes (XV): List derivation
- Python tells you what timing attacks are
- Python -- file and exception
- [Python from introduction to mastery] (IV) what are the built-in data types of Python? Figure out
- Python code to scan code to pay attention to official account login
- [algorithm learning] 1221 Split balanced string (Java / C / C + + / Python / go / trust)
- Python notes (22): errors and exceptions
- Python has been hidden for ten years, and once image recognition is heard all over the world
- Python notes (21): random number module
- Python notes (19): anonymous functions
- Use Python and OpenCV to calculate and draw two-dimensional histogram
- Python, Hough circle transformation in opencv
- A library for reading and writing markdown in Python: mdutils
- Datetime of Python time operation (Part I)
- The most useful decorator in the python standard library
- Python iterators and generators