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.
If M = 4 and for polynomial A
For power 0, co-efficient is 5
For power 1, co-efficient is 0
For power 2, co-efficient is 10
For power 3, co-efficient is 6.
Then polynomial A represents "6x^3 + 10x^2 + 5", the polynomial B represents "4x^2 + 2x + 1" and the addition of A and B is "6x^3 + 14x^2 + 2x + 6"
sampel input 1
4
0 5
1 0
2 10
3 6
3
0 1
1 2
2 4
output
6x^3 + 14x^2 + 2x + 6
samplel input 2
5
0 -2
3 6
4 7
1 -3
2 -1
5
0 1
1 2
2 -4
3 3
4 5
output
12x^4 + 9x^3 - 5x^2 - x - 1
def get_polynomial():
n = int(input())
polynomial=[0 for i in range(n)]
for i in range(0,n):
Pj,Cj = input().split(' ')
polynomial[int(Pj)] = int(Cj)
return polynomial
def calculate_sum(A,B):
if(len(A)>=len(B)):
sum_pol=[0 for i in range(len(A))]
for i in range(0,len(A)):
if(i>=len(B)):
B.append(0)
sum_pol[i]=A[i]+B[i]
return sum_pol
return -1
A=get_polynomial()
B=get_polynomial()
sum_pol=calculate_sum(A,B)
if(sum_pol==-1):
sum_pol=calculate_sum(B,A)
if(sum(sum_pol)!=0):
for i in range(len(sum_pol)-1,0,-1):
if sum_pol[i] != 0:
if i!=1:
if sum_pol[i]>0:
if i==len(sum_pol)-1:
if sum_pol[i]<0:
sum_pol[i]=-1*sum_pol[i]
print (f' - {sum_pol[i]}x^{i}',end='')
else:
if sum_pol[i]==1:
print (f'x^{i}',end='')
else:
print (f'{sum_pol[i]}x^{i}',end='')
else:
print (f' + {sum_pol[i]}x^{i}',end='')
else:
if sum_pol[i]!=-1:
if sum_pol[i]<0:
sum_pol[i]=-1*sum_pol[i]
print (f' - {sum_pol[i]}x^{i}',end='')
else:
print (f'{sum_pol[i]}x^{i}',end='')
else:
print (f' - x^{i}',end='')
else:
if sum_pol[i]>0:
print (f' + {sum_pol[i]}x',end='')
else:
if sum_pol[i]!=-1:
if sum_pol[i]<0:
sum_pol[i]=-1*sum_pol[i]
print (f' - {sum_pol[i]}x',end='')
else:
print (f'{sum_pol[i]}x',end='')
else:
if sum_pol[i]<0:
print (f' - x',end='')
else:
print (f' + x',end='')
if sum_pol[0]<0:
sum_pol[0]=-1*sum_pol[0]
print (f' - {sum_pol[0]}',end='')
else:
print (f' + {sum_pol[0]}',end='')
else:
print(str(sum_pol[0]))
Comments
Leave a comment