分别用Python的迭代器和生成器实现斐波那契数列

小菜鸟的代码世界 2020-03-27

迭代器实现:
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

相关推荐