Given two polynomials A and B, write a program that adds the given two polynomials A and B.Input
The first line contains a single integer M.
Next M lines contain two integers Pi, Ci separated with space, where Pi denotes power and Ci denotes co-efficient of Pi for polynomial A.
After that next line contains a single integer N.
Next N lines contain two integers Pj, Cj separated with space, where Pj denotes power and Cj denotes co-efficient of Pj for polynomial B.Output
Print the addition of polynomials A and B.
The format for printing polynomials is: Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0, where Pi's are powers in decreasing order, Ci is co-efficient and C0 is constant, there will be space before and after the plus or minus sign.
If co-efficient is zero then don't print the term.
If the term with highest degree is negative, the term should be represented as -Cix^Pi.
p = []
l = 'N '
j = 'i'
for i in range(2):
while True:
try:
N = int(input(l))
break
except ValueError:
print(l + 'must be integer')
continue
k = 0
while k < N:
try:
power, coef = input(f'p{j} c{j} ').split()
power, coef = int(power), int(coef)
except ValueError:
continue
flag = True
for i in range(len(p)):
if p[i][0] == power:
p[i][1] += coef
flag = False
break
if flag:
p.append([power, coef])
k += 1
l = 'M '
j = 'j'
p = sorted(p, reverse=True, key=lambda k : k[0])
res = ''
if len(p) == 0:
print(0)
else:
f = True
for el in p:
if el[1] == 0:
continue
if el[1] < 0:
if f:
res += '-'
else:
res += ' - '
else:
if not f:
res += ' + '
f = False
if (abs(el[1]) == 1) and el[0] == 0:
res += '1'
continue
if abs(el[1]) != 1:
res += str(abs(el[1]))
if el[0] < 0:
res += 'x^({})'.format(el[0])
elif el[0] == 1:
res += 'x'
elif el[0] > 0:
res += 'x^{}'.format(el[0])
if len(res) == 0:
print('0')
else:
print(res)
Comments
Leave a comment