Recursive functions of Python

Source: Internet
Author: User
Tags function definition

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 x 2 x 3 x ... x n , which is represented by a function fact(n) , and you can see:

Fact (n) = n! = 1 x 2 x 3 x ... x (n-1) x n = (n-1)! X n = fact (n-1) x n

Therefore, fact(n) can be expressed as n x fact(n-1) , only n=1 need special handling.

So, it fact(n) is written in a recursive way:

def fact(n):    if n==1: return 1 return n * fact(n - 1)

Above is a recursive function. You can try:

>>> fact(1)1>>> fact(5)120>>> fact(100)93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

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 * 24===> 120   

The advantage of recursive functions is that they are simple in definition and clear in 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 use of recursive functions requires careful prevention of 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 fact(1000) :

>>> fact(1000)Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 4, in fact ... File "<stdin>", line 4, in factRuntimeError: maximum recursion depth exceeded in comparison

The method of solving recursive call stack overflow is optimized by tail recursion , in fact, the effect of tail recursion and loop is the same, so it is possible to think of the loop as a special tail recursive function.

Tail recursion means that when a function returns, it calls itself, and the return statement cannot contain an expression. In this way, the compiler or interpreter can optimize the tail recursion, so that the recursive itself, regardless of the number of calls, only occupy a stack frame, there is no stack overflow situation.

The above fact(n) function, because of the introduction of the return n * fact(n - 1) multiplication expression, is not a tail recursion. To change to a tail recursion, more code is needed, mainly to pass the product of each step into the recursive function:

def fact(n):    return fact_iter(n, 1)def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1, num * product)

As you can see, return fact_iter(num - 1, num * product) only the recursive function itself is returned, num - 1 and num * product it is evaluated before the function call, without affecting the function call.

fact(5)The corresponding fact_iter(5, 1) call is as follows:

===> fact_iter(5, 1)===> fact_iter(4, 5)===> fact_iter(3, 20)===> fact_iter(2, 60)===> fact_iter(1, 120)===> 120

At the end of a recursive call, if optimized, the stack does not grow, so no amount of calls will cause the stack to overflow.

Unfortunately, most programming languages are not optimized for tail recursion, and the Python interpreter is not optimized, so even if the above function is changed to fact(n) tail recursion, it can cause the stack to overflow.

Summary

The advantage of using a recursive function is that the logic is simple and clear, and the disadvantage is that too-deep calls cause a stack overflow.

The language that is optimized for tail recursion can prevent stack overflow by tail recursion. The tail recursion is actually equivalent to the loop, and the programming language without the loop statement can only be looped by the tail recursion.

The Python standard interpreter is not optimized for tail recursion, and there is a stack overflow problem with any recursive function.

Recursive functions of Python

Related Article

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.