...

/

Solution Review: Create a Fibonacci Iterator

Solution Review: Create a Fibonacci Iterator

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

Press + to interact
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: ...

Access this course and 1400+ top-rated courses and projects.