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.
Test Case 1:-
Input:-
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
Output:-
12x^8 - x^7 - 20x^6 - 72x^5 - 39x^4 + 118x^3 + 34x^2 + 43x - 120
Note :- Need Space between - and + operators
Test Case 2:-
Input:-
4
0 5
1 0
2 10
3 6
3
0 1
1 2
2 4
Output :-
6x^3 + 14x^2 + 2x + 6
Note:- Need Space between - and + operators
Test Case 3:- Test Case 4:-
Input:- Input:-
5 4
0 -2 0 5
3 6 1 0
4 7 2 10
1 -3 3 6
2 -1 4
5 0 -5
0 1 1 0
1 2 2 -10
2 -4 3 -6
3 3 Output:-
4 5 0
Output:-
12x^4 + 9x^3 - 5x^2 - x - 1
Note:- Need Space between - and + operators
We need all 4 test cases can be came when code was run. I want exact outputs for all test cases
# 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