[Learn python from zero] 30. In-depth understanding of recursive functions and anonymous functions

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

insert image description here

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

[python] Use Selenium and Chrome WebDriver to obtain article information in [Tencent Cloud Studio Practical Training Camp]

Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition

[Fun with Python series [Xiaobai must see] Python multi-threaded crawler: download pictures of emoticon package websites

[Play with Python series] [Must-see for Xiaobai] Use Python to crawl historical data of Shuangseqiu and analyze it visually

[Play with python series] [Must-see for Xiaobai] Use Python crawler technology to obtain proxy IP and save it to a file

[Must-see for Xiaobai] Python image synthesis example using PIL library to realize the synthesis of multiple images by ranks and columns

[Xiaobai must see] Python crawler actual combat downloads pictures of goddesses in batches and saves them locally

[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

[Must-see for Xiaobai] Technical realization of using Python to download League of Legends skin pictures in batches

[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

[Must-see for Xiaobai] Python crawler combat: get pictures from Onmyoji website and save them automatically

Xiaobai must-see series of library management system - sample code for login and registration functions

100 Cases of Xiaobai's Actual Combat: A Complete and Simple Shuangseqiu Lottery Winning Judgment Program, Suitable for Xiaobai Getting Started

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

Introductory Guide to Crawlers (7): Using Selenium and BeautifulSoup to Crawl Douban Movie Top250 Example Explanation [Reptile Xiaobai must watch]

Getting Started Guide to Crawlers (6): Anti-crawlers and advanced skills: IP proxy, User-Agent disguise, Cookie bypass login verification and verification code identification tools

Introductory Guide to Crawlers (5): Distributed Crawlers and Concurrency Control [Implementation methods to improve crawling efficiency and request rationality control]

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

Application of Deep Learning Model in Image Recognition: CIFAR-10 Dataset Practice and Accuracy Analysis

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

Use Python and Selenium to automate crawling#【Dragon Boat Festival Special Call for Papers】Explore the ultimate technology, and the future will be due to you"Zong" #Contributed articles

Python multi-thread and multi-process tutorial: comprehensive analysis, code cases and optimization skills

Selenium Automation Toolset - Complete Guide and Tutorials

Python web crawler basics advanced to actual combat tutorial

Python introductory tutorial: master the basic knowledge of for loop, while loop, string operation, file reading and writing and exception handling

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

Introductory Python programming basics and advanced skills, web development, data analysis, and machine learning and artificial intelligence

Graph prediction results with 4 regression methods: Vector Regression, Random Forest Regression, Linear Regression, K-Nearest Neighbors Regression

Guess you like

Origin blog.csdn.net/qq_33681891/article/details/132295259