Python Programming - Generators - Discussion

Discussion Forum : Generators - General Questions (Q.No. 50)
50.
How can you implement a generator that produces a Fibonacci sequence?
Using a loop with a yield statement and two variables
By calling a recursive function with yield
Using a list comprehension with yield
By using the itertools.cycle() function
Answer: Option
Explanation:
A generator for a Fibonacci sequence can be implemented using a loop with a yield statement and two variables to keep track of the current and previous values.
def fibonacci_sequence():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

# Example usage
fibonacci_gen = fibonacci_sequence()
for _ in range(5):
    print(next(fibonacci_gen))
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.