一宪潮、使用迭代器實現(xiàn)斐波拉契數(shù)列
class Fib(object):
"""
迭代器生成斐波拉契數(shù)列
:param max_value:最大范圍
:returns :所有的斐波拉契數(shù)列
"""
def __init__(self, max_value):
self.cur = 0
self.next = 1
self.max_value = max_value
def __iter__(self):
return self
def __next__(self):
if self.cur <= self.max_value:
result = self.cur
self.cur, self.next = self.next, self.cur+self.next
return result
else:
raise StopIteration()
二倾贰、使用生成器
def Fib(max_value):
"""
生成器生成斐波拉契數(shù)列
:param max_value:最大范圍
:returns :所有的斐波拉契數(shù)列
"""
cur_value = 0
next_value = 1
while cur_value <= max_value:
yield cur_value
cur_value, next_value = next_value, cur_value + next_value
使用迭代器和生成器的好處是節(jié)省內(nèi)存水评、惰性求值