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:

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

Def a (): B () def b (): A () if __name__ = = ' __main__ ': A ()

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

An exception will be thrown soon:runtimeerror:maximum recursion depth exceeded

What 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.

650) this.width= 650, "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

  1 from greenlet import greenlet 2 def test1 (): 3      while 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 ') 10         print (' test2  ',  u) 11  12 if __name__ ==  ' __main__ ': 13     gr1 = greenlet ( test1) 14     gr2 = greenlet (test2) 15     print  gr1.switch () 

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

Next, use generator to simulate this implementation.

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

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")

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

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.

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

Def test1 ():    while true:             data = yield  (gr2,  ' msg from test1 ')          print (' test1  ',  data)          Def test2 ():    while true:                 data = yield  (gr1,  ' msg from  Test2 ')         print (' test2  ',  data)          gr1 = test1 () Gr2 = test2 () Gr1.next () Gr2.next () Def run ():     co, data = gr1,  ' init '     while true:         co, data = co.send (data) run ()

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

This ' s ok!


Infinite "recursive" python program

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.