Add two polynomials
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.
Explanation
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"
Sample Input
4
0 5
1 0
2 10
3 6
3
0 1
1 2
2 4
Sample Output
6x^3 + 14x^2 + 2x + 6
def enter_polinom():
while True:
try:
N = int(input(''))
except:
print('enter positive integer')
continue
if N < 0:
print('enter positive integer')
continue
break
P = []
k = 0
while k < N:
try:
t = list(map(int, input('').split()))
if len(t) != 2:
print('enter two integers')
continue
k += 1
except:
print('enter two integers')
continue
add = True
for i in range(len(P)):
if P[i][0] == t[0]:
P[i][1] += t[1]
add = False
if add:
P.append(t)
return P
def add_polinoms(pol_1, pol_2):
added = []
while pol_1 or pol_2:
if pol_1:
tmp = pol_1.pop(0)
for i in range(len(pol_2)):
if pol_2[i][0] == tmp[0]:
tmp[1] += pol_2[i][1]
pol_2.pop(i)
break
else:
tmp = pol_2.pop(0)
added.append(tmp)
added.sort(reverse=True)
return(added)
def print_polinom(p):
s = ''
first = True
if len(p) == 0:
print(0)
return
elif p[0][1] < 0:
if p[0][0] == 0:
s += '{}'.format(p[0][1])
else:
if p[0][1] == -1:
if p[0][0] == 1:
s += '-x'
else:
s += '-x^{}'.format(p[0][0])
else:
if p[0][0] == 1:
s += '{}x'.format(p[0][1])
else:
s += '{}x^{}'.format(p[0][1],p[0][0])
p.pop(0)
first = False
for el in p:
if el[1] == 0:
continue
elif el[1] < 0:
s += ' - '
el[1] = -el[1]
else:
if not first:
s += ' + '
if el[0] == 0:
s += '{}'.format(el[1])
elif el[0] == 1:
s += '{}x'.format(el[1])
else:
s += '{}x^{}'.format(el[1], el[0])
first = False
print(s)
A = enter_polinom()
B = enter_polinom()
print_polinom(add_polinoms(A, B))
Comments
Leave a comment