Sub topic 15
Polynomials as Coefficient Lists in Code
This chapter assumes you can add, subtract, and multiply polynomials by hand, and that you can read short Python programs. You should know what a coefficient, a degree, and a like term are. The goal is to turn each operation from earlier chapters into a small function, and to see why the code does exactly what the hand method does.
The representation
A polynomial in one variable is fully described by its coefficients. If you fix the order of the powers, you can drop the variable and store only the numbers. This chapter lists coefficients from the constant term upward. The position in the list is the exponent.
| Polynomial | Coefficient list |
|---|---|
| 3x^2 + 2x + 1 | [1, 2, 3] |
| x^2 - 4x + 5 | [5, -4, 1] |
| x^3 + 5x^2 + 7x + 2 | [2, 7, 5, 1] |
| x^2 - 9 | [-9, 0, 1] |
| 7 | [7] |
Two details matter here.
- A missing power gets a zero. The polynomial x^2 - 9 has no x term, so its list needs a 0 at index 1. If you leave it out, every later coefficient shifts to the wrong power.
- The list is in ascending order, which is the reverse of standard form. Standard form puts the highest power first. Ascending order is convenient in code because index
iis exactly the exponenti.
The degree of a nonzero polynomial is the index of its last nonzero entry. For [2, 7, 5, 1] the last index is 3, so the degree is 3.
Addition: combine like terms by position
Like terms have the same power of x. In a coefficient list, like terms sit at the same index. Adding two polynomials therefore means adding the two lists position by position.
The only complication is length. If p has degree 2 and q has degree 4, the lists have different lengths. Missing high-order terms are zeros, so you pad the shorter list with zeros before adding.
def add(p, q):
# Coefficients are listed from the constant term upward: [1, 2, 3] means 1 + 2x + 3x^2.
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)]
p = [1, 2, 3] # 3x^2 + 2x + 1
q = [5, -4, 1] # x^2 - 4x + 5
print(add(p, q)) # [6, -2, 4] -> 4x^2 - 2x + 6Check index by index. The constants give 1 + 5 = 6. The x terms give 2 + (-4) = -2. The x^2 terms give 3 + 1 = 4. This is the same like-term bookkeeping you did by hand, with the alignment handled by the index.
Padding creates new lists (p + [...] does not change the original), so the caller's lists stay unchanged. That is a useful property to keep.
Subtraction: negate, then add
Subtracting a polynomial means distributing the negative sign over every term of the second polynomial. A common hand error is to negate only the first term. The code version cannot make that mistake, because it negates every coefficient in one comprehension and then reuses add.
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(subtract(p, q)) # [-4, 6, 2] -> 2x^2 + 6x - 4Work through it. Negating q gives [-5, 4, -1]. Adding to p gives [1 - 5, 2 + 4, 3 - 1] = [-4, 6, 2]. Note that the x coefficient was -4 in q, and subtracting a negative gave +4. That is the sign change students most often miss.
Multiplication: every pair of terms
Multiplication uses the distributive property and the product rule for exponents. Each term a*x^i of the first polynomial multiplies each term b*x^j of the second. The product is a*b*x^(i+j). So the pair contributes a*b to the coefficient at index i + j.
That sentence is the whole algorithm. Several pairs can land on the same index, and those are like terms, so their contributions add.
def multiply(p, q):
# Each pair of terms a*x^i and b*x^j contributes a*b to the coefficient of x^(i+j).
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])) # (x + 2)(x^2 + 3x + 1) -> [2, 7, 5, 1], i.e. x^3 + 5x^2 + 7x + 2
print(multiply([-3, 1], [3, 1])) # (x - 3)(x + 3) -> [-9, 0, 1], i.e. x^2 - 9Why the result has length `len(p) + len(q) - 1`
If p has degree m, its list has m + 1 entries. If q has degree n, its list has n + 1 entries. The highest possible index is m + n, so the result needs m + n + 1 entries. That equals (m + 1) + (n + 1) - 1. This matches the degree rule from earlier in the tutorial: the degree of a product is the sum of the degrees.
Tracing the first example
Multiply [2, 1] (x + 2) by [1, 3, 1] (x^2 + 3x + 1). The result starts as [0, 0, 0, 0].
| i, a | j, b | Index i + j | Added a*b | Result after |
|---|---|---|---|---|
| 0, 2 | 0, 1 | 0 | 2 | [2, 0, 0, 0] |
| 0, 2 | 1, 3 | 1 | 6 | [2, 6, 0, 0] |
| 0, 2 | 2, 1 | 2 | 2 | [2, 6, 2, 0] |
| 1, 1 | 0, 1 | 1 | 1 | [2, 7, 2, 0] |
| 1, 1 | 1, 3 | 2 | 3 | [2, 7, 5, 0] |
| 1, 1 | 2, 1 | 3 | 1 | [2, 7, 5, 1] |
Index 1 and index 2 each received two contributions. That is the like-term combining step, and in the code it happens automatically through +=. You get the FOIL pattern for free when both inputs have two entries, and the same loop works unchanged for any sizes.
Zeros inside the list
The second example shows a result with a zero in the middle. (x - 3)(x + 3) gives [-9, 0, 1]. The cross terms 3x and -3x cancel, leaving 0 at index 1. The zero must stay, because it holds the place of the x term.
Checking with substitution
By hand, you check an expansion by choosing a value for x and evaluating both sides. The same check works in code. The function evaluate computes c * x**i for each coefficient and sums them.
def evaluate(p, x):
return sum(c * x**i for i, c in enumerate(p))
factor_a = [2, 1] # x + 2
factor_b = [1, 3, 1] # x^2 + 3x + 1
product = [2, 7, 5, 1] # x^3 + 5x^2 + 7x + 2
x = 2
print(evaluate(factor_a, x) * evaluate(factor_b, x)) # 44
print(evaluate(product, x)) # 44At x = 2, the factors give 4 and 11, and 4 * 11 = 44. The expanded polynomial gives 2 + 14 + 20 + 8 = 44. The two sides agree.
What the check can and cannot show
Agreement at one value does not prove the expansion is correct. A wrong answer can still match at a particular x. For example, at x = 0 any polynomial returns its constant term, so a check at 0 says nothing about the other coefficients. At x = 1 the result is the sum of all coefficients, so errors that swap two coefficients go unseen.
Practical advice:
- Test at several values, such as 2, 3, and -1.
- Avoid 0 and 1 as the only test points.
- Two polynomials of degree at most
dthat agree at more thanddistinct values must be identical. A product of degrees 1 and 2 has degree 3, so agreement at four distinct values is a proof, not just evidence.
You can turn this into a short test loop.
def check_product(p, q, result, points=(-2, -1, 2, 3, 5)):
return all(
evaluate(p, x) * evaluate(q, x) == evaluate(result, x)
for x in points
)
print(check_product([2, 1], [1, 3, 1], multiply([2, 1], [1, 3, 1]))) # True
print(check_product([2, 1], [1, 3, 1], [2, 7, 5, 2])) # FalseThe first call uses five distinct points, which is more than the degree 3, so True confirms the product. The second call changes the leading coefficient to 2, and the check fails.
Common errors
- Forgetting zero placeholders. Writing
x^2 - 9as[-9, 1]meansx - 9. Always include the 0. - Mixing orders. If one list is ascending and another descending,
addsilently returns nonsense. Pick one order for the whole program. - Trailing zeros.
add([1, 2], [3, -2])returns[4, 0], which represents the constant 4 but has length 2. The list is still correct as a polynomial. If you compute degree aslen(p) - 1, you get 1 instead of 0. Strip trailing zeros before reading the degree. - Mutating inputs. Using
p.extend(...)to pad would change the caller's list. Thep + [0] * ...form avoids this. - Wrong result size in multiplication. Using
max(len(p), len(q))for the result raises anIndexErroror drops terms. The size islen(p) + len(q) - 1.
Here is a helper that fixes the trailing zero problem.
def trim(p):
# Remove zeros at the high-degree end, but keep at least one entry.
while len(p) > 1 and p[-1] == 0:
p = p[:-1]
return p
def degree(p):
p = trim(p)
if p == [0]:
return None # the zero polynomial has no defined degree
return len(p) - 1
print(trim([4, 0])) # [4]
print(degree([4, 0])) # 0
print(degree([2, 7, 5, 1])) # 3
print(degree([0, 0])) # NoneThe zero polynomial is a special case. It has no nonzero term, so its degree is usually left undefined, and the helper reflects that by returning None.
Limits of the approach
The double loop in multiply does len(p) * len(q) multiplications. For small polynomials this is fine. For lists with thousands of entries, faster methods exist, such as the Karatsuba algorithm or the fast Fourier transform. You do not need them for the hand-sized problems in this tutorial. The representation also assumes a single variable. Polynomials with several variables need a different structure, for example a dictionary from exponent tuples to coefficients.
Exercise
Using the functions from this chapter, compute (2x^2 - x + 3) - (x^2 + 4x - 1) and then multiply (x - 2) by (x^2 + 2x + 4). Give both results as coefficient lists in ascending order, and say what the second result represents.
Show answer
The first polynomial is [3, -1, 2] and the second is [-1, 4, 1]. subtract gives [3 - (-1), -1 - 4, 2 - 1] = [4, -5, 1], which is x^2 - 5x + 4. For the product, (x - 2) is [-2, 1] and (x^2 + 2x + 4) is [4, 2, 1]. The result has length 2 + 3 - 1 = 4. Index 0: -24 = -8. Index 1: -22 + 14 = 0. Index 2: -21 + 12 = 0. Index 3: 11 = 1. The result is [-8, 0, 0, 1], which represents x^3 - 8, a difference of cubes.
Exercise
The call add([1, 2], [3, -2]) returns [4, 0]. Why is that a correct sum, and what should you do before reading its degree?
Show answer
Adding index by index gives 1 + 3 = 4 and 2 + (-2) = 0, so the sum is 4 + 0x, which equals the constant 4. The list is correct but has a trailing zero. Strip trailing zeros (for example with trim) before computing the degree, so the degree is 0 and not len(p) - 1 = 1.
Exercise
You expand (x + 1)(x^2 + 1) and get [1, 1, 1, 1]. A friend checks the answer only at x = 1 and says it is confirmed. Is the check enough? Which x values would give a conclusive test, and how many do you need?
Show answer
The expansion is correct here, but the check at x = 1 alone is not enough as a method. At x = 1 the value is the sum of the coefficients, so many wrong lists (such as [2, 0, 1, 1] or [1, 1, 1, 1] with two entries swapped) also give 4 on the right side and 2 * 2 = 4 on the left. The product has degree 3, so agreement at four distinct values proves the two polynomials are identical. For example, test x = -1, 0, 2, and 3, using evaluate on both the factors and the result.