Add two polynomials: 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
4
0 -5
1 0
2 -10
3 -6
output:0
def add_polinom(p):
n = int(input())
for i in range(n):
pi, ci = input().split()
pi, ci = int(pi), int(ci)
if pi in p:
p[pi] += ci
else:
p[pi] = ci
return p
def polinom_to_string(p):
s = ''
flag = True
for key in p:
if p[key] == 0:
continue
if flag:
if p[key] < 0:
s += '-'
p[key] *= -1
flag = False
else:
if p[key] < 0:
s += ' - '
p[key] *= -1
elif p[key] > 0:
s += ' + '
if p[key] != 1:
s += f'{p[key]}'
if key == 0:
continue
elif key == 1:
s += 'x'
else:
s += f'x^{key}'
else:
if key == 0:
s += '1'
elif key == 1:
s += 'x'
else:
s += f'x^{key}'
if len(s) == 0:
s = '0'
return s
def sort_polinom(p):
keys = list(p.keys())
keys.sort(reverse=True)
res = {}
for el in keys:
res[el] = p[el]
return res
polinom = {}
for i in range(2):
polinom = add_polinom(polinom)
polinom = sort_polinom(polinom)
print(polinom_to_string(polinom))
Comments
Leave a comment