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
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)
Comments
Leave a comment