Answer to Question #233875 in Python for Lovely

Question #233875

Add two polynomials


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


Input


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.

Please provide me a correct answer


1
Expert's answer
2021-09-06T23:58:20-0400
# output format wasn't specified in the task
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)
print(output.lstrip('+'))

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