迭代器:斐波那契数列

迭代器:斐波那契数列

class FibIterator(object):
    """斐波那契数列迭代器"""
    def __init__(self, n):
        self.n = n        # 迭代次数
        self.current = 0  # 标记迭代器位置
        # 初始值
        self.num1 = 0
        self.num2 = 1

    def __next__(self):
        """被next()函数调用,来获取下一个数"""
        if self.current < self.n:
            num = self.num1
            self.num1, self.num2 = self.num2, self.num1 + self.num2
            self.current += 1
            return num
        else:
            # 没有迭代数据时,抛出异常
            raise StopIteration

    def __iter__(self):
        """迭代器的__iter__返回自身,规定"""
        return self

fib = FibIterator(20)
sum1 = 0
for num in fib:
    sum1 += num

print("斐波那契数列的前20项之和为:%s" % sum1)

  

猜你喜欢

转载自www.cnblogs.com/andy9468/p/8988458.html