标签:存储 method common lin when 否则 proc already 代码
如果一个函数直接或者间接调用了自己,那么就形成了递归(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()
“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()
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 @consumer def test1(): while True: data = yield print(‘test1 ‘, data) gr2.send(‘msg from test1‘) @consumer def 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!
标签:存储 method common lin when 否则 proc already 代码
原文地址:http://www.cnblogs.com/chenliyang/p/6559819.html