Add two polynomials
Given two polynomials A and B, write a program that adds the given two polynomials A and 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
Sample Input 1:-
6
0 -20
1 23
2 30
3 19
4 6
5 17
9
0 -100
5 -89
6 -20
7 -1
1 20
2 4
3 99
4 -45
8 12
Sample Output 1:-
12x^8 - x^7 - 20x^6 - 72x^5 - 39x^4 + 118x^3 + 34x^2 + 43x - 120
Note :- Need Space between - and + operators
Sample Input 2:-
4
0 5
1 0
2 10
3 6
3
0 1
1 2
2 4
Sample Output 2:-
6x^3 + 14x^2 + 2x + 6
Note:- Need Space between - and + operators
Sample Input 3:-
5
0 -2
3 6
4 7
1 -3
2 -1
5
0 1
1 2
2 -4
3 3
4 5
Sample Output 3:-
12x^4 + 9x^3 - 5x^2 - x - 1
Note:- Need Space between - and + operators
print('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')
print('Example: sample input is given below:')
print(""
"4 \n"
"0 5 \n"
"1 0 \n"
"2 10 \n"
"3 6 \n")
print("3 \n"
"0 1 \n"
"1 2 \n"
"2 4 \n")
print("Sample Output 6x^3 + 14x^2 + 2x + 6")
print('-------------------------------------------------------------')
# Number of terms in the polynomial
print('Total number of terms in polynomial')
n = int(input('Enter the cofficient of the polynomials in following with terms'))
polinomial_A =[0 for item in range(n)]
for item in range(n):
p, c = input('Enter separated by space Pi and Ci ').split(' ')
polinomial_A[int(p)] = int(c)
m = int(input('Enter the cofficient of the polynomials in following with terms'))
polinomial_B =[0 for item in range(m)]
print('Enter the data of the polynomial B')
for item in range(m):
p, c = input('Enter separated by space Pi and Ci ').split(' ')
polinomial_B[int(p)] = int(c)
# define references to polynomials of greater and lesser length
pol_max , pol_min = polinomial_A , polinomial_B
if len(pol_min) > len(pol_max):
pol_max , pol_min = polinomial_B , polinomial_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