Summary of recursive function knowledge in Python basic learning

Time:2021-12-6

1、 Notes on the use of recursive functions

Recursive functions must write termination conditions, otherwise infinite recursion will occur. (dead cycle)

2、 Efficiency of recursion

  • The recursive efficiency is not high. Too many recursive levels will lead to stack overflow.
  • Recursion is not recommended in Python.

3、 Recursive function introduction

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
"""
Use the code loop to output the story: Once upon a time, there was a mountain and a temple in the mountain
"""
#------------ while loop (ignore the dead loop temporarily)---------------
while true:
    print("Once upon a time, there was a mountain and a temple in the mountain...")
 
#---------------- call the implementation in the while loop by defining a method (ignoring the dead loop temporarily)---------------
def func_story():
    print("Once upon a time, there was a mountain and a temple in the mountain...")
 
while true:
    func_story()
 
#---------------- use recursive methods to implement loops---------------
def story():
    print("Once upon a time, there was a mountain and a temple in the mountain...")
    story()
 
story()
#Error: recursion error: maximum recursion depth exceeded while calling a python object

4、 Depth of recursion

This is extended to a maximum depth of recursion.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import sys
 
#Gets the maximum recursion depth
res = sys.getrecursionlimit()
print(res) #Output: 1000
 
#Maximum recursion depth:
def func(n):
    print(n)
    n += 1
    func(n)
 
 
func(1#Python 3 stops printing when it prints to 998

We can set the maximum depth of recursion. However, the maximum depth that can be reached is also related to the computer configuration:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import sys
 
#Sets the depth of recursion
sys.setrecursionlimit(10000)
 
 
#Maximum recursion depth:
def func(n):
    print(n)
    n += 1
    func(n)
 
 
func(1#Python 3 stops printing when it prints to 3221

5、 Resolve recursion constraints through caching

Solve the problem of maximum recursion limit by caching:

  • Python’s functools module provides the operation of many high-order functions.
  • lru_ Cache: a cache function decorator, which can cache function call results with the same parameters and save high overhead or I / O function call time.
  • By LRU_ Cache decorated recursive function

Summary of recursive function knowledge in Python basic learning
Summary of recursive function knowledge in Python basic learning

6、 Examples of using recursive functions

Example 1 of recursive function:

?
1
2
3
4
5
6
7
8
9
10
11
# 18 20 22 24
def age(n):
    if n == 1:
        return 18
    else:
        return age(n-1) + 2
 
print(age(1)) #Output: 18
print(age(2)) #Output: 20
print(age(3)) #Output: 22
print(age(4)) #Output: 24

Recursive function example 2: print three-level menu

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#We have such a three-level menu
menu = {
    "Function test": {
        "Use case management": {
            "Add use case": {},
            "Delete use case": {},
            "Copy use case": {}
        },
        "Element management": {
            Add element: {},
            Delete element: {},
            Copy element: {}
        },
    },
    "Interface test": {
        "API management": {
            "Add API": {},
            "Delete API": {},
            "Replication API": {}
        },
        "Environmental management": {
            "Add environment": {},
            "Delete environment": {},
            "Replication environment": {}
        },
    },
}
 
def query_menu(menu:dict):
    """
    First level query menu information
    :return:
    """
    #User input Q exit
    while true:
        for k in menu:print(f"Current menu: {K}")
        key = input(">>>").strip()
        if key == "q": return key
        elif key in menu.keys() and menu[key]:
            res = query_menu(menu[key])
            if res == "q":
                return "q"
 
query_menu(menu)

Output results:

Summary of recursive function knowledge in Python basic learning

This is the end of this article on the summary of recursive function knowledge of Python basic learning. For more information about Python recursive function, please search the previous articles of developepper or continue to browse the relevant articles below. I hope you will support developepper in the future!