Add two polynomials
Given two polynomials A and B, write a program that adds the given two polynomials A and B
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.
If the degree of polynomial is zero and the constant term is also zero, then just print 0 to represent the polynomial.
For term Cix^Pi, if the coefficient of the term Ci is 1, simply print x^Pi instead of 1x^Pi.Explanation
Sample Input
6
0 -20
1 23
2 30
3 19
4 6
5 17
9
0 -100
5 -89
6 -20
7 -1
1 20
2 4
3 99
4 -45
8 12
Sample Output
12x^8 - x^7 - 20x^6 - 72x^5 - 39x^4 + 118x^3 + 34x^2 + 43x - 120
def main():
polynomialA=readPolynomial()
polynomialB=readPolynomial()
sumPolynomialAB=computeSumPolynomialAB(polynomialA,polynomialB)
printSumPolynomialAB(sumPolynomialAB,polynomialA,polynomialB)
def readPolynomial():
N = int(input())
polynomial=[0 for i in range(N)]
for i in range(0,N):
pi,ci = input().split(' ')
polynomial[int(pi)] = int(ci)
return polynomial
def computeSumPolynomialAB(polynomialA,polynomialB):
if(len(polynomialA)>=len(polynomialB)):
sumPolynomialAB=[0 for i in range(len(polynomialA))]
for i in range(0,len(polynomialA)):
if(i>=len(polynomialB)):
polynomialB.append(0)
sumPolynomialAB[i]=polynomialA[i]+polynomialB[i]
return sumPolynomialAB
return -1
def printSumPolynomialAB(sumPolynomialAB,polynomialA,polynomialB):
if(sumPolynomialAB==-1):
sumPolynomialAB=computeSumPolynomialAB(polynomialB,polynomialA)
if(sum(sumPolynomialAB)!=0):
for index in range(len(sumPolynomialAB)-1,0,-1):
if sumPolynomialAB[index] != 0:
if index!=1:
if sumPolynomialAB[index]>0:
if index==len(sumPolynomialAB)-1:
print (f'{sumPolynomialAB[index]}x^{index}',end='')
else:
print (f'+{sumPolynomialAB[index]}x^{index}',end='')
else:
if sumPolynomialAB[index]!=-1:
print (f'{sumPolynomialAB[index]}x^{index}',end='')
else:
print (f'-x^{index}',end='')
else:
if sumPolynomialAB[index]>0:
print (f'+{sumPolynomialAB[index]}x',end='')
else:
if sumPolynomialAB[index]!=-1:
print (f'{sumPolynomialAB[index]}x',end='')
else:
print (f'x',end='')
print(sumPolynomialAB[0])
else:
print(str(sumPolynomialAB[0]))
main()
Comments
Leave a comment