Fibonacci generator in Python
Generators produce values lazily - infinite sequences without infinite memory.
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
def take(gen, n):
return [next(gen) for _ in range(n)]
How it works
- Defines a generator that runs forever.
- Each
yieldhands out the next Fibonacci number on demand. take()pulls the first n values withnext().
Keywords and builtins used here
deffibonaccifornextrangereturntakewhileyield
The run, in numbers
- Lines
- 8
- Characters to type
- 120
- Tokens
- 48
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 30 seconds.
Step 2 of 7 in Iterators, errors & files, step 45 of 72 in Language basics.