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 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):
final_dict = {}
if len(p) >= len(q):
for k,v in p.items():
final_dict[k] = v + q.get(k,0)
final_keys = list(final_dict.keys())
for k1,v1 in q.items():
if k1 not in final_keys:
final_dict[k1] = v1
else:
for k,v in q.items():
final_dict[k] = v + p.get(k,0)
final_keys = list(final_dict.keys())
for k1,v1 in p.items():
if k1 not in final_keys:
final_dict[k1] = v1
return final_dict
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()
Test Case
If M = 4 and for polynomial A
For power 0, co-efficient is 5
For power 1, co-efficient is 0
For power 2, co-efficient is 10
For power 3, co-efficient is 6.
If N = 3 and for polynomial B
For power 0, co-efficient is 1
For power 1, co-efficient is 2
For power 2, co-efficient is 4.
Then polynomial A represents "6x^3 + 10x^2 + 5", the polynomial B represents "4x^2 + 2x + 1" and the addition of A and B is "6x^3 + 14x^2 + 2x + 6"
Comments
Leave a comment