Answer to Question #231257 in Python for bhuvana

Question #231257

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


1
Expert's answer
2021-09-02T12:39:10-0400
pol = dict()
for _ in range(2):
    n = int(input('N: '))
    for _ in range(n):
        p, c = [int(x) for x in input('P, C: ').split()]
        if p in pol:
            pol[p] += c
        else:
            pol[p] = c
output = ''
for p in sorted(pol, reverse=True):
    if pol[p] < 0:
        if output:
            output += ' - '
        else:
            output += '-'
    elif pol[p] > 0:
        if output:
            output += ' + '
        else:
            pass
    elif pol[p] == 0:
        continue

    if pol[p] != 1:
        output += str(abs(pol[p]))
    elif pol[p] == 1 and p == 0:
        output += '1'
        continue

    if p < 0:
        output += f'x^({p})'
    elif p == 1:
        output += 'x'
    elif p > 0:
        output += f'x^{p}'
print(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