Fibonacci Generator in Python
Level 4117 keystrokes
This creates a generator function using yield. Generators produce values lazily, one at a time when iterated.
Python code
# Generator function that yields the first n Fibonacci numbers1def fibonacci_gen(n): # Start with the first two Fibonacci numbers, 0 and 12 a, b = 0, 1 # Repeat n times; _ marks the loop variable as unused3 for _ in range(n): # Yield the current number and pause until the next value is requested4 yield a # Move forward: a takes b, and b takes the sum of the previous two5 a, b = b, a + b6 # list() runs the generator to the end and collects its 8 values7fib = list(fibonacci_gen(8))# Print [0, 1, 1, 2, 3, 5, 8, 13]8print(fib)Output
[0, 1, 1, 2, 3, 5, 8, 13]
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
(× 5)× 5,× 4_× 3=× 3:× 2+× 1