Answer to Question #200889 in Python for meghana

Question #200889

\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.Output


Print the addition of polynomials A and B.

The format for printing polynomials is: Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0, where Pi's are powers in decreasing order, Ci is co-efficient and C0 is constant, there will be space before and after the plus or minus sign.

If co-efficient is zero then don't print the term.

If the term with highest degree is negative, the term should be represented as -Cix^Pi.

For the term where power is 1 represent it as C1x instead of C1x^1.

.





1
Expert's answer
2021-05-31T00:53:35-0400
def polynomial(f):
    n = int(input(f'Enter {f}:'))
    poly = {}
    for i in range(n):
        idx, pw = map(int, input().split())
        poly[idx] = pw
    return poly


def add_poly(a, b):
    res = {}
    poly = set(a).union(b)
    for p in poly:

        if p in a:
            q = a[p]
        else:
            q = 0.0

        if p in b:
            q += b[p]
        if q != 0:
            res[p] = q
    return res


def display_poly(poly):
    res = ''
    first = True
    for idx in sorted(poly, reverse=True):
        pw = poly[idx]
        if first:
            if pw == 0 and idx == 0:
                return '0'
            if pw == 1 and idx != 0:
                pass
            elif pw == -1 and idx != 0:
                res = '-'
            else:
                res = f'{pw}'
            first = False
        else:
            if pw > 0:
                res += ' + '
            elif pw < 0:
                res += ' - '
            else:
                continue
            res += f'{abs(pw)}'
        if idx == 0:
            continue
        if idx == 1:
            res += 'x'
        else:
            res += f'x^{idx}'
    return res


print(display_poly(add_poly(polynomial('N'), polynomial('M'))))



// in
Enter N: 4
0 5
1 0
2 10
3 6
Enter M: 3
0 1
1 2
2 4
// out
6x^3 + 14x^2 + 2x + 6

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