Add two polynomials in Python
In this post, you will learn how to add two polynomials using the Python programming language.
Polynomials are algebraic expressions that contain indeterminates and constants. A polynomial is composed of variables, constants, and exponents that are combined using mathematical operations such as addition, subtraction, and multiplication, but we cannot perform division operations by a variable in polynomials. The exponents of the variables in a polynomial have to be non-negative integer.
Example
X3+5X2+4X+6
The power of X in each term is:
X3, X has power of 3
5X2, X has power of 2
4X, X has power of 1
6, 6 has power of 0
Python Polynomial Program
def add(A, B, m, n):
size = max(m, n);
sum = [0 for i in range(size)]
# Initialize the product polynomial
for i in range(0, m, 1):
sum[i] = A[i]
# Take ever term of first polynomial
for i in range(n):
sum[i] += B[i]
return sum
# Function to print a polynomial
def printPoly(poly, n):
for i in range(n):
print(poly[i], end = "")
if (i != 0):
print("x^", i, end = "")
if (i != n - 1):
print(" + ", end = "")
# Driver Code
if __name__ == '__main__':
# The given array represents
# polynomial 6 + 8x^2 + 2x^3
A = [6, 0, 8, 2]
# The following array represents
# polynomial 3 + 9x + 5x^2
B = [3, 9, 5]
m = len(A)
n = len(B)
print("First polynomial : ")
printPoly(A, m)
print("\n", end = "")
print("Second polynomial : ")
printPoly(B, n)
print("\n", end = "")
sum = add(A, B, m, n)
size = max(m, n)
print("Sum polynomial : ")
printPoly(sum, size)
Output of the above code:
First polynomial :
6 + 0x^ 1 + 8x^ 2 + 2x^ 3
Second polynomial :
3 + 9x^ 1 + 5x^ 2
Sum polynomial :
9 + 9x^ 1 + 13x^ 2 + 2x^ 3
Related Articles
Python program to print all even numbers between 1 to 100
Pandas DataFrame to JSON
Prettytable in Python
Count consonants in a string Python
Python split strings by comma
Count vowels in a string Python
Replace multiple characters Python
Convert array to list Python
Python loop through list
Difference between tuple and list in Python
Convert string to list Python
Remove last element from list Python
Convert list to string Python
Convert Python list to numpy array
Remove element from list Python
Python dict inside list
Check if list is empty Python
Python iterate list with index
Python iterate list with index
Python split string by comma
Printing Simple Diamond Pattern in Python
Stemming and Lemmatization in Python
Python | Generate QR Code using pyqrcode module