Python斐波那契數列迭代器

題目:實現一個迭代器類,將斐波那契數列從第一個元素返回到(n)。

迭代器:

class myFactorial:
    def __init__(self, n):
        self.n = n
        self.a = 0
        self.b = 1
        self.count = 0

    def __iter__(self):
        return self

    def __next__(self):
        value = self.a
        self.a, self.b = self.b, self.a + self.b
        self.count += 1
        if self.count > self.n:
            raise StopIteration
        return value

調用:

    mf = myFactorial(2)
    print(next(mf))
    print(next(mf))
    print(next(mf))

輸出結果:

0
1
1
2
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-2-c9c3e03a6025> in <module>()
      4 print(next(mf))
      5 print(next(mf))
----> 6 print(next(mf))

<ipython-input-1-3e19f48be091> in __next__(self)
     14         self.count += 1
     15         if self.count > self.n:
---> 16             raise StopIteration
     17         return value

StopIteration: 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章