Python Learning---function advanced

Source: Internet
Author: User

One, recursive function:

The program should know that in a function can also call other functions, which is called the function, but there is a special case, inside a function of the function of the call, we become the function of the recursive call.

Here, a household example is used to demonstrate the recursive invocation of a function------to find factorial:

1>>> func (1)213>>> Func (10)436288005>>> func (100)69332621544394415268169923885626670049071596826438162146859296389521759999322991560894146397615651828625369792082722375825 1185210916864000000000000000000000000L7>>> func (200)87886578673647905035523632139321850622951359776871732632947425332443594499634033429203042840119846239041772121389196388302 5764279024263710506192662495282993111346285727076331723739698894392244562145166424025403329186413122742829485327752424240 7573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000 000000000000L9>>>

The function implements a repeated call to itself, which is recursive!

The advantage of recursive functions is that they are simple in definition and clear in logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.

The use of recursive functions requires careful prevention of stack overflow. In the computer, the function call is implemented through a stack (stack) of this data structure, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the size of the stack is not infinite, there are too many recursive calls that can cause the stack to overflow. You can try func(1000) this: This is the exception display for stack Overflow

1File"<console>", Line 4,inchfunc2File"<console>", Line 4,inchfunc3File"<console>", Line 4,inchfunc4File"<console>", Line 4,inchfunc5File"<console>", Line 4,inchfunc6File"<console>", Line 4,inchfunc7File"<console>", Line 4,inchfunc8File"<console>", Line 4,inchfunc9File"<console>", Line 4,inchfuncTenFile"<console>", Line 4,inchfunc OneFile"<console>", Line 4,inchfunc AFile"<console>", Line 4,inchfunc -File"<console>", Line 4,inchfunc -File"<console>", Line 4,inchfunc theFile"<console>", Line 4,inchfunc -File"<console>", Line 4,inchfunc -File"<console>", Line 4,inchfunc -File"<console>", Line 4,inchfunc +File"<console>", Line 4,inchfunc -File"<console>", Line 4,inchfunc +File"<console>", Line 4,inchfunc AFile"<console>", Line 4,inchfunc atFile"<console>", Line 4,inchfunc -File"<console>", Line 4,inchFunc

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 the return statement cannot contain an expression. In this way, the compiler or interpreter can optimize the tail recursion, so that the recursive itself, regardless of the number of calls, only occupy a stack frame, there is no stack overflow situation.

The above fact(n) function, because of the introduction of the return n * fact(n - 1) multiplication expression, is not a tail recursion. To change to a tail recursion, more code is needed, mainly to pass the product of each step into the recursive function:

1 def func (n): 2     return func_iter (1, 1, N)34def  func_iter (product, COUNT, max):  5     if count > max:6         return  product  7     return func_iter (product * count, Count + 1, max)

At the end of a recursive call, if optimized, the stack does not grow, so no amount of calls will cause the stack to overflow.

Unfortunately, most programming languages are not optimized for tail recursion, and the Python interpreter is not optimized, so even if the above function is changed to fact(n) tail recursion, it can cause the stack to overflow.

There is a decorator for tail-recursive optimization, you can refer to the source code:

http://code.activestate.com/recipes/474088-tail-call-optimization-decorator/

We'll talk about how to write decorator later. Now, just use this @tail_call_optimized , and you'll be able to calculate it smoothly fact(1000) :

The code is described as follows:

1 #!/usr/bin/env python2.42 #This program shows off a python decorator (3 #which implements tail call optimization. It4 #does this by throwing a exception if it is5 #it ' s own grandparent, and catching such6 #exceptions to recall the stack.7 8 ImportSYS9 Ten classtailrecurseexception: One   def __init__(self, args, Kwargs): ASelf.args =args -Self.kwargs =Kwargs -  the deftail_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. +    A This function fails if the decorated at function recurses in a non-tail context. -   """ -   defFunc (*args, * *Kwargs): -f =Sys._getframe () -     ifF.f_back andF.f_back.f_back -          andF.f_back.f_back.f_code = =F.f_code: in       Raisetailrecurseexception (args, Kwargs) -     Else: to        while1: +         Try: -           returnG (*args, * *Kwargs) the         excepttailrecurseexception, E: *args =E.args $Kwargs =E.kwargsPanax NotoginsengFunc.__doc__= G.__doc__ -   returnfunc the  + @tail_call_optimized A defFactorial (n, acc=1): the   "Calculate a factorial" +   ifn = =0: -     returnACC $   returnFactorial (n-1, nACC) $  - PrintFactorial (10000) - #prints a big, big number, the #But doesn ' t hits the recursion limit. - Wuyi @tail_call_optimized the defFIB (i, current = 0, next = 1): -   ifi = =0: Wu     return Current -   Else: About     returnFIB (I-1, Next, current +next) $  - PrintFIB (10000) - #also prints a big number, - #But doesn ' t hits the recursion limit.

Python Learning---function advanced

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.