Answer to Question #189768 in Python for Hari nadh babu

Question #189768

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


Hint:-

We can use dictionaries to maintain polynomial coeffients and powers.


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:-

Input:-

5

0 -2

3 6

4 7

1 -3

2 -1

5

0 1

1 2

2 -4

3 3

4 5

Output:-

12x^4 + 9x^3 - 5x^2 - x - 1

Note:- Need Space between - and + operators

We need all test cases can be came when code was run


1
Expert's answer
2021-05-06T02:21:35-0400
print('Polynomial  A data')

first = int(input('Enter the number of first polynomial members: '))
pA =[0 for i in range(first)]
for i in range(first):
    Pi, Ci = input('Enter separated by space Pi and Ci:').split(' ')
    pA[int(Pi)] = int(Ci)

second = int(input('Enter the number of second polynomial members: '))
pB =[0 for i in range(second)]
print('Polynomial B data')
for i in range(second):
    Pi, Ci = input('Enter separated by space Pi and Ci:').split(' ')
    pB[int(Pi)] = int(Ci)


max_poly , min_poly = pA , pB
if len(min_poly) > len(max_poly):
    max_poly , min_poly = pB , pA

for i in range(len(min_poly)):
    max_poly[i] += min_poly[i]

for i in range(len(max_poly)-1,0,-1):
    if i == 0:
        continue
    print (f'{max_poly[i]}x^{i} + ',end='')
print(max_poly[0])

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS