python迭代器斐波那契
时间: 2023-12-25 13:30:03 浏览: 81
以下是两种Python迭代器实现斐波那契数列的例子:
1. 使用itertools模块的islice函数实现斐波那契数列迭代器:
```python
from itertools import islice
class Fib:
def __init__(self):
self.prev = 0
self.curr = 1
def __iter__(self):
return self
def __next__(self):
value = self.curr
self.curr += self.prev
self.prev = value
return value
if __name__ == '__main__':
fib = Fib()
print(list(islice(fib, 0, 10))) # 输出:[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
```
2. 使用迭代器方法实现斐波那契数列迭代器:
```python
class Fibonacci:
def __init__(self, all_num):
self.all_num = all_num
self.current_num = 0
self.a = 0
self.b = 1
def __iter__(self):
return self
def __next__(self):
if self.current_num < self.all_num:
result = self.a
self.a, self.b = self.b, self.a + self.b
self.current_num += 1
return result
else:
raise StopIteration
fibo = Fibonacci(10)
for num in fibo:
print(num) # 输出:0, 1, 1, 2, 3, 5, 8, 13, 21, 34
```
阅读全文