Python-end recursive usage examples in detail

Source: Internet
Author: User
Tags python decorator
The example in this paper describes the recursive use of the tail in Python. Share to everyone for your reference. The specific analysis is as follows:

If all the recursive calls in a function appear at the end of the function, we call this recursive function the tail recursion. This recursive invocation is the tail recursion when the recursive call is the last executed statement in the body of the function and its return value is not part of an expression. The feature of the tail recursive function is that it is not necessary to do anything in the regression process, which is important because most modern compilers use this feature to automatically generate optimized code.

Principle:

When the compiler detects that a function call is tail-recursive, it overwrites the current active record instead of creating a new one in the stack. The compiler can do this because the recursive call is the last statement to be executed during the current active period, so there is nothing else to do in the stack frame when the call returns, so there is no need to save the stack frame. By overwriting the current stack frame instead of adding one on top of it, the stack space used is greatly reduced, which makes the actual running efficiency even higher. Therefore, whenever possible, we need to write recursive functions in the form of tail recursion.

Code:

# shows off a python decorator (# which implements tail call optimization. it# does this by throwing a exception if it is# it ' s own grandparent, and catching such# exceptions to recall the STACK.I Mport Sysclass tailrecurseexception:def __init__ (self, args, Kwargs): Self.args = args Self.kwargs = Kwargsdef tail_cal L_optimized (g): "" "This function decorates a function with tail call optimization. It does this by throwing a exception if it is it's own grandparent, and catching such exceptions to fake the tail call op Timization. This function fails if the decorated function recurses in a non-tail context. "" "Def func (*args, **kwargs): F = sys._getframe () if F.f_back and f.f_back.f_back and f.f_back.f_back.f_code = = F.f_cod E:raise tailrecurseexception (args, Kwargs) else:while 1:try:return g (*args, **kwargs) except Tailrecurs Eexception, E:args = E.args Kwargs = E.kwargs func.__doc__ = g.__doc__ return func@tail_call_optimizeddef Factori Al (N, acc=1): "Calculate a factorial" if n = = 0:return acc return factorial (n-1, N*ACC) print factorial (10000) # Prints a big, bi G number,# but doesn ' t hits the recursion limit. @tail_call_optimizeddef fib (i, current = 0, next = 1): if i = = 0:return C Urrent else:return fib (i-1, Next, current + next) print fib (10000) # also prints a big number,# but doesn ' t hits the RECU Rsion limit.

Hopefully this article will help you with Python programming.

  • 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.