协程(Coroutines)实现fibonacci函数

 1 def fibonacci():
 2     yield 1
 3     yield 1
 4     l=[1,1]
 5     while True:
 6         l=[l[-1],sum(l[-2:])]
 7         yield l[-1]
 8 
 9 def tribonacci():
10     yield 0
11     yield 1
12     yield 1
13     l=[0,1,1]
14     while True:
15         l=[l[-2],l[-1],sum(l[-3:])]
16         yield  l[-1]
17 
18 for i,(f,t) in enumerate(zip(fibonacci(),tribonacci())):
19     if i==10:
20         break
21     print(f,t)

运行结果如下

 1 1 0
 2 1 1
 3 2 1
 4 3 2
 5 5 4
 6 8 7
 7 13 13
 8 21 24
 9 34 44
10 55 81

 

posted @ 2018-05-02 11:49  xajh00789  阅读(166)  评论(0编辑  收藏  举报