分别用Python的迭代器和生成器实现斐波那契数列
迭代器实现:
class Fib(object):
def __init__(self, stop):
self.stop = stop
self.current = 0
self.num1 = self.num2 = 1
def __iter__(self):
return self
def __next__(self):
x = self.num1
if self.current < self.stop:
self.current += 1
self.num1, self.num2 = self.num2, self.num1 + self.num2
return x
raise StopIteration生成器实现:
def Fib(stop):
current = 0
num1 = num2 = 1
while current < stop:
yield num1
num1, num2 = num2, num1 + num2
current += 1 相关推荐
JnX 2020-09-21
joyjoy0 2020-09-18
Jan 2020-08-17
shenxiuwen 2020-08-01
Andrewjdw 2020-07-26
fanhuasijin 2020-06-21
丽丽 2020-06-08
容数据服务集结号 2020-06-08
czsay 2020-06-01
程序员之怒 2020-04-26
wmsjlihuan 2020-04-26
oDongTianShuiYue 2020-04-26
kong000dao0 2020-04-29
breakpoints 2020-04-20
卷卷萌 2020-04-20
RocNg 2020-04-18
HongKongPython 2020-03-26
kkpiece 2020-03-25