A Fibonacci Generator
Write a generator function fibonacci() that yields the Fibonacci numbers 0, 1, 1, 2, 3, 5, 8, ... without end. It takes no arguments. Each time you ask for the next value it must produce it on demand; it must not build a list first.
Understand the problem
What is a generator?
What does calling a generator function (a function with yield in it) do?
- It runs the whole body and returns a list
- It returns a generator object without running the body yet; the body runs as you ask for values
- It returns the first value
Calling it only creates the generator. The code inside runs when you call next() (or loop over it), up to the next yield, and then pauses with its local variables intact.
Why can a generator be infinite when a list cannot?
- It stores the numbers in a faster structure
- It only ever holds the current state and makes the next value on request
- Python limits the length for you
A list would have to hold every item in memory. A generator holds only a few variables (here the last two numbers) and computes the next value on demand. That is lazy evaluation.
Write the solution
Use yield. The tests read the first values with islice.
def fibonacci():
# Write your code here.
pass
Hint 1: a question to ask yourself
What do you need to remember to make the next number, and how do you keep it between values?
Hint 2: the shape of the answer
Two variables a, b = 0, 1. A while True: loop that does yield a and then a, b = b, a + b.
Reflect
Solution
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
What this tests: yield, generator functions, lazy evaluation, while True with an infinite sequence, and tuple assignment.
How to use an infinite generator: take only what you need. next(g) gives one value; itertools.islice(g, 10) gives the first 10; a for loop with break stops when you decide. Never call list() on it: it would never finish.
A generator is also an iterator: it remembers where it was. A second next continues where the first stopped. A new call to fibonacci() starts again from the beginning.
Memory: O(1), only two numbers are stored (they grow, but only by a few digits per step).
What an interviewer might ask next: Yield only the even Fibonacci numbers, lazily. ((x for x in fibonacci() if x % 2 == 0), a generator expression on top of a generator.)
VISIBLE = 3
CASES = [
('from itertools import islice\nresult = list(islice(fibonacci(), 10))', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34], 'the first ten numbers'),
('g = fibonacci()\nresult = [next(g), next(g), next(g)]', [0, 1, 1], 'next() gives one value at a time'),
('result = type(fibonacci()).__name__', 'generator', 'it returns a generator object'),
('g = fibonacci()\nfor _ in range(50):\n last = next(g)\nresult = last', 7778742049, 'the fiftieth number'),
('a = fibonacci()\nb = fibonacci()\nnext(a)\nnext(a)\nresult = next(b)', 0, 'two generators are independent'),
('from itertools import islice\nresult = list(islice(fibonacci(), 0))', [], 'taking nothing'),
]