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