递归实现
>>> >>> 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