自定义迭代器实现斐波那契数列

#斐波那契阿数列

class fib:
    def __init__(self):
        self.pre=0
        self.cou=1

    def __iter__(self):
        return self
    def __next__(self):
     #0 1 2 3 5 8 13
        # print(self.pre)  #0
        # print(self.cou)  #1
        self.cou,self.pre = self.pre+self.cou,self.cou
        print(self.cou)

if __name__=='__main__':

    f = fib()
    i = 0
    while i < 10:
        if i==0:
            print(i)
        # print(i)
        f.__next__()

        i += 1
#斐波那契阿数列
class Fib():
    def __init__(self):
        self.pre=0
        self.cour=1
    def __iter__(self):
        return self
    
    def __next__(self):
        value=self.cour
        self.cour=self.pre+self.cour
        self.pre=value
        return value
f=Fib()
list(islice(f,0,10))

猜你喜欢

转载自blog.csdn.net/qq_35810838/article/details/82936194