Fibonacci Sequence
Medium · 50 XPPrint the first 10 Fibonacci numbers (starting 0, 1) on one line separated by spaces.
0 1 1 2 3 5 8 13 21 34
Track a, b = 0, 1; append to a list; print(" ".join(map(str, fibs))).
fibs = []
a, b = 0, 1
for _ in range(10):
fibs.append(a)
a, b = b, a + b
print(" ".join(map(str, fibs)))
Run your code to check it…
How to approach Fibonacci Sequence
Each Fibonacci number is the sum of the two before it, so you only ever need to remember two values. Start with a, b = 0, 1; on each step, record a, then move both forward.
The move is a, b = b, a + b. Python evaluates the whole right-hand side before assigning anything, so the old a is still available when a + b is computed. Collect the numbers in a list and print them with " ".join(map(str, fibs)), because join only accepts strings.
Worked through on this data
- Start a = 0, b = 1. Record 0, then a, b = 1, 1.
- Record 1, then 1, 2. Record 1, then 2, 3. Record 2, then 3, 5. Record 3, then 5, 8.
- Continue for ten records in total: 0 1 1 2 3 5 8 13 21 34.
Common mistakes
- Two separate lines,
a = bthenb = a + b, overwriteatoo early and produce 0 1 2 4 8 16, doubling instead of adding. - Printing the list directly shows brackets and commas:
[0, 1, 1, ...]. - Off-by-one: starting at 1, 1 or looping 11 times gives the wrong ten numbers.
Time and space
The loop is O(n) time and the list is O(n) space. The naive recursive definition fib(n - 1) + fib(n - 2) is O(2^n), because it recomputes the same values again and again.
Where this shows up
Carrying a small amount of state forward through a loop, rather than recomputing from scratch, is the core of running totals, moving averages and dynamic programming.
Take it further
Turn it into a generator function with yield, then print the first Fibonacci number with more than 100 digits.