Python: recursive function, python Recursive Function
1. First recognized recursive functions
1) What is a recursive function? If you call a recursive function in a function to a certain extent, an error is returned. --- RecursionError: maximum recursion dep th exceeded while calling a Python object. Recursive errors exceed the maximum depth of recursive functions. 2) Maximum recursion depth: 9973 by default) Advantages and Disadvantages of recursive functions # if there are too many recursion times, recursion is not suitable for solving the problem. # Disadvantages of recursion: memory occupation # advantages of recursion: making the code simpler 4) When Will recursion be used? The answers to the questions are answered step by step. 2. initial recognition algorithm ------ bipartite
# Locate the target value aim and position in l
L = [,] def find (l, aim ): mid_index = len (l) // 2 # Find the intermediate index if l [mid_index] <aim: # If the value of the intermediate index <target value new_l = l [mid_index + 1:] find (new_l, aim) elif l [mid_index]> aim: # If the value corresponding to the intermediate index> target value new_l = l [: mid_index] find (new_l, aim) else: print ('found ', mid_index, l [mid_index]) find (l, 66)
# Problem: if the target value is not in l, an error is reported and no return value is returned. Therefore, improvements are required.
Improvement:
Def find (l, aim, start = 0, end = None): end = len (l) if end is None else end mid_index = (end-start) // 2 + start if start <= end: if l [mid_index] <aim: return find (l, aim, start = mid_index + 1, end = end) elif l [mid_index]> aim: return find (l, aim, start = start, end = mid_index-1) else: return mid_index else: return 'This value cannot be found' ret = find (l, 44) print (ret)