Answer to Question #292811 in Python for Hari

Question #292811

Add two polynomialsGiven two polynomials A and B, write a program that adds the giventwo polynomials A and B

5

0 -2

3 6

4 7

1 -3

2 -1

5

0 1

1 2

2 -4

3 3

4 5


output : 12x^4 + 9x^3 - 5x^2 - x - 1





1
Expert's answer
2022-02-01T23:54:07-0500
def read_polynom():
    n = int(input())
    p = {}
    for i in range(n):
        L = input().split()
        Pi = int(L[0])
        Ci = int(L[1])
        p[Pi] = Ci
    return p


def add_polynomilas(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 tostring_polynom(p):
    res = ''
    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:
                res = '-'
            else:           
                res = f'{Ci}'
            first = False
            
        else:        
            if Ci > 0:
                res += ' + '
            elif Ci < 0:
                res += ' - '
            else:
                continue
            res += f'{abs(Ci)}'
        
        if Pi == 0:
            continue
        if Pi == 1:
            res += 'x'
        else:
            res += f'x^{Pi}'
    return res

def main():
    p = read_polynom()
    q = read_polynom()
    r = add_polynomilas(p, q)
    print(f'Add {tostring_polynom(p)} to {tostring_polynom(q)}')
    print(f'results {tostring_polynom(r)}')

if __name__ == '__main__':
    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