Lesson 11 of 15
Recurrence Relations
Counting with Recurrences
A recurrence relation defines a sequence by expressing in terms of previous terms. Combined with initial conditions, it uniquely determines the sequence.
Linear Recurrences
A linear homogeneous recurrence with constant coefficients:
Characteristic equation: substitute to get . If roots are distinct, the solution is:
Fibonacci: , , . Characteristic roots (golden ratio and its conjugate).
Towers of Hanoi
, . Closed form: .
def solve_linear_recurrence(coeffs, initial, n):
seq = list(initial)
k = len(coeffs)
while len(seq) <= n:
next_val = sum(coeffs[i] * seq[-(i+1)] for i in range(k))
seq.append(next_val)
return seq[n]
# Fibonacci: coeffs=[1,1], initial=[0,1]
print(solve_linear_recurrence([1, 1], [0, 1], 10)) # 55
Your Task
Implement solve_fibonacci, solve_linear_recurrence, and towers_of_hanoi_count.
Pyodide loading...
Loading...
Click "Run" to execute your code.