Fibonacci Sequence Generator
Generators are a powerful feature in Python for creating iterators in a simple way. They allow you to produce a sequence of values lazily, meaning they generate values one at a time as needed, which can be very memory-efficient for large sequences. This challenge will have you create a generator function to produce the Fibonacci sequence.
Problem Description
Your task is to create a Python generator function named fibonacci_generator that yields the numbers in the Fibonacci sequence. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones (e.g., 0, 1, 1, 2, 3, 5, 8, 13, ...).
Key Requirements:
- The generator function should be named
fibonacci_generator. - It should yield an infinite sequence of Fibonacci numbers.
- The sequence should start with 0 and 1.
Expected Behavior:
When you iterate over the generator, it should produce the Fibonacci numbers in the correct order.
Edge Cases to Consider:
- The first two numbers (0 and 1) are the base cases. Ensure they are handled correctly.
Examples
Example 1:
# Get the first 5 Fibonacci numbers
gen = fibonacci_generator()
output = [next(gen) for _ in range(5)]
print(output)
[0, 1, 1, 2, 3]
Explanation: The generator starts with 0 and 1. The next number is 0+1=1, then 1+1=2, then 1+2=3.
Example 2:
# Get the first 10 Fibonacci numbers
gen = fibonacci_generator()
output = [next(gen) for _ in range(10)]
print(output)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Explanation: Continuing the sequence, the numbers generated are 3+5=8, 5+8=13, 8+13=21, and 13+21=34.
Example 3:
# Demonstrate that the generator is infinite and can be stopped
gen = fibonacci_generator()
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
Explanation: This example shows that the generator can continue producing numbers indefinitely. We manually stop after printing 16 numbers.
Constraints
- The generator should produce an infinite sequence.
- The function must be a generator function (i.e., use
yield). - Do not pre-compute a large number of Fibonacci values and store them in memory. The generator should compute them on-the-fly.
Notes
- Remember the definition of the Fibonacci sequence: F(n) = F(n-1) + F(n-2), with F(0) = 0 and F(1) = 1.
- You'll need to keep track of the previous two numbers to calculate the next one.
- Consider how to handle the initial values (0 and 1) within your generator logic.
- Generators are memory efficient because they produce values one at a time. This is particularly useful for potentially infinite sequences.