Add two polynomials
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.
Input 1
4
0 5
1 0
2 10
3 6
3
0 1
1 2
2 4
output 1
6x^3 + 14x^2 + 2x + 6
input 2
4
0 5
1 0
2 10
3 6
4
0 -5
1 0
2 -10
3 -6
output2
M = int(input())
polA=[0 for i in range(M)]
for i in range(0,M):
Pj,Cj = input().split(' ')
polA[int(Pj)] = int(Cj)
N = int(input())
polB=[0 for i in range(N)]
for i in range(0,N):
Pj,Cj = input().split(' ')
polB[int(Pj)] = int(Cj)
if(len(polB)<=len(polA)):
polSum=[0 for i in range(len(polA))]
for i in range(0,len(polA)):
if(i>=len(polB)):
polB.append(0)
polSum[i]=polA[i]+polB[i]
else:
polSum=None
if(polSum==None):
if(len(polA)<=len(polB)):
polSum=[0 for i in range(len(polB))]
for i in range(0,len(polB)):
if(i>=len(polA)):
polA.append(0)
polSum[i]=polB[i]+polA[i]
if(sum(polSum)!=0):
for i in range(len(polSum)-1,0,-1):
if polSum[i] != 0:
if i!=1:
if polSum[i]>0:
if i==len(polSum)-1:
if polSum[i]<0:
polSum[i]=-1*polSum[i]
print (f' - {polSum[i]}x^{i}',end='')
else:
if polSum[i]==1:
print (f'x^{i}',end='')
else:
print (f'{polSum[i]}x^{i}',end='')
else:
print (f' + {polSum[i]}x^{i}',end='')
else:
if polSum[i]!=-1:
if polSum[i]<0:
polSum[i]=-1*polSum[i]
print (f' - {polSum[i]}x^{i}',end='')
else:
print (f'{polSum[i]}x^{i}',end='')
else:
print (f' - x^{i}',end='')
else:
if polSum[i]>0:
print (f' + {polSum[i]}x',end='')
else:
if polSum[i]!=-1:
if polSum[i]<0:
polSum[i]=-1*polSum[i]
print (f' - {polSum[i]}x',end='')
else:
print (f'{polSum[i]}x',end='')
else:
if polSum[i]<0:
print (f' - x',end='')
else:
print (f' + x',end='')
if polSum[0]<0:
polSum[0]=-1*polSum[0]
print (f' - {polSum[0]}',end='')
else:
print (f' + {polSum[0]}',end='')
else:
print(f'{polSum[0]}')
Comments
Leave a comment