Answer to Question #200419 in Python for varun

Question #200419

Add two polynomials

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 of poly A

After that next line contains a single integer N.

Next N lines contain two integers Pj, Cj of poly B


Output


Print the addition of poly's A and B.

The format for printing polynomials is: Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0, where Pi's are powers in decreasing order, Ci is co-efficient and C0 is constant, there will be space before and after the plus or minus sign.

If co-eff is zero then don't print the term.

If the term with highest degree is negative, the term should be represented as -Cix^Pi.

For the term where power is 1 represent it as C1x instead of C1x^1.

If the degree of poly is zero and the constant term is also zero, then just print 0 to represent the poly.

For term Cix^Pi, if the coefficient of the term Ci is 1, simply print x^Pi instead of 1x^Pi.


Sample input

4

0 5

1 0

2 10

3 6

4

0 -5

1 0

2 -10

3 -6


Expected output



1
Expert's answer
2021-05-30T07:24:01-0400
m = int(input("Enter M: "))
dic1 = {}
for i in range(0, m):
    temp = [int(i) for i in input().split()]
    dic1[temp[0]] = dic1.get(temp[0], 0) + temp[1]
      
n = int(input("Enter N: "))
dic2 = {}
for i in range(0, n):
    temp = [int(i) for i in input().split()]
    dic2[temp[0]] = dic2.get(temp[0], 0) + temp[1]
    
# dic1 + dic2 by keys and sort
for i in dic2.keys():
    dic1[i] = dic1.get(i,0) + dic2[i]
tmp = sorted(dic1, reverse=True)


result = ''
for b in tmp:
    if dic1[b]!=0:
        result+= str(dic1[b]) + ' '
if result!='':
    print(result)
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
APPROVED BY CLIENTS