Add two polynomials
Given two polynomials A and B, write a program that adds the given two polynomials A and 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 1:-
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 1:-
12x^8 - x^7 - 20x^6 - 72x^5 - 39x^4 + 118x^3 + 34x^2 + 43x - 120
Note :- Need Space between - and + operators
Sample Input 2:-
4
0 5
1 0
2 10
3 6
3
0 1
1 2
2 4
Sample Output 2:-
6x^3 + 14x^2 + 2x + 6
Note:- Need Space between - and + operators
def main():
A=getPolynomial()
B=getPolynomial()
sumAB=getSum(A,B)
if(sumAB==-1):
sumAB=getSum(B,A)
if(sum(sumAB)!=0):
for i in range(len(sumAB)-1,0,-1):
if sumAB[i] != 0:
if i!=1:
if sumAB[i]>0:
if i==len(sumAB)-1:
if sumAB[i]<0:
sumAB[i]=-1*sumAB[i]
print (f' - {sumAB[i]}x^{i}',end='')
else:
print (f'{sumAB[i]}x^{i}',end='')
else:
print (f' + {sumAB[i]}x^{i}',end='')
else:
if sumAB[i]!=-1:
if sumAB[i]<0:
sumAB[i]=-1*sumAB[i]
print (f' - {sumAB[i]}x^{i}',end='')
else:
print (f'{sumAB[i]}x^{i}',end='')
else:
print (f' - x^{i}',end='')
else:
if sumAB[i]>0:
print (f' + {sumAB[i]}x',end='')
else:
if sumAB[i]!=-1:
if sumAB[i]<0:
sumAB[i]=-1*sumAB[i]
print (f' - {sumAB[i]}x',end='')
else:
print (f'{sumAB[i]}x',end='')
else:
print (f'x',end='')
if sumAB[0]<0:
sumAB[0]=-1*sumAB[0]
print (f' - {sumAB[0]}',end='')
else:
print (f' + {sumAB[0]}',end='')
else:
print(str(sumAB[0]))
def getPolynomial():
totalValues = int(input())
P=[0 for i in range(totalValues)]
for i in range(0,totalValues):
Pi,Ci = input().split(' ')
P[int(Pi)] = int(Ci)
return P
def getSum(A,B):
if(len(A)>=len(B)):
sumAB=[0 for i in range(len(A))]
for i in range(0,len(A)):
if(i>=len(B)):
B.append(0)
sumAB[i]=A[i]+B[i]
return sumAB
return -1
main()
Output:
Comments
Leave a comment