生成器
- 生成器表達(dá)式:(x ** 2 for x in range(1, 11))
- yield關(guān)鍵字
迭代器
- __iter__:返回迭代器對象
- __next__:取下一個迭代值
斐波那契數(shù)列和求素數(shù)的生成器和迭代器的實現(xiàn)
from math import sqrt
def is_prime(num):
"""判斷是不是素數(shù)"""
for factor in range(2, int(sqrt(num)) + 1):
if num % factor == 0:
return False
return True
def prime(num):
"""素數(shù)生成器"""
for val in range(2, num + 1):
if is_prime(val):
yield val
class Prime(object):
"""素數(shù)迭代器"""
def __init__(self, number):
self.number = number
self.idx = 1
def __iter__(self):
return self
def __next__(self):
if self.idx < self.number:
self.idx += 1
if is_prime(self.idx):
return self.idx
return self.__next__()
raise StopIteration()
class Fib(object):
"""斐波拉切數(shù)迭代器"""
def __init__(self, num):
self.num = num
self.a, self.b = 0, 1
self.idx = 0
def __iter__(self):
return self
def __next__(self):
if self.idx < self.num:
self.a, self.b = self.b, self.a + self.b
self.idx += 1
return self.a
raise StopIteration()
def fib(num):
"""斐波拉切數(shù)生成器"""
a, b = 0, 1
for _ in range(num):
a, b = b, a + b
yield a
def main():
"""主函數(shù)"""
print('fibonacci number'.center(80, '-'))
for val in Fib(20):
print(val, end=' ')
print('\n', '-' * 80, sep='')
print('prime number'.center(80, '-'))
for val in prime(100):
print(val, end=' ')
print('\n', '-' * 80, sep='')
if __name__ == '__main__':
main()