美文网首页
斐波那契数列

斐波那契数列

作者: 胖虎很可爱 | 来源:发表于2018-04-20 16:14 被阅读0次
# 类实现
class fib:

    def __init__(self, n):
        self.current = 0
        self.n = n
        self.num1, self.num2 = 0, 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.current < self.n:
            num = self.num2
            self.num1, self.num2 = self.num2, self.num1 + self.num2
            self.current += 1
            return num
        raise StopIteration
aa = fib(340)
for i in aa:
    print(i)
# 生成器实现
def fib(n):
    current = 0
    num1, num2 = 0, 1
    while current < n:
        num = num2
        num1, num2 = num2, num1 + num2
        current += 1
        yield num
    raise StopIteration

a = fib(5)
for i in a:
    print(i)

相关文章

网友评论

      本文标题:斐波那契数列

      本文链接:https://www.haomeiwen.com/subject/schzkftx.html