Python recursive functions

Source: Internet
Author: User

Python can call other functions inside the function, and if a function calls itself internally, the function is a recursive function

Write a factorial recursive function def func(n):

n = =: N * func (N) (func ())

The use of recursive functions need to pay attention to prevent stack overflow, in the computer, function calls through the stack (stack) This data structure implemented, whenever a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack frame, because the size of the stack is not infinite, so the number of recursive calls too many, Will cause the stack to overflow, the case is as follows


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 thereturn statement cannot contain an expression. In this way, the compiler or interpreter can optimize the tail recursion, so that the recursive itself, no matter how many times it is called, consumes only one stack frame, and no stack overflow occurs.

The func (n) function above introduces a multiplication expression due to return N*func (n-1), so it is not a tail-recursive. To change to a tail recursion requires a bit more code, mainly to pass the flight of each step into the recursive function:

(n): Fact_iter (n) (numproduct): num = =: Product Fact_iter (num-num*product) (Fact ())

Tail recursive invocation, if optimized, the stack does not grow, so no matter how many calls will not cause a stack overflow

Unfortunately, most programming languages, including Python, do not optimize for tail recursion, so changing the above fact () function to tail recursion can also lead to stack overflow

Python recursive functions

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.