Add two polynomials
Given two polynomials A and B, write a program that adds the given two polynomials A and B
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.
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.Explanation
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
# enter dataset polinom
print('Plolinom A data entry')
n = int(input('Enter the number of N polynomial members '))
polinom_a =[0 for item in range(n)]
for item in range(n):
p, c = input('Enter separated by space Pi and Ci ').split(' ')
polinom_a[int(p)] = int(c)
m = int(input('Enter the number of M polynomial members '))
polinom_b =[0 for item in range(m)]
print('Plolinom B data entry')
for item in range(m):
p, c = input('Enter separated by space Pi and Ci ').split(' ')
polinom_b[int(p)] = int(c)
# define references to polynomials of greater and lesser length
pol_max , pol_min = polinom_a , polinom_b
if len(pol_min) > len(pol_max):
pol_max , pol_min = polinom_b , polinom_a
# add the coefficients of the polynorms in pairs
for item in range(len(pol_min)):
pol_max[item] += pol_min[item]
# result output
for item in range(len(pol_max)-1,0,-1):
if item == 0:
continue
print (f'{pol_max[item]}x^{item} + ',end='')
print(pol_max[0])
Comments
Leave a comment