Sub topic 15
Polynomials as Coefficient Lists in Code
Prerequisites and representation
Assume you can evaluate algebraic expressions, use integer arithmetic, interpret powers such as \(x^3\), and apply the distributive property.
A polynomial can be stored as a coefficient list: a list whose position gives the exponent of \(x\). The first position stores the constant coefficient, the next stores the coefficient of \(x\), and so on.
For example:
| Polynomial | Coefficient list |
|---|---|
| \(1+2x+3x^2\) | `[1, 2, 3]` |
| \(5-4x+x^2\) | `[5, -4, 1]` |
| \(7+x^3\) | `[7, 0, 0, 1]` |
The zero entries matter. In [7, 0, 0, 1], they show that the \(x\) and \(x^2\) terms are missing.
The list [1, 2, 3] represents \(1+2x+3x^2\), even though the usual written form starts with the highest power: \(3x^2+2x+1\).
Addition and subtraction
To add polynomials, align coefficients with the same exponent. Lists may have different lengths, so extend the shorter list with zeros.
Subtraction follows the same rule after changing every coefficient of the second polynomial to its opposite. This is the coefficient-list version of distributing a negative sign.
def add(p, q):
n = max(len(p), len(q))
p = p + [0] * (n - len(p))
q = q + [0] * (n - len(q))
return [a + b for a, b in zip(p, q)]
def subtract(p, q):
return add(p, [-c for c in q])
p = [1, 2, 3] # 3x^2 + 2x + 1
q = [5, -4, 1] # x^2 - 4x + 5
print(add(p, q)) # [6, -2, 4]
print(subtract(p, q)) # [-4, 6, 2]The addition result [6, -2, 4] represents \(4x^2-2x+6\). The subtraction result represents \(2x^2+6x-4\).
Multiplication by accumulating powers
When multiplying \(a x^i\) by \(b x^j\), multiply the coefficients and add the exponents:
\[ (a x^i)(b x^j)=abx^{i+j}. \]
Therefore, each pair of list entries contributes to position i + j. This implements distribution for polynomials of any size.
def multiply(p, q):
result = [0] * (len(p) + len(q) - 1)
for i, a in enumerate(p):
for j, b in enumerate(q):
result[i + j] += a * b
return result
print(multiply([2, 1], [1, 3, 1]))
# [2, 7, 5, 1], or x^3 + 5x^2 + 7x + 2
print(multiply([-3, 1], [3, 1]))
# [-9, 0, 1], or x^2 - 9A product of polynomials with degrees \(m\) and \(n\) has degree at most \(m+n\). The degree can be lower if the highest coefficients cancel.
Checking a computation
You can evaluate both factors and the product at the same value of \(x\). Equal values provide a useful check.
def evaluate(p, x):
return sum(c * x**i for i, c in enumerate(p))
a = [2, 1]
b = [1, 3, 1]
product = multiply(a, b)
x = 2
print(evaluate(a, x) * evaluate(b, x)) # 44
print(evaluate(product, x)) # 44Exercise
What coefficient list represents \(4x^3-2x+9\), and what is its degree?
Show answer
[9, -2, 0, 4]; its degree is 3.