Examples of tail recursion in python: python instances

Source: Internet
Author: User
Tags python decorator

Examples of tail recursion in python: python instances

This example describes the tail recursion usage in python. Share it with you for your reference. The specific analysis is as follows:

If all recursive calls to a function appear at the end of the function, we call this function tail recursion. When a recursive call is the last statement executed in the entire function body and its return value is not part of the expression, this recursive call is tail recursion. The feature of the tail recursive function is that you do not need to perform any operations in the regression process. This feature is very important because most modern compilers will use this feature to automatically generate optimized code.

Principle:

When the compiler detects that a function call is tail recursion, it overwrites the current active records instead of creating a new one in the stack. The compiler can do this because recursive calls are the last statement to be executed in the active period. When this call returns, nothing else can be done in the stack frame, therefore, there is no need to save stack frames. By overwriting the current stack frame rather than adding another one on it, the used stack space is greatly reduced, which makes the actual running efficiency higher. Therefore, as long as possible, we need to write recursive functions into the form of tail recursion.

Code:

# This program shows off a python decorator(# which implements tail call optimization. It# does this by throwing an exception if it is# it's own grandparent, and catching such# exceptions to recall the stack.import sysclass TailRecurseException: def __init__(self, args, kwargs):  self.args = args  self.kwargs = kwargsdef tail_call_optimized(g): """ This function decorates a function with tail call optimization. It does this by throwing an exception if it is it's own grandparent, and catching such exceptions to fake the tail call optimization. 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_code:   raise TailRecurseException(args, kwargs)  else:   while 1:    try:     return g(*args, **kwargs)    except TailRecurseException, e:     args = e.args     kwargs = e.kwargs func.__doc__ = g.__doc__ return func@tail_call_optimizeddef factorial(n, acc=1): "calculate a factorial" if n == 0:  return acc return factorial(n-1, n*acc)print factorial(10000)# prints a big, big number,# but doesn't hit the recursion limit.@tail_call_optimizeddef fib(i, current = 0, next = 1): if i == 0:  return current else:  return fib(i - 1, next, current + next)print fib(10000)# also prints a big number,# but doesn't hit the recursion limit.

I hope this article will help you with Python programming.

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.