...

/

Solution Review: Generate Fibonacci Series with Generator

Solution Review: Generate Fibonacci Series with Generator

The solution to the 'Generate Fibonacci Series with Generator' challenge.

We'll cover the following...
Press + to interact
Python 3.10.4
def Fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a, b
a, b = b, a+b
for num in Fibonacci(7):
print(num)

Explanation

Look at the header of the generator at the start; it takes n as a parameter to define the limit. We create two variables a and b and set 0 and 1, respectively. We have a for loop controlling the iterations until n. According to the algorithm discussed previously, the variable a is returned every time via yield, and then the variables are modified.

Now, look at line 7. In the loop, we use Fibonacci(7) as a generator object to generate the following sequence: 0, 1, 1, 2, 3, 5, 8. Below is the visualization of how to follow these steps.


Ask