Add two polynomials
Given two polynomials A and B, write a program that adds the given two polynomials A and B.
Output format:-
For the term where power is 1 represent it as C1x instead of C1x^1.
If the degree of polynomial is zero and the constant term is also zero, then just print 0 to represent the polynomial.
For term Cix^Pi, if the coefficient of the term Ci is 1, simply print x^Pi instead of 1x^Pi.
Sample Input
5
0 -2
3 6
4 7
1 -3
2 -1
5
0 1
1 2
2 -4
3 3
4 5
Sample Output
12x^4 + 9x^3 - 5x^2 - x - 1
Sample input
4
0 5
1 0
2 10
3 6
4
0 -5
1 0
2 -10
3 -6
Sample Output
0
Sample Input
5
0 2
1 0
2 1
4 7
3 6
5
2 4
3 3
4 5
0 1
1 0
Sample Output
12x^4 + 9x^3 + 5x^2 + 3
# Add two polynomials
def read_pol():
n = int(input())
pol = {}
for i in range(n):
L = input().split()
Pi = int(L[0])
Ci = int(L[1])
pol[Pi] = Ci
return pol
def add_pol(pol1, pol2):
res = {}
for Pi in pol1:
res[Pi] = pol1[Pi]
for Pi in pol2:
if Pi in res:
res[Pi] += pol2[Pi]
else:
res[Pi] = pol2[Pi]
return res
def print_pol(pol):
first = True
for Pi in sorted(pol, reverse=True):
Ci = pol[Pi]
if first:
if Ci == 0 and Pi == 0:
print('0', end='')
break
if Ci == 1 and Pi != 0:
pass
elif Ci == -1 and Pi != 0:
print('-', end='')
if Ci == 0:
continue
else:
print(f'{Ci}', end='')
first = False
else:
if Ci > 0:
print(' + ', end='')
elif Ci < 0:
print(' - ', end='')
else:
continue
if abs(Ci) != 1 or Pi == 0:
print(f'{abs(Ci)}', end='')
if Pi == 0:
continue
print('x', end='')
if Pi != 1:
print(f'^{Pi}', end='')
print()
pol1 = read_pol()
pol2 = read_pol()
pol3 = add_pol(pol1, pol2)
print_pol(pol3)
Comments
Leave a comment