Python: function recursion
definition : The function itself is called directly or indirectly in the process of invoking a function, called a recursive call. Recursive calls can call up to 999 layers.
Base model:
def func (): Print ('fromfunc') func () #直接调用自身 func ():
def func (): Print (' fromfunc') bar () #间接调用自身 def Bar (): Print ("frombar") func () func ()
Although the above two methods are basic models of function recursion, they are often not used directly. Because there is no end condition for a function, it is only equivalent to a dead loop.
Recursion is divided into two important stages: recursion + backtracking
Recursion: The function continuously reduces the problem size until the final termination condition.
Backtracking: After getting the final definite value, return to the last call for processing until the initial layer.
Exercises: Solving age problems, finding out Alex's age
""" Alex He is two years older than Paige. 4 Age (3) + 2 page He is two years older than sun. 3 Age (2) + 2nd days He is two years older than Taibai. 2 Age (1) + 2 Taibai: I am at this year. 1 "" "def age (n): if n = = 1: return @ Else: return Age (n-1) + 2print(age (4)) # 4 here means the scale of the problem is solved.
29
Process Analysis:
""" def Age (4): if n = = 1: return all else: return Age (3) + 2 + 2 + 2 + 2def Age (3): if n = = 1: C8/>return Else: return Age (2) + 2 + 2 + 2 def Age (2): if n = = 1: return else:< C16/>return Age (1) + 2 + 2 def age (1): if n = = 1: return -Else: return Age (0) + 2 c23> "" "
Note in Python:
1. Recursive invocation must have a definite end condition
2, there is no tail recursive optimization in Python, the efficiency of recursive calls is not high
3. The scale of the problem must be reduced when entering the next recursion
Simple Application Scenario:
Remove all elements from the list l=[1,2,[3,[4,[5,[6,[7,[8,9,[10] []]]]]]
def get (L): for inch L: if isinstance (item, list): get (item) #如果元素为一个列表, then recursively call yourself to pass the list to the Get () function and make a recursive call to else : print(item)
Get (L)
Python: function recursion