Polynomial Multiplication in Python

In this tutorial, we are going to learn how to multiply two polynomials in Python.

Polynomial Multiplication

Let’s consider two polynomials P, Q. Where P is 2+3x^1+4x^3 and Q is 1+2x^1+4x^2+5x^3. The product of the polynomials P and Q is 2+7x^1+14x^2+26x^3+23x^4+16x^5+20x^6.

The product of two polynomials is the multiplication of every term of the first polynomial with every term in the second polynomial. For instance, let’s the length of the polynomial P, Q is m, n respectively.

Approach

1) Firstly create a result array of size m+n-1 which stores the result.

2) Secondly, initialize all the values in result[] to 0.

3) Multiply every element in polynomial P with every element in polynomial Q
result[i+j] = result[i+j]+P[i]*Q[j]

4) return the result

def polynomial_multiplication(P, Q):
    m = len(P)
    n = len(Q)
    result = [0]*(m+n-1)
    for i in range(m):
        for j in range(n):
            result[i+j] += P[i]*Q[j]

    return result

# function that print polynomial
def polynomial(poly):
    n = len(poly)
    for i in range(n): 
        print(poly[i], end = "")
        if (i != 0): 
            print("x^", i, end = "") 
        if (i != n - 1): 
            print(" + ", end = "")

# polynomial in array representation
P = [2, 3, 0, 4]
print("First polynomial is:")
polynomial(P)
print('\n')
Q = [1, 2, 4, 5]
print("Second polynomial is: ")
polynomial(Q)
print('\n')
result = (polynomial_multiplication(P, Q))
print("Product of polynomials is: ")
polynomial(result)

Output

First polynomial is:
2 + 3x^ 1 + 0x^ 2 + 4x^ 3

Second polynomial is: 
1 + 2x^ 1 + 4x^ 2 + 5x^ 3

Product of polynomials is: 
2 + 7x^ 1 + 14x^ 2 + 26x^ 3 + 23x^ 4 + 16x^ 5 + 20x^ 6

Also, read

2 responses to “Polynomial Multiplication in Python”

  1. Sam says:

    –Hi
    Can you get rid of the space between “^” and the degree that follows it?
    For example: “x^3” instead of “x^ 3”
    Thanks.
    –Sam

  2. Bruce says:

    def poly_str(arr):
    “”” string representation of polynomial.
    arr are the coefficients from high to low order.
    “””
    n = len(arr)
    res = “”
    for i in range(n):
    v = arr[i]

    # catch the leading negative sign
    if i == 0:
    if v < 0:
    res = "-"
    else:
    # separating sign
    if v < 0:
    res += " – "
    else:
    res += " + "

    p = n-i-1
    if p == 0:
    # constant term
    res += f"{abs(v)}"
    elif p == 1:
    # x term
    if v == 1:
    res += f"x"
    else:
    res += f"{abs(v)} x"
    else:
    # other x ** p terms
    if v == 1:
    res += f"x**{p}"
    else:
    res += f"{abs(v)} x**{p}"

    return res

Leave a Reply

Your email address will not be published.