Answer to Question #201519 in Python for sajid pasha

Question #201519

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

input:

4

0 5

1 0

2 10

3 6

3

0 1

1 2

2 4

output:

6x^3 + 14x^2 + 2x + 6





1
Expert's answer
2021-06-02T07:48:55-0400
A = {}
An =  int(input())
p = 0


for i in range(An):
   row = input().split(' ')
   A[int(row[0])] = int(row[1])
   p = max(p, int(row[0]))
B = {}
Bn =  int(input())
for i in range(Bn):
   row = input().split(' ')
   B[int(row[0])] = int(row[1])
   p = max(p, int(row[0]))


polynom = ''
for i in range(p,-1,-1):
    aa = A[i] if i in A else 0
    bb = B[i] if i in B else 0
    if (aa + bb) != 0:
        if (aa + bb) < 0:
            if len(polynom) > 0:
                polynom = polynom + "-"
            else:
                polynom = polynom + " - "
        elif len(polynom) > 0:
            polynom = polynom + " + "
        polynom = polynom + str(aa + bb)
        if i > 0:
            polynom = polynom + 'x'
            if i > 1:
                polynom = polynom + "^" + str(i)
print(polynom)

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