您的位置:首页 > 其它

斐波那契数列

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: