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  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

? 