Answer to Question #258829 in Python for Raju

Question #258829

Add two Polynomials 


Given two Polynomials A and B,write a program that adds the given two Polynomials A and B.


Sample input 1

4

0 5

1 0

2 10

3 6


Sample Output 1



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


1
Expert's answer
2021-10-30T00:38:46-0400
d = {}
for i in range(2):
    for _ in range(int(input())):
        p, c = map(int, input().split())
        d[p] = d.get(p, 0) + c
output = ''
for pwr in sorted(d.keys(), reverse=True):
    if d[pwr]:
        if d[pwr] < 0:
            output += '-'
        else:
            output += '+'
        if abs(d[pwr]) != 1:
            output += str(abs(d[pwr]))
        elif not pwr:
            output += '1'
        if pwr:
            output += 'x'
            if pwr != 1:
                output += '^' + str(pwr)
if output:
    print(output.lstrip('+'))
else:
    print(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