Fibonacci sequence is implemented using iterators

Fibonacci sequence, the first number in the sequence is 0, the second number is 1, and each subsequent number can be obtained by adding the first two numbers:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

class FibIterator(object):
    """Fibonacci sequence iterator"""
    def __init__(self, n):
        """
        :param n: int, specifies the first n numbers of the generated sequence
        """
        self.n = n
        # current is used to save the number of numbers currently generated into the sequence
        self.current = 0
        # num1 is used to save the previous number, the initial value is the first number in the sequence 0
        self.num1 = 0
        # num2 is used to save the previous number, the initial value is the second number 1 in the sequence
        self.num2 = 1

    def __next__(self):
        """Called by next() function to get the next number"""
        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):
        """Iterator's __iter__ returns itself"""
        return self


if __name__ == '__main__':
    fib = FibIterator(10)
    for num in fib:
        print(num, end=" ")

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325855730&siteId=291194637