Given polynomial, write a program that prints polynomial in Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0 format.
n = int(input())
pw_cf = []
for i in range(n):
line = input().split()
pw = int(line[0])
cf = int(line[1])
pw_cf.append((pw, cf))
pw_cf.sort(reverse=True)
first = True
for pw, cf in pw_cf:
if cf == 0:
continue
if cf < 0.0:
if first:
print(cf, end='')
else:
print(' -', abs(cf), end='')
else:
if first:
print(cf, end='')
else:
print(' +', abs(cf), end='')
first = False
if pw == 0:
continue
if pw == 1:
continue
if pw < 0:
print(f'x^({pw})', end='')
else:
print(f'x^{pw}', end='')
print()
ex.1
// IN
4 2 3
3 4
5 6
7 8
// OUT
8x^7 + 6x^5 + 4x^3 + 3x^2
ex.2
// IN
5 0 1
2 3
4 0
5 6
8 -5
// OUT
-5x^8 + 6x^5 + 3x^2 + 1
Comments
Leave a comment