Python: recursive function, python Recursive Function

Source: Internet
Author: User

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)

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.