Given two polynomials A and B, write a program that adds the given two polynomials A and B.
pol = dict()
for _ in range(2):
n = int(input('N: '))
for _ in range(n):
p, c = [int(x) for x in input('P, C: ').split()]
if p in pol:
pol[p] += c
else:
pol[p] = c
output = ''
for p in sorted(pol, reverse=True):
if pol[p] < 0:
if output:
output += ' - '
else:
output += '-'
elif pol[p] > 0:
if output:
output += ' + '
else:
pass
elif pol[p] == 0:
continue
if pol[p] != 1:
output += str(abs(pol[p]))
elif pol[p] == 1 and p == 0:
output += '1'
continue
if p < 0:
output += f'x^({p})'
elif p == 1:
output += 'x'
elif p > 0:
output += f'x^{p}'
print(output)
Comments
Leave a comment