斐波那契数列

递归实现

>>> 
>>> def fibonacci(a,b,end):
...     if b > end:
...             return
...     else:
...             print b
...             (a,b) = (b,a+b)
...             fibonacci(a,b,end)
... 
>>> fibonacci(0,1,10)
1
1
2
3
5
8
>>> 

  

while循环实现

>>> 
>>> def fibonacci(end):
...     a,b = 0,1
...     result = []
...     while b<end:
...             result.append(b)
...             a,b = b,a+b
...     return result
... 
>>> fibonacci(10)
[1, 1, 2, 3, 5, 8]
>>> 

  

while+yield实现

>>> 
>>> def fibonacci(end):
...     a,b = 0,1
...     while b<end:
...             yield b
...             a,b = b,a+b
... 
>>> for num in fibonacci(10):
...     print num
... 
1
1
2
3
5
8
>>> 

  

实现迭代器协议 *****

迭代器协议:必须具有 __next__ 和 __iter__ 方法

可迭代对象有 __iter__ 方法,执行__iter__方法得到的就是迭代器
 
# Python3

class Fibonacci(object):
    def __init__(self,end):
        self._a = 0
        self._b = 1
        self.end = end
    def __next__(self):
        if self._b > self.end:
            raise StopIteration
        self._a,self._b = self._b,self._a+self._b
        return self._a
    def __iter__(self):
        return self

fib = Fibonacci(100)
from collections import Iterator
print(isinstance(fib,Iterator))
for num in fib:
    print(num)

######################
True
1
1
2
3
5
8
13
21
34
55
89
作者:Standby一生热爱名山大川、草原沙漠,还有妹子
出处:http://www.cnblogs.com/standby/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/standby/p/8277567.html