Answer to Question #245640 in Python for prime

Question #245640

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


Input

7

0 2

1 3

2 1

5 0

3 6

4 7

6 -9

5

0 1

2 4

3 0

1 0

4 -5


Your Output : - 9x^6 + 2x^4 + 6x^3 + 5x^2 + 3x + 3
Expected: -9x^6 + 2x^4 + 6x^3 + 5x^2 + 3x + 3


I need exact output like this expected output and I want to pass each and every testcase for this program






1
Expert's answer
2021-10-03T04:01:17-0400

Source code


def readPoly():
    num = int(input())
    p1 = {}
    for i in range(num):
        num_sp = input().split()
        p = int(num_sp[0])
        c = int(num_sp[1])
        p1[p] = c
    return p1


def addPoly(p, q):
    r = {}
    Pis = set(p).union(q)
    for Pi in Pis:
        if Pi in p:
            Ci = p[Pi]
        else:
            Ci = 0.0
        if Pi in q:
            Ci += q[Pi]
        if Ci != 0.0:
            r[Pi] = Ci
    return r




def toStringPoly(p):
    result = ''
    first = True
    for Pi in sorted(p, reverse=True):
        Ci = p[Pi]
        if first:
            if Ci == 0 and Pi == 0:
                return '0'
            
            if Ci == 1 and Pi != 0:
                pass
            elif Ci == -1 and Pi != 0:
                result = '-'
            else:           
                result = f'{Ci}'
            first = False
            
        else:        
            if Ci > 0:
                result += ' + '
            elif Ci < 0:
                result += ' - '
            else:
                continue
            result += f'{abs(Ci)}'
        
        if Pi == 0:
            continue
        if Pi == 1:
            result += 'x'
        else:
            result += f'x^{Pi}'
    return result
PC1 = readPoly()
PC2 = readPoly()


final_L = addPoly(PC1, PC2)
if not final_L:
    print('Results: 0')
else:
    print(f'{toStringPoly(final_L)}')


Output



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