Python Programming - Generators - Discussion
Discussion Forum : Generators - General Questions (Q.No. 50)
50.
How can you implement a generator that produces a Fibonacci sequence?
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:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers