Answer to Question #176090 in Python for CHANDRASENA REDDY CHADA

Question #176090

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

Should be Zero: 0


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-29T06:25:52-0400
# Polynomials addition


def polynom_input():
    N = int(input())
    A = {}
    for i in range(N):
        L = input().split()
        Pi = int(L[0])
        Ci = int(L[1])
        A[Pi] = Ci
    return A


def polynoms_add(A, B):
    C = {}


    Pis = set(list(A.keys()) + list(B.keys()))
    for Pi in Pis:
        Ci = A.get(Pi, 0) + B.get(Pi, 0)
        if Ci != 0:
            C[Pi] = Ci
    if len(C) == 0:
        C = {0:0}
    return C


def polynom_print(A):
    first = True
    for Pi in sorted(A, reverse=True):
        Ci = A[Pi]
        if first:
            if Ci == 0 and Pi == 0:
                print('0', end='')
                break
            
            if Ci == 1 and Pi != 0:
                pass
            elif Ci == -1 and Pi != 0:
                print('-', end='')
            if Ci == 0:
                continue
            else:           
                print(f'{Ci}', end='')
            first = False
            
        else:        
            if Ci > 0:
                print(' + ', end='')
            elif Ci < 0:
                print(' - ', end='')
            else:
                continue
            if abs(Ci) != 1 or Pi == 0:
                print(f'{abs(Ci)}', end='')
        
        if Pi == 0:
            continue
        print('x', end='')
        if Pi != 1:
            print(f'^{Pi}', end='')
    print()


A = polynom_input()
B = polynom_input()
C = polynoms_add(A, B)
polynom_print(C)

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