Given two polynomials A and B, write a program that adds the given two polynomials A and B.\
input:
4
0 5
1 0
2 10
3 6
3
0 1
1 2
2 4
output:
6x^3 + 14x^2 + 2x + 6
A = {}
An = int(input())
p = 0
for i in range(An):
row = input().split(' ')
A[int(row[0])] = int(row[1])
p = max(p, int(row[0]))
B = {}
Bn = int(input())
for i in range(Bn):
row = input().split(' ')
B[int(row[0])] = int(row[1])
p = max(p, int(row[0]))
polynom = ''
for i in range(p,-1,-1):
aa = A[i] if i in A else 0
bb = B[i] if i in B else 0
if (aa + bb) != 0:
if (aa + bb) < 0:
if len(polynom) > 0:
polynom = polynom + "-"
else:
polynom = polynom + " - "
elif len(polynom) > 0:
polynom = polynom + " + "
polynom = polynom + str(aa + bb)
if i > 0:
polynom = polynom + 'x'
if i > 1:
polynom = polynom + "^" + str(i)
print(polynom)
Comments
Leave a comment