Python turn tail recursive optimization!

Source: Internet
Author: User

This article and everyone to share is mainly python in the tail recursion related use method, hope that through the sharing of this article can help you better learn the Python language , come together to see it.

general recursion and tail recursion

General recursion

def normal_recursion (n):

if n = = 1:

return 1

Else:

return n + normal_recursion (n-1)

Perform:

normal_recursion (5) 5 + normal_recursion (4) 5 + 4 + normal_recursion (3) 5 + 4 + 3 + normal_recursion (2) 5 + 4 + 3 + 2 + normal_recursion (1) 5 + 4 + 3 + 35 + 4 + 65 + 1015

As you can see , the general recursion , each level of recursion needs to call the function , will create a new stack ,

as the recursion depth increases , the stacks are created more and more, causing a burst stack : Boom:

tail recursion

Tail recursion is based on the tail call of the function, and each level calls the return value of the return function to update the call stack without creating a new call stack . implementations of similar iterations , General recursion is optimized in both time and space !

def tail_recursion(n, total=0):

if n = = 0:

return Total

Else:

return tail_recursion (n-1, Total+n)

Perform:

tail_recursion(5)tail_recursion(4, 5)tail_recursion(3, 9)tail_recursion (2,)tail_recursion(1, +)tail_recursion(0,)

as you can see , each level of recursive function calls becomes a " linear " form .

deep understanding of tail recursion

uh , so what ? does it feel like it's not enough? ... who says tail-recursive calls don't have to create a new stack? ?

Let's go to the bottom and find out.

int tail_recursion(int n, int total) {

If (n = = 0) {

return total;

}

Else {

return tail_recursion (n-1, total+n);

}

}

int main(void) {

int total = 0, n = 4;

tail_recursion (n, total);

return 0;

}

Anti-assembly

$ gcc-s tail_recursion.c-o normal_recursion. S

· $ gcc-s-o2 tail_recursion.c-o tail_recursion. S -gcc open tail recursive optimization

Compare the disassembly code as follows (+/- grammar )


As you can see , using the call function to create a new call stack before turning on tail recursion optimization (lbb0_3);

With the end recursive optimization , there is no new call stack generated , but direct pop

BP points to the address of the _tail_recursion function (Pushq%rbp) and then returns ,

still using the same call stack !

problems that exist

Although the tail recursive optimization is very good , but python does not support the tail recursion, the recursion depth of more than zero will be error

runtimeerror: maximum recursion depth exceeded

A cow man came up with a solution

implement a tail_call_optimized decorator

#!/usr/bin/env python2.4# This program shows off a python decorator (# which implements tail call optimization. I t# does this is throwing an exception if it is# it's own grandparent, and catching such# exceptions to recall the stack.

Import sys

class tailrecurseexception:

def __init__(self, args, Kwargs):

Self.args = args

Self.kwargs = Kwargs

def tail_call_optimized(g):

"""

This function decorates a function with tail call

Optimization. It does 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 ()

# Why is grandparent, the function default first-level recursion is the parent call ,

# for tail recursion , do not want to generate a new function call ( ie : grandfather call ),

# So throw an exception here , get the Parameters , exit the recursive call stack of the modified function ! ( analysis of moving graphs behind )

if f.f_back and F.f_back.f_back

and F.f_back.f_back.f_code = = F.f_code:

# throws an exception

raise tailrecurseexception (args, Kwargs)

Else:

while 1:

Try:

return g (*args, **kwargs)

except tailrecurseexception, E:

# catch exception , get Parameters , exit recursive call stack of modified function

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)

in order to show more clearly the effect of the pre-and post-call stack changes and the tail_call_optimized adorner throwing out the recursive call stack , I use pudb Debugging Tools made a motion picture.

Turn on call stack before tail recursive optimization


after turning on tail recursion optimization (tail_call_optimized Adorner ) the call stack

by Pudb the stack in the right column , You can see the change of the call stack clearly .

because the tail recursion does not have a nesting of call stacks , Python does not report runtimeerror:maximum recursion Depth Exceeded 's wrong !

here 's an explanation of the sys._getframe () function :

sys._getframe ([depth]):

Return A Frame object from the call stack.

If Optional Integer depth is given and return the frame object that many calls below the top of T He stack.

If is deeper than the call stack, Valueefror is raised. The default for depth is zero,

returning the frame at the top of the "Call stack."

that is , the stack frame object that returns the depth depth call .

Import sys

def get_cur_info():

Print sys._getframe (). F_code.co_filename # Current file name

Print sys._getframe (). F_code.co_name # Current function name

Print sys._getframe (). F_lineno # Current line number

Print sys._getframe (). F_back # caller's frame

Source: Segmentfault



Python turn tail recursive optimization!

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.