KatInterview

Build an Endless Fibonacci Stream with Python Generators

Math & Bit ManipulationModel answer
MediumModel answerMath & Bit Manipulationpythongeneratorslazy-evaluation

Last updated

Explain how lazy evaluation works in Python and write a generator that yields Fibonacci numbers indefinitely, with safe ways to consume it and the reasoning behind its state handling.

Task

Two parts:

  1. In your own words, explain what lazy evaluation means in Python. Mention at least one built-in or language feature that behaves lazily, and contrast it with an eager equivalent.
  2. Write a generator function, using yield, that produces the Fibonacci sequence without end: 0, 1, 1, 2, 3, 5, 8, ...

Expectations

  • The function must take no arguments and must not build a list of earlier terms.
  • Each value should be computed only when the caller asks for the next one.
  • Demonstrate how you would safely read:
    • the first 10 terms,
    • every term below 100,
    • the term at index 1000 (0-indexed).
  • Explain where the generator keeps its state between two consecutive requests.
  • State the time and space cost of producing the first n terms.
  • Mention which pitfalls apply when a caller consumes an infinite generator.

Expected outputs

  • First 10 terms: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
  • Terms below 100: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Hints

Hint 1

Think about what a Fibonacci step needs to remember. Two numbers are enough, so the generator only needs two local variables and an infinite loop.

Hint 2

A generator function does not run when called. It returns an iterator, and each `next()` resumes the body until the next `yield`, keeping its local variables alive in between.

Hint 3

Use tuple assignment, `a, b = b, a + b`, so both new values are computed from the old ones. To bound an infinite stream, use `itertools.islice` or `takewhile` rather than `list()` on the whole thing.