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

走远了吗. 提交于 2020-03-27 11:09:13

迭代器实现:

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!