What's the recursive function and binary algorithm of the Python

Source: Internet
Author: User

What ' s the recursion?

  the definition of a recursive function: a function can be called again, if the function of the call is the function itself, then a recursive function is formed.

The maximum recursion depth is 997, which is defined by the program, and 997 can satisfy the situation of recursion in general.

# 997 Floors Max . def foo (n):     Print (n)     + = 1    foo (n) foo (1)

For a chestnut, suppose you want to know the age of a, but you only know a than B is 2 years old, B is two years older than C, and C is two years older than D, D is two years older than E, just you know the age of E, that is, you can know the age of a, which can be composed of a recursive. Well, let's assume that E's age is 20.

def Age (N):     if n = =1        :return    -Else:        return age (n-1 ) +2Print(age (5))

two-part algorithm

A classical use of recursive functions is the binary algorithm , which means to find the number in a list of small to large numbers by means of a semi-tangent search method.

Give me a chestnut:

L = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]deffunc (L,aim): Mid= (Len (l)-1)//2ifL:ifAim >L[mid]: func (L[mid+1:],aim)elifAim <L[mid]: func (L[:mid],aim)elifAim = =L[mid]:Print("Bingo", mid)Else:        Print('I can't find them .') func (L,66) func (L,6)

The above is a simple binary algorithm, of course, we can also improve the above code, in fact, is a meaning.

defFunc (l, Aim,start = 0,end = Len (l)-1): Mid= (start+end)//2if  notL[start:end+1]:        return    elifAim >L[mid]:returnFunc (l,aim,mid+1, end)elifAim <L[mid]:returnFunc (l,aim,start,mid-1)    elifAim = =L[mid]:Print("Bingo")        returnMidindex= Func (l,68)Print(index)

What ' the Python recursive function and the binary algorithm

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.