Answer to Question #205054 in Python for ayushi

Question #205054

Given polynomial, write a program that prints polynomial in Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0 format.


input : 5

0 2

1 3

2 1

4 7


expected output : 7x^4 + 6x^3 + x^2 + 3x + 2
 your output: 7x^4 + 6x^3 + 1x^2 + 3 + 2


please explain this


1
Expert's answer
2021-06-09T12:34:34-0400
n = int(input('N: '))
pol = dict()
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