Python learning diary (13) recursive functions and binary search algorithm

What is a recursive function?

It is simply a function of repeated calls itself a function of

Recursive function at the time of the call will continue until the end of the open space or memory to program a number of times recursive will complain

Recursively computing times:

i = 0
def func():
    global i
    print('i = {}'.format(i))
    i += 1
    return func()
func()            #.....i = 994 i = 995 RecursionError: maximum recursion depth exceeded while calling a Python object

Here we modify the number of times we recursive:

import sys
sys.setrecursionlimit(1000000)
i = 0
def func():
    global i
    print('i = {}'.format(i))
    i += 1
    return func()
func()      #...i = 3924 i = 3925

If you want recursion more times, it is necessary to improve the performance of the computer

Recursive function advantage is to allow a simple question, but the disadvantage is too occupy memory, thus recursive function is not suitable for solving large-scale problems to be computed recursively

 

Binary search algorithm:

This is the query must be a list ordered list

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 ' I can not find this element! ' 
Print (Find ([5,6,8,9,10,17,18,19,20],. 8)) # 2

Guess you like

Origin www.cnblogs.com/Fantac/p/11388221.html