Function recursion
That is, the function calls itself directly or indirectly in the call stage.
supplement
# View the upper recursion limit supported by the function import sys print(sys.getrecursionlimit()) # Not very accurate # Generally, 1000 is returned. sys.setrecursionlimit(2000) # If you want to change the upper limit of recursion, you can use this method to change it to 2000.
Functions should not be recursed indefinitely
Recursion is divided into two stages
1. Backtracking: it is a repeated process, which must be based on the fact that the complexity of each repeated problem should be reduced.
To have a final end condition
2. Recursion: the process of backward derivation
age(n) = age(n-1) + 2 # n > 1 age(1) = 18 # n = 1 # Recursive function def age(n): if n == 1: # There must be an end condition return 18 return age(n-1) + 2 res = age(5) print(res) # 26
l = [1,[2,[3,[4,[5,[6,[7,[8,[9,[10,[11,[12,[13,]]]]]]]]]]]]] # Print the numbers in the list in turn(The number of layers of the loop is something you have to think about) def get_num(l): for i in l: if type(i) is int: print(i) else: get_num(i) # Here, you can call yourself recursively to achieve the purpose of loop. get_num(l)
dichotomy
Algorithm: an efficient way to solve problems
Result with target Gu num = 66l = [1,2,4,65,76,123,156,157,235,256,278,301,324,786] target_num = 66 # These are the initial parameters def get_num(l,target_num): print(l) # With this sentence, every time you search or split the list, you will print the list. middle_index = len(l)//2 # There l Then it will be l_left perhaps l_right Replace # So, every time middle_index It's the middle one of the current list. if not l: # This means judging if target_num Not in list l Words in Li print('It's not on this watch.') return # If it does, its return value is None if target_num > l[middle_index]: l_right = l[middle_index+1:] # Notice here that since target_num than l[middle_index]Big, # Well, l[middel_index]It can be eliminated directly from l[middle_index+1]Start comparing get_num(l_right,target_num) # That's the way l_right As the original l It's in. # Here is the recursive call elif target_num < l[middle_index]: l_left = l[:middle_index] get_num(l_left,target_num) else: print('find it',l[middle_index]) get_num(l,target_num) # Call this function # Give this function two arguments, the top two.[1, 2, 4, 65, 76, 123, 156, 157, 235, 256, 278, 301, 324, 786] [1, 2, 4, 65, 76, 123, 156] [76, 123, 156] [76] [] //It's not on this watch.