Incredible Python tail recursion Optimization

Source: Internet
Author: User

In general, similar to Java and C #, Python does not have the ability to automatically optimize tail recursion. recursive calls are widely criticized for being limited by the call stack length, however, this article will give you an incredible method to achieve Python's tail recursion optimization. Therefore, Python's recursive call no longer needs to be restricted by the call stack length.

BKJIA recommended reading: Use Python recursion to process files

Let's take a look at the call method of the last delivery method:

 
 
  1. defFib(n,b1=1,b2=1,c=3):  
  2. ifn<3: 
  3. return1  
  4. else:  
  5. ifn==c:  
  6. returnb1+b2  
  7. else:  
  8. returnFib(n,b1=b2,b2=b1+b2,cc=c+1) 

To test this program, call Fib (1001:

 
 
  1. >>>defFib(n,b1=1,b2=1,c=3):  
  2. ...ifn<3: 
  3. ...return1  
  4. ...else:  
  5. ...ifn==c:  
  6. ...returnb1+b2  
  7. ...else:  
  8. ...returnFib(n,b1=b2,b2=b1+b2,cc=c+1)  
  9. ...  
  10. >>>Fib(1001)  
  11.  
  12. 703303677114228158218352548771835497701812698363587327426  
  13. 049050871545371181969335797422494945626117334877504492417  
  14. 659910881863632654502236471060120533741212738673391111981  
  15. 39373125598767690091902245245323403501L 

If we use Fib (1002), the result is as follows:

 
 
  1. .....  
  2. File"<stdin>",line8,inFib  
  3. File"<stdin>",line8,inFib  
  4. File"<stdin>",line8,inFib  
  5. File"<stdin>",line8,inFib  
  6. File"<stdin>",line8,inFib  
  7. File"<stdin>",line8,inFib  
  8. RuntimeError:maximumrecursiondepthexceeded 

Now let's optimize the tail recursion. Add a Decorator to the Fib function, as shown below:

 
 
  1. @tail_call_optimized  
  2. defFib(n,b1=1,b2=1,c=3):  
  3. ifn<3: 
  4. return1  
  5. else:  
  6. ifn==c:  
  7. returnb1+b2  
  8. else:  
  9. returnFib(n,b1=b2,b2=b1+b2,cc=c+1) 

This is the decorator @ tail_call_optimized. This decorator makes Python magically break the call stack restrictions. Even if we run Fib (20000), we can run the results in ms.

 
 
  1. importsys  
  2. classTailRecurseException:  
  3. def__init__(self,args,kwargs):  
  4. self.args=args  
  5. self.kwargs=kwargs  
  6. deftail_call_optimized(g):  
  7. """  
  8. Thisfunctiondecoratesafunctionwithtailcall  
  9. optimization.Itdoesthisbythrowinganexception  
  10. ifitisit'sowngrandparent,andcatchingsuch  
  11. exceptionstofakethetailcalloptimization.  
  12.  
  13. Thisfunctionfailsifthedecorated  
  14. functionrecursesinanon-tailcontext.  
  15. """  
  16. deffunc(*args,**kwargs):  
  17. f=sys._getframe()  
  18. iff.f_backandf.f_back.f_backandf.f_back.f_back.f_code==f.f_code:  
  19. raiseTailRecurseException(args,kwargs)  
  20. else:  
  21. while1:  
  22. try:  
  23. returng(*args,**kwargs)  
  24. exceptTailRecurseException,e:  
  25. args=e.args  
  26. kwargs=e.kwargs  
  27. func.__doc__=g.__doc__  
  28. returnfunc 

The method used has been shown before. The author throws an exception and captures it to break the call stack growth. This is simply incredible. In addition, the efficiency problem is about five times the time overhead compared with direct tail-recursive Fib. Finally, it was incredible that the goal of tail recursion optimization was achieved.

Link: http://www.cnblogs.com/Alexander-Lee/archive/2010/09/16/1827587.html

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.