Add two polynomialsGiven two polynomials A and B, write a program that adds the giventwo polynomials A and B
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 read_polynom():
n = int(input())
p = {}
for i in range(n):
L = input().split()
Pi = int(L[0])
Ci = int(L[1])
p[Pi] = Ci
return p
def add_polynomilas(p, q):
r = {}
Pis = set(p).union(q)
for Pi in Pis:
if Pi in p:
Ci = p[Pi]
else:
Ci = 0.0
if Pi in q:
Ci += q[Pi]
if Ci != 0.0:
r[Pi] = Ci
return r
def tostring_polynom(p):
res = ''
first = True
for Pi in sorted(p, reverse=True):
Ci = p[Pi]
if first:
if Ci == 0 and Pi == 0:
return '0'
if Ci == 1 and Pi != 0:
pass
elif Ci == -1 and Pi != 0:
res = '-'
else:
res = f'{Ci}'
first = False
else:
if Ci > 0:
res += ' + '
elif Ci < 0:
res += ' - '
else:
continue
res += f'{abs(Ci)}'
if Pi == 0:
continue
if Pi == 1:
res += 'x'
else:
res += f'x^{Pi}'
return res
def main():
p = read_polynom()
q = read_polynom()
r = add_polynomilas(p, q)
print(f'Add {tostring_polynom(p)} to {tostring_polynom(q)}')
print(f'results {tostring_polynom(r)}')
if __name__ == '__main__':
main()
Comments
Leave a comment