Infinite "recursive" python program

Source: Internet
Author: User

If a function calls itself directly or indirectly, it forms a recursive (recursion), such as an implementation of the Fibonacci sequence.

def fib (n):    if n <= 2:        return 1    else:        return fib (n-1) + fib (n-2)

Recursion must have an end condition, otherwise a dead loop is formed, such as the following example:

Def a ():    B () def b ():    A () if __name__ = = ' __main__ ':    A ()
An exception will be thrown soon: runtimeerror:maximum recursion depth exceededWhat will be reported this anomaly, very simple, we all know that the subroutine call needs to push the stack out of the stack, if the infinite recursive call, then the stack has been pressed, there is no stack, memory consumption is more.  Python is more advanced and throws this exception directly, ending the program running. The previous article mentions the concept of coroutine, whether it's generator or greenlet, the syntax looks much like a function call, but in fact it's not, the co-process simply stores the information in the current call stack as it switches:
"All local state are retained, including the current bindings of local variables, the instruction pointer, and the ternal evaluation stack. When the execution are resumed by calling one of the generator ' s methods, the function can proceed exactly as if the expression was just another external call. "

Implementing infinite recursion using a co-process seems to be possible, with a pseudo-code description on Wikipedia. First, it is easier to implement this "infinite recursive" function for Greenlet.

1 from Greenlet import Greenlet 2 def test1 (): 3 and     true:4         z = Gr2.switch (' msg from Test1 ') 5         print (' Test1 ', Z) 6  7 def test2 (v): 8 while     true:9         u = Gr1.switch (' msg from test2 ')         -print (' Test2 ', u) one-by-one if __n ame__ = = ' __main__ ':     gr1 = Greenlet (test1)     GR2 = Greenlet (test2)     print Gr1.switch ()

Next, use generator to simulate this implementation.
DEF consumer (func):    def wrapper (*args,**kw):        gen = func (*args, **kw)        gen.next ()        return Gen    wrapper.__name__ = func.__name__    wrapper.__dict__ = func.__dict__    wrapper.__doc__  = func.__doc__    return wrapper@consumerdef test1 (): While    True:        data = yield        print (' test1 ', data)        gr2.send (' msg From Test1 ') @consumerdef test2 (): While    True:        data = yield        print (' test2 ', data)        gr1.send (' msg From Test2 ') Gr1 = test1 () GR2 = Test2 () gr1.send ("Init")

Run Error: Valueerror:generator already executing, this error is also mentioned in this article, this issue, on Wikipedia on the correct posture. We changed the code.

def test1 ():    while True:            data = yield (GR2, ' msg from test1 ')        print (' test1 ', data)        def test2 ():    whil E True:                data = yield (Gr1, ' msg from test2 ')        print (' test2 ', data)        GR1 = test1 () GR2 = Test2 () gr1.next () Gr2.nex T () def run ():    Co, data = Gr1, ' init ' while    True:        Co, data = co.send (data) run ()

This ' s ok!

References:http://www.cnblogs.com/xybaby/p/6323358.htmlhttps://en.wikipedia.org/wiki/coroutine#implementations _for_pythonhttps://segmentfault.com/q/1010000003059446

Infinite "recursive" python program

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.