Animations
Fibonacci Sequence — Visual Walkthrough
Watch the two sliding variables a and b advance each step to generate the Fibonacci sequence.
Fibonacci Sequence
Generate the first 10 Fibonacci numbers. Each number is the sum of the two before it.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34Fibonacci Sequencesliding window · O(n)
target10 numbers
sliding variables
a
—
+
b
—
=
next
?
sequence
0 / 10[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
fibonacci.py
def fibonacci(n):
a, b = 0, 1
sequence = [0, 1]
while len(sequence) < n:
next = a + b
sequence.append(next)
a, b = b, next
return sequence
Call fibonacci(10) — generate first 10 Fibonacci numbers
step 0/35
0%
How it works
def fibonacci(n):
a, b = 0, 1
sequence = [0, 1]
while len(sequence) < n:
next = a + b
sequence.append(next)
a, b = b, next
return sequencea and b are the two most recent numbers. Each iteration calculates their sum, appends it, then slides both variables one step forward.
a, b = b, next is Python simultaneous assignment — both right-hand values are calculated before either assignment happens. No temporary variable needed.
Complexity
| Time | Space | |
|---|---|---|
| This approach | O(n) | O(n) |