分別用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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章