Answer to Question #338834 in Python for lokesh

Question #338834

Hi, Please refer new input and output as given below. include new input also



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.

Output





Given Input:


4

0 5

1 0

2 10

3 6

4

0 -5

1 0

2 -10

3 -6


Expected Output: 0




1
Expert's answer
2022-05-09T14:55:26-0400

input:

4

0 -8

1 7

2 9

3 -8

4

0 -4

1 6

2 -10

3 8

expected output:

-12 + 13x -x^2


code:

result = list()
coffs, powers = list(), list()
for i in range(int(input())):
    power, coff = map(int, input().split())
    coffs.append(coff)
    powers.append(power)
for i in range(int(input())):
    power, coff = map(int, input().split())
    if power in powers:
        coffs[powers.index(power)] = coffs[powers.index(power)] + coff
    else:
        coffs.append(coff)
        powers.append(power)
for ind, i in enumerate(coffs):
    if i != 0:
        result.append(str(i) + 'x^' + str(powers[ind]))
result = " + ".join(result).replace('+ -', '-').replace('x^0 ', ' ').replace('x^1', 'x').replace('1x', 'x')
print(result)

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