Given polynomial, write a program that prints polynomial in Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0 format.
where Pi's are powers in decreasing order, Ci is coefficient, and C0 is constant. There will be space before and after the plus or minus sign.If the coefficient is zero, then don't print the term.
If the term with the highest degree is negative, the term should represent -Cix^Pi.
For the term where power is 1, represent it as C1x instead of C1x^1.
For term Cix^Pi, if the coefficient of the term Ci is 1, print x^Pi instead of 1x^Pi.
Explanation
If N = 4 If N = 5
For power 0, the coefficient is 5 For power 0, the coefficient is 2
For power 1, the coefficient is 0 For power 1, the coefficient is 3
For power 2, the coefficient is 10 For power 2, the coefficient is 2
For power 3, the coefficient is 6. For power 3, the coefficient is 6.
For power 4, the coefficient is 7.
polynomial represents "6x^3+10x^2+5" polynomial represents "7x^4+6x^3+x^2+3x+2"
n = int(input('N '))
p = {}
for i in range(n):
pi, ci = map(int,input(f'p{i} c{i} ').split())
if pi in p:
p[pi] += ci
else:
p[pi] = ci
res = ''
if len(p) != 0:
first = True
for k in sorted(p, reverse=True):
if p[k] == 0:
continue
elif p[k] < 0:
if first:
res += '-'
else:
res += ' - '
else:
if not first:
res += ' + '
first = False
if (abs(p[k]) == 1) and k == 0:
res += '1'
continue
elif abs(p[k]) != 1:
res += str(abs(p[k]))
if k < 0:
res += f'x^({k})'
elif k == 1:
res += 'x'
elif k > 0:
res += f'x^{k}'
if len(res) == 0:
print('0')
else:
print(res)
Comments
Leave a comment