Answer to Question #248211 in Python for Lovely

Question #248211

add two polynomials given two polynomials a and b, write a program that adds the given two polynomials a and b. input the first line contains a single integer m. next m lines contain two integers pi, ci separated with space, where pi denotes power and ci denotes co-efficient of pi for polynomial a. after that next line contains a single integer n. next n lines contain two integers pj, cj separated with space, where pj denotes power and cj denotes co-efficient of pj for polynomial b.

I am not getting correct answer for this i have tried lot but coming please help me


1
Expert's answer
2021-10-07T14:09:36-0400
# Add polynomials

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