#36 · Iterators and generators · Beginner · 35 XP · about 6 min
In a Fibonacci-style sequence each number is the sum of the two before it. Starting from 0 and 1 you get 0, 1, 1, 2, 3, 5, 8, 13 and so on, forever.
Write a generator fib_stream(a=0, b=1) that yields the sequence starting with a and b, and never stops. Because it never ends, whoever uses it decides how much to take, for example with itertools.islice.
from itertools import islice list(islice(fib_stream(), 8)) # returns [0, 1, 1, 2, 3, 5, 8, 13] list(islice(fib_stream(2, 1), 6)) # returns [2, 1, 3, 4, 7, 11] next(fib_stream()) # returns 0
The second example starts from 2 and 1, which gives the Lucas numbers.
A list cannot hold an endless sequence, so the answer has to be a generator that makes each number only when it is asked for.
Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.