Solution Review: Create a Fibonacci Iterator
The solution to the 'Create a Fibonacci Iterator' challenge.
We'll cover the following...
Press + to interact
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: ...
Access this course and 1400+ top-rated courses and projects.