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.
Output
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.
sample output :
"6x^3 + 14x^2 + 2x + 6"
sample Input:
4
0 5
1 0
2 10
3 6
4
0 -5
1 0
2 -10
3 -6
sample output:
#python 3.9.5
n1 = int(input())
# input tuples of Pi and Ci first polynomial
PiCi1 = []
for i in range(n1):
l = input().split()
Pi = int(l[0])
Ci = int(l[1])
PiCi1.append((Pi, Ci))
n2 = int(input())
# input tuples of Pi and Ci second polynomial
PiCi2 = []
for i in range(n2):
l = input().split()
Pi = int(l[0])
Ci = int(l[1])
PiCi2.append((Pi, Ci))
def addpoly(p1,p2):
result = []
for i in range(len(p1)):
Pi = int(i)
Ci = p1[i][1] + p2[i][1]
result.append((Pi, Ci))
return result
final_list = addpoly(PiCi1, PiCi2)
polynomial = ''
for i in range(len(final_list)):
if (final_list[i][1] == 0):
polynomial += ''
elif (i == 0):
polynomial += str(final_list[i][1])
else:
polynomial += ' + ' + str(final_list[i][1]) + 'x^' + str(i)
if (polynomial == ''):
print('\nFihal polynomial: 0')
else:
print('\nFihal polynomial: ' + polynomial)
Comments
Leave a comment