斐波那契数列
2018-01-12 20:27
141 查看
递归实现
>>> >>> 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__ 方法
# 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
相关文章推荐
- 第十二周项目3斐波那契数列
- 斐波那契数列心得
- go语言斐波那契数列实现
- 十七、斐波那契数列 【递推思想(迭代思想)解决】
- hdu 5171 GTY's birthday gift (矩阵快速幂求类斐波那契数列)
- 剑指Offer——斐波那契数列
- M斐波那契数列(矩阵快速幂+费马小定理)
- HDU-2672 god is a girl 斐波那契数列
- 剑指offer之斐波那契数列(Fibonacci)
- 斐波那契数列及相关问题
- 面试题9:斐波那契数列
- 斐波那契数列与阶乘---递归实现
- 循环队列,4阶斐波那契数列
- 斐波那契数列
- 剑指offer——斐波那契数列相关问题总结
- HD2041 超级楼梯【斐波那契数列】
- 斐波那契数列 Java实现
- 斐波那契数列
- 关于斐波那契数列三种解法及时间复杂度分析
- 斐波那契数列