zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python 斐波那契数列 Iterator 版本

Python 版本 数列 斐波 那契 Iterator
2023-09-14 09:07:32 时间
class Fabonacci(object):

    def __init__(self, num):
        #fabonni number
        self.num = num
        self.a = 1
        self.b = 1
        self.current_index = 0

    # __iter__
    def __iter__(self):
        return self

    #__next__
    def __next__(self):
        #1. judge if exceed
        if self.current_index < self.num:
            data = self.a
            self.a, self.b = self.b, self.a + self.b
            self.current_index += 1
            print("index = %d, a = %d, b = %d" % (self.current_index, self.a, self.b))
            return data
        #2. exceed
        else:
            raise StopIteration


if __name__ == '__main__':
    fabo_iteration = Fabonacci(5)
    for value in fabo_iteration:
    # value = next(fabo_iteration)
        print(value)