Recursive functions
Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.
For example, let's calculate factorial n! = 1 * 2 * 3 * ... * n, denoted by the function fact (n), you can see:
Fact (n) = n! = 1 * 2 * 3 * ... * (n-1) * n = (n-1)! * n = fact (n-1) * n
So, fact (n) can be represented as N * fact (n-1), and only n=1 requires special handling.
So, fact (n) is written in a recursive way:
def fact (N): if n==1: return 1 return N * Fact (N-1)
Explain
The
Above is a recursive function. You can try it:
>>> fact (1)
1
>>> Fact (5)
+
>>> fact (+)
9332621544394415268169923885626670049071596826438162146859296389521759999322991560894146397615651828625369792082722375825 1185210916864000000000000000000000000L
If we calculate fact (5), we can see the calculation process according to the function definition as follows:
===> fact (5)
===> 5 * FACT (4 )
===> 5 * (4 * FACT (3))
===> 5 * (4 * (3 * FACT (2)))
===> 5 * (4 * (3 * (2 * FACT (1)))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 *
===> +
Recursive functions have the advantage of simple definition and clear logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion. The
uses recursive functions that require attention to prevent stack overflow. In the computer, the function call is implemented through a stack (stack) of this data structure, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the size of the stack is not infinite, there are too many recursive calls that can cause the stack to overflow. You can try to calculate fact (10000).
def Digui (n): = 0 if n<=0: return 1 else: Return N*digui (n-1print(Digui (5))
If you thirst for knowledge, you are foolish. The sort of Python to list int and Fibonacci sequence
Li = [33,2,10,3] for in range (1,le (i) ) # - in Range (Len (LI)-1): # make multiple comparisons of a number if li[i] > li[i + 1]: # make a judgment condition temp = Li[i] # meet words replace li[i] = li[i + 1] + 1] = temp Print(LI)
Since the sorting is OK, then the Fibonacci sequence
Use the function to write the following series:
The Fibonacci sequence refers to a sequence of 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368. ..
def Fun (i, A1, A2): if i = = : return a1 = a1 + a2 = Fun (i + 1, A2, A3)
return re fun (1)
think about it and look at it later.
Python recursion and Fibonacci sequence