...

/

Solution Review: Create a Fibonacci Iterator

Solution Review: Create a Fibonacci Iterator

The solution to the 'Create a Fibonacci Iterator' challenge.

Press + to interact
Python 3.10.4
class Fibonacci:
def __init__(self, n):
self.limit = n
self.count = 1
self.a = 0
self.b = 1
def __iter__(self):
return self
def __next__(self):
if self.count <= self.limit: # Controlled iterations
x = self.a
self.a, self.b = self.b, self.a +self.b # Adding preceding values
self.count += 1
return x
else:
raise StopIteration
fib = Fibonacci(7)
iterator = iter(fib)
for x in iterator:
print(x)

Explanation

For calculating the Fibonacci sequence, we need two variables to maintain the track as every number is the sum of the preceding two numbers: Fi=Fi1+Fi2F_{i} = F_{i-1} + F_{i-2}

As required by the problem statement, the iterator Fibonacci has three methods:

  • __init__() method
  • __iter__() method
  • __next__() method

Let’s look at each of them one by one.

The __init__() method

Here, we set an instance limit that defines the maximum number of iterations, and another instance count to track the number of iterations completed successfully. Most importantly, to calculate sequence, we need two separate variables. So, we create two instances a and b. We set a as 0 and b as 1, the first two Fibonacci numbers.

The __iter__() method

This method returns nothing but the iterator object.

The __next__() method

This method contains the implementation of the algorithm. Look at line 12. We apply a condition (self.count <= self.limit) that controls when to stop the loop. Then comes the important part, i.e., calculating the next number in the sequence. Let’s break down the task into a few steps:

  • In every iteration, we have to return the number stored in a. We’ll create a dummy variable and set it with the value of a.
  • The instance a will be equal to b, and b will be equal to the sum of b and a.
  • We’ll increment count by 1 and return the value stored in the dummy variable in the first step.

All these steps are performed if the condition at line 12 is true. If it is not, then we raise an exception StopIteration.

Now, look at line 20. We create an object of Fibonacci with n as 7. Its iterator is then passed in the loop to generate the sequence: 0, 1, 1, 2, 3, 5, 8.


Ask