無限“遞迴”的python程式

來源:互聯網
上載者:User

標籤:get   例子   next   exe   resume   targe   main   ext   條件   

  如果一個函數直接或者間接調用了自己,那麼就形成了遞迴(recursion),比如斐波那契數列的一個實現

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

  遞迴一定要有結束條件,否則就形成了死迴圈, 比如下面的例子:

def a():    b()def b():    a() if __name__ == ‘__main__‘:    a()
  很快 就會拋出一個異常: RuntimeError: maximum recursion depth exceeded  會什麼報這個異常,很簡單,我們都知道子程式調用(call)需要壓棧出棧,如果無限遞迴調用,那麼就一直壓棧,沒有出棧,記憶體消耗也越來愈多。python比較進階,直接拋出這個異常,結束程式運行。   前面的文章提到協程(coroutine)這個概念,不管是generator還是greenlet,文法看起來都很像函數調用,但事實上並不是,協程只是在切換的時候把當前調用棧中的資訊儲存了起來:
“all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack. When the execution is resumed by calling one of the generator’s methods, the function can proceed exactly as if the  yield expression was just another external call.”

 

  利用協程實現無限遞迴似乎成為了可能, 維基百科上有虛擬碼描述。首先對於greenlet,實現這個“無限遞迴”函數比較容易的。

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

 

   接下來用generator來類比這個實現
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")

 

運行報錯:ValueError: generator already executing,這個錯誤在這篇文章也有提到,這個問題,在維基百科上正確的姿勢。我們改改代碼

 

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

This‘s Ok!

 references:http://www.cnblogs.com/xybaby/p/6323358.htmlhttps://en.wikipedia.org/wiki/Coroutine#Implementations_for_Pythonhttps://segmentfault.com/q/1010000003059446 

無限“遞迴”的python程式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.