# 5 Best Ways to Subtract One Polynomial from Another in Python

Rate this post

π‘ Problem Formulation: When working with polynomials in Python, one might encounter the need to perform basic arithmetic operations, such as subtraction. If we have two polynomials, say `P(x) = 3x^2 + 2x + 1` and `Q(x) = x^2 + x`, the goal is to find the resulting polynomial after subtraction, which in this case should be `R(x) = 2x^2 + x + 1`.

## Method 1: Using Numpy’s poly1d Class

The `numpy` library provides a method for creating polynomial objects using the `poly1d` class. These polynomial objects can be directly subtracted in an intuitive manner that resembles algebraic operations. This method requires the `numpy` library to be installed.

Here’s an example:

```import numpy as np

P = np.poly1d([3, 2, 1])
Q = np.poly1d([1, 1, 0])
R = P - Q

print(R)```

Output:

```   2
2 x + 1 x + 1```

This code snippet demonstrates the subtraction of two polynomials created with `numpy`‘s `poly1d` class. It succinctly performs the subtraction operation using the `-` operator and results in the expected polynomial `R(x)`.

## Method 2: Using the sympy Library

For symbolic mathematics, the `sympy` library is an ideal choice. This library provides tools for algebraic operations on polynomials, including subtraction, with exact symbolic representations. The `sympy` library is particularly useful for higher-level mathematical operations or when an exact symbolic answer is required.

Here’s an example:

```from sympy import symbols
from sympy import expand

x = symbols('x')
P = 3*x**2 + 2*x + 1
Q = x**2 + x
R = expand(P - Q)

print(R)```

Output:

`2*x**2 + x + 1`

This snippet utilizes the `sympy` library to define polynomials as symbolic expressions and then subtracts them. The `expand` function is used to ensure the resulting polynomial is simplified.

## Method 3: List-based Coefficient Subtraction

A more manual way of subtracting polynomials is by representing them as lists of coefficients and then subtracting these lists element-wise. This method does not require any external libraries but requires careful handling of the lists, especially when polynomials are of different degrees.

Here’s an example:

```P_coef = [3, 2, 1]  # Coefficients of P(x) = 3x^2 + 2x + 1
Q_coef = [1, 1, 0]  # Coefficients of Q(x) = x^2 + x

R_coef = [p - q for p, q in zip(P_coef, Q_coef)]

print(R_coef)```

Output:

`[2, 1, 1]`

In this approach, we zip the coefficient lists `P_coef` and `Q_coef` together and subtract the elements pairwise, creating a new list `R_coef` that represents the coefficients of the resulting polynomial.

## Method 4: Using the Polynomial Class of numpy

The `numpy` library also provides a `Polynomial` class under its `numpy.polynomial` module. This class handles polynomial operations and can be a more robust option than using `poly1d`, especially with future library support in mind.

Here’s an example:

```from numpy.polynomial import Polynomial

P = Polynomial([1, 2, 3])  # Polynomials are input with coefficients in ascending order
Q = Polynomial([0, 1, 1])
R = P - Q

print(R)```

Output:

`Polynomial([ 1.,  1.,  2.], domain=[-1,  1], window=[-1,  1])`

This snippet makes use of numpy’s `Polynomial` class to handle polynomials as first-class objects. The subtraction utilizes the β-β operator, and the result is printed in a representation that includes coefficients, domain, and window.

## Bonus One-Liner Method 5: Using List Comprehension and zip with Padding

To subtract polynomials of potentially different degrees in one line, you can use list comprehension along with `zip_longest` from the `itertools` module to handle the lists of coefficients, padding shorter polynomials with zeros as necessary.

Here’s an example:

```from itertools import zip_longest

P_coef = [3, 2, 1]
Q_coef = [1, 1]
R_coef = [p - q for p, q in zip_longest(P_coef, Q_coef, fillvalue=0)]

print(R_coef)```

Output:

`[2, 1, 1]`

This compact solution uses list comprehension to subtract element-wise. `zip_longest` pairs elements, padding with zeroes wherever the lists have different lengths, ensuring proper subtraction without explicit pre-processing of coefficient lists.

## Summary/Discussion

• Method 1: Numpy’s poly1d. Straightforward and clean syntax. Might not be suitable for symbolic algebra or polynomials with non-integer coefficients.
• Method 2: sympy Library. Provides exact symbolic results. Might be overkill for simple numerical operations and has additional overhead compared to other methods.
• Method 3: List-based Coefficient Subtraction. No external libraries needed. Can be error-prone and requires manual handling of lists of different lengths.
• Method 4: numpy Polynomial Class. Robust and future-proof method within numpy. Slightly more complex syntax due to object’s representation containing additional information.
• Method 5: One-Liner with zip_longest. Quick and concise. Might be less readable for those not familiar with `itertools` or complex list operations.