Answer to Question #176089 in Python for CHANDRASENA REDDY CHADA

Question #176089

Add two polynomials

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


Sample Input

4

0 5

1 0

2 10

3 6

3

0 1

1 2

2 4

Sample Output

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


Sample input

4

0 5

1 0

2 10

3 6

4

0 -5

1 0

2 -10

3 -6

Sample Output



Sample Input

5

0 2

1 0

2 1

4 7

3 6

5

2 4

3 3

4 5

0 1

1 0

Sample Output

12x^4 + 9x^3 + 5x^2 + 3


1
Expert's answer
2021-03-28T13:25:31-0400
def main():
    A=getPolynomial()
    B=getPolynomial()
    sumAB=calculateSum(A,B)
    displaySum(sumAB)
    
#This function allows to read the power and the coefficient of the polynomial
def getPolynomial():
    N = int(input())
    polynomial=[0 for i in range(N)]
    for i in range(0,N):
        pi,ci = input().split(' ')
        polynomial[int(pi)] = int(ci)
    return polynomial
#This function allows to add the given two polynomials A and B.
def calculateSum(A,B):
    if(len(A)>=len(B)):
        sumAB=[0 for i in range(len(A))]
        for i in range(0,len(A)):
            if(i>=len(B)):
                B.append(0)
            sumAB[i]=A[i]+B[i]
        return sumAB


    return -1
#This function allows to display sum of the given two polynomials A and B.
def displaySum(sumAB):
    if(sumAB==-1):
        sumAB=calculateSum(B,A)
    
    if(sum(sumAB)!=0):
        for pi in range(len(sumAB)-1,0,-1):
            if sumAB[pi] != 0:
                if pi!=1:
                    print (f'{sumAB[pi]}x^{pi} + ',end='')
                else:
                    print (f'{sumAB[pi]}x + ',end='')
        
        print(sumAB[0])
    else:
        print(str(sumAB[0]))
    
main()

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