Article directory
recursive function
1. What is a recursive function
Through the previous study, we know that a function can call other functions.
If a function does not call other functions internally, but itself, this function is a recursive function.
2. The role of recursive functions
As an example, let's calculate the factorial n! = 1 * 2 * 3 * ... * n
Solution 1: Use a loop to do it
def cal(num):
result,i = 1,1
while i <= num:
result *= i
i+= 1
return result
print(cal(3))
Look at the law of factorial
1! = 1
2! = 2 × 1 = 2 × 1!
3! = 3 × 2 × 1 = 3 × 2!
4! = 4 × 3 × 2 × 1 = 4 × 3!
…
n! = n × (n-1)!
Solution 2: Use recursion to achieve
def factorial(num):
result = 1
if num == 1:
return 1
result = num * factorial(num -1)
return result
print(factorial(3))
principle
Exercise: Implement the Fibonacci sequence using recursion. 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
anonymous function
Small anonymous functions can be created using the lambda keyword. Such functions get their name from the omission of the standard step of declaring functions with def.
The syntax of a lambda function consists of only one statement, as follows:
lambda 参数列表: 运算表达式
Examples are as follows:
sum = lambda arg1, arg2: arg1 + arg2
# 调用sum函数
print("Value of total : %d" % sum( 10, 20 ))
print("Value of total : %d" % sum( 20, 20 ))
The output of the above example:
Value of total : 30
Value of total : 40
Lambda functions can accept any number of parameters but can only return the value of an expression
Anonymous functions can execute arbitrary expressions (even print functions), but it is generally believed that expressions should have a calculation result for return.
Python can use lambda when writing some execution scripts, which can accept the process of defining functions, such as writing a simple script management server.
Applications
function passed as parameter
def fun(a, b, opt):
print("a = " % a)
print("b = " % b)
print("result =" % opt(a, b))
add = lambda x,y:x+y
fun(1, 2, add) # 把 add 作为实参传递
The above example output:
a = 1
b = 2
result = 3
practise
have a list
students = [
{
'name': 'zhangsan', 'age': 18, 'score': 92},
{
'name': 'lisi', 'age': 20, 'score': 90},
{
'name': 'wangwu', 'age': 19, 'score': 95},
{
'name': 'jerry', 'age': 21, 'score': 98},
{
'name': 'chris', 'age': 17, 'score': 100},
]
It is required to sort the data in the above list in ascending order according to score.
Built-in functions and classes in Python that take functions as arguments:
function or class name | Function | Parameter Description |
---|---|---|
sorted function | Used to sort an unordered list | The return value of the function parameter specifies which attribute of the element to sort by |
filter class | Used to filter all elements in a list that meet the requirements, and the result is an iterator | The return value of the function parameter specifies the filter condition that the element satisfies |
map class | Perform the same operation on each item in the list, and the result is an iterator | The function parameter is used to specify the operation to be performed on the elements in the list |
reduce function | Performs a compression operation on a sequence to obtain a value. After python3, this method was moved to the functools module | The function parameter is used to specify which way elements are merged |
Advanced case
[Python] Python realizes the word guessing game-challenge your intelligence and luck!
[python] Python tkinter library implements GUI program for weight unit converter
[python] Use Selenium to get (2023 Blog Star) entries
Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition
[Xiaobai must see] Python word cloud generator detailed analysis and code implementation
[Xiaobai must see] Python crawls an example of NBA player data
[Must-see for Xiaobai] Sample code for crawling and saving Himalayan audio using Python
[Xiaobai must see] Python crawler data processing and visualization
[Must-see for Xiaobai] Python crawler program to easily obtain hero skin pictures of King of Glory
[Must-see for Xiaobai] Use Python to generate a personalized list Word document
Geospatial data processing and visualization using geopandas and shapely (.shp)
Use selenium to crawl Maoyan movie list data
Detailed explanation of the principle and implementation of image enhancement algorithm Retinex
Getting Started Guide to Crawlers (8): Write weather data crawler programs for visual analysis
Getting started with crawlers (4): The best way to crawl dynamic web pages using Selenium and API
Getting Started Guide to Crawlers (3): Python network requests and common anti-crawler strategies
Getting started with crawlers (2): How to use regular expressions for data extraction and processing
Getting started with reptiles (1): Learn the basics and skills of reptiles
Python object-oriented programming basics and sample code
MySQL database operation guide: learn how to use Python to add, delete, modify and query operations
Python file operation guide: encoding, reading, writing and exception handling
Selenium Automation Toolset - Complete Guide and Tutorials
Python web crawler basics advanced to actual combat tutorial
Pandas data processing and analysis tutorial: from basics to actual combat
Detailed explanation of commonly used data types and related operations in Python
[Latest in 2023] Detailed Explanation of Six Major Schemes to Improve Index of Classification Model