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
if we get "0" after adding two polynomials it should print "0" as output
M = int(input())
polynomialA=[0 for i in range(M)]
for i in range(0,M):
Pj,Cj = input().split(' ')
polynomialA[int(Pj)] = int(Cj)
N = int(input())
polynomialB=[0 for i in range(N)]
for i in range(0,N):
Pj,Cj = input().split(' ')
polynomialB[int(Pj)] = int(Cj)
if(len(polynomialB)<=len(polynomialA)):
polynomialsSumResult=[0 for i in range(len(polynomialA))]
for i in range(0,len(polynomialA)):
if(i>=len(polynomialB)):
polynomialB.append(0)
polynomialsSumResult[i]=polynomialA[i]+polynomialB[i]
else:
polynomialsSumResult=None
if(polynomialsSumResult==None):
if(len(polynomialA)<=len(polynomialB)):
polynomialsSumResult=[0 for i in range(len(polynomialB))]
for i in range(0,len(polynomialB)):
if(i>=len(polynomialA)):
polynomialA.append(0)
polynomialsSumResult[i]=polynomialB[i]+polynomialA[i]
if(sum(polynomialsSumResult)!=0):
for i in range(len(polynomialsSumResult)-1,0,-1):
if polynomialsSumResult[i] != 0:
if i!=1:
if polynomialsSumResult[i]>0:
if i==len(polynomialsSumResult)-1:
if polynomialsSumResult[i]<0:
polynomialsSumResult[i]=-1*polynomialsSumResult[i]
print (f' - {polynomialsSumResult[i]}x^{i}',end='')
else:
if polynomialsSumResult[i]==1:
print (f'x^{i}',end='')
else:
print (f'{polynomialsSumResult[i]}x^{i}',end='')
else:
print (f' + {polynomialsSumResult[i]}x^{i}',end='')
else:
if polynomialsSumResult[i]!=-1:
if polynomialsSumResult[i]<0:
polynomialsSumResult[i]=-1*polynomialsSumResult[i]
print (f' - {polynomialsSumResult[i]}x^{i}',end='')
else:
print (f'{polynomialsSumResult[i]}x^{i}',end='')
else:
print (f' - x^{i}',end='')
else:
if polynomialsSumResult[i]>0:
print (f' + {polynomialsSumResult[i]}x',end='')
else:
if polynomialsSumResult[i]!=-1:
if polynomialsSumResult[i]<0:
polynomialsSumResult[i]=-1*polynomialsSumResult[i]
print (f' - {polynomialsSumResult[i]}x',end='')
else:
print (f'{polynomialsSumResult[i]}x',end='')
else:
if polynomialsSumResult[i]<0:
print (f' - x',end='')
else:
print (f' + x',end='')
if polynomialsSumResult[0]<0:
polynomialsSumResult[0]=-1*polynomialsSumResult[0]
print (f' - {polynomialsSumResult[0]}',end='')
else:
print (f' + {polynomialsSumResult[0]}',end='')
else:
print(str(polynomialsSumResult[0]))
Comments
this code is for not adding two polynomials
Leave a comment