Given two polynomials A and B, write a program that adds the given two polynomials A and B.Input
The first line contains a single integer M.
Next M lines contain two integers Pi, Ci separated with space, where Pi denotes power and Ci denotes co-efficient of Pi for polynomial A.
After that next line contains a single integer N.
Next N lines contain two integers Pj, Cj separated with space, where Pj denotes power and Cj denotes co-efficient of Pj for polynomial B.Output
Print the addition of polynomials A and B.
The format for printing polynomials is: Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0, where Pi's are powers in decreasing order, Ci is co-efficient and C0 is constant, there will be space before and after the plus or minus sign.
If co-efficient is zero then don't print the term.
if sum of polynomials is zero the output will be "0",
if "1" is the co-efficeint in sum of polynomials then neglect "1" in output
def add_polynomial(polynomial_A, polynomial_B,x,y):
size = max(x,y)
summation = [0 for row in range(size)]
for n in range(0,x, 1):
summation[n] = polynomial_A[n]
for n in range(y):
summation[n] += polynomial_B[n]
return summation
def polynomial_display(polyno, a):
for col in range(a):
print(polyno[col], end= " ")
if (col != 0):
print("x^", col, end=" ")
if (col != a - 1):
print(" + ", end= " ")
R = []
T = []
m = int(input("Enter the size of the first polynomial\t"))
n = int(input("Enter the size of the second polynomial\t"))
print("The elements of the second polynomial\t")
for element in range(m):
x, y = input("Enter the power and coefficient and separate them with space\t").split(' ')
R.append(int(y))
print("The elements of the second polynomial\t")
for element in range(n):
x, y = input("Enter power and coefficient and separate them with space\t").split(' ')
T.append(int(y))
print("First polynomial is")
polynomial_display(R, m)
print("Second polynomial is")
polynomial_display(T,n)
print("\n", end=" ")
sum = add_polynomial(R, T, m, n)
size = max(m,n)
print("Sum polynomial is" )
#Importing numpy to display the result of adding polynomial
import numpy as np
p = np.poly1d(sum)
print(p)
Comments
Leave a comment