Solution Review: Create a Fibonacci Iterator
The solution to the 'Create a Fibonacci Iterator' challenge.
We'll cover the following...
class Fibonacci:def __init__(self, n):self.limit = nself.count = 1self.a = 0self.b = 1def __iter__(self):return selfdef __next__(self):if self.count <= self.limit: # Controlled iterationsx = self.aself.a, self.b = self.b, self.a +self.b # Adding preceding valuesself.count += 1return xelse:raise StopIterationfib = 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:
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 ofa. - The instance
awill be equal tob, andbwill be equal to the sum ofbanda. - We’ll increment
countby 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.