用Python实现斐波那契数列代码

class fibonacci(object):
    def __init__(self, sequence_count=10):
        self._first = 0
        self._second = 1
        self._sequence_count = sequence_count

        self._index = 0

    def __iter__(self):
        return self

    def __next__(self):
        self._index += 1
        if self._index == 1:
            return self._first   # 返回数列的第一项
        elif self._index == 2:
            return self._second  # 返回数列的第二项
        elif self._index <= self._sequence_count:
            self._first, self._second = self._second, self._first + self._second  # 这是 Python 的语法糖,把 self._second 赋值给 self._first ,把 self._first+self._second 的和赋值给 self._second
            return self._second  # 返回数列的第 n 项,其中 n >= 3
        else:
            raise StopIteration


if __name__ == "__main__":
    fi = fibonacci(sequence_count=20)

    for item in fi:
        print(item, end=" ")

运行结果如下:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 

猜你喜欢

转载自blog.csdn.net/lianshaohua/article/details/111050932