Given polynomial, write a program that prints polynomial in Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0 format.InputThe first line contains a single integer N. Next N lines contain two integers Pi, Ci separated with space, where Pi denotes power and Ci denotes coefficient of Pi.OutputPrint the polynomial in the format Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0, 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. If the polynomial degree is zero and the constant term is also zero, then print 0 to represent the polynomial.For term Cix^Pi, if the coefficient of the term Ci is 1, print x^Pi instead of 1x^Pi.ExplanationIf N = 4For power 0,
#!/usr/bin/env python
# Read polynom
n = int(input())
Ps = []
Cs = []
for i in range(n):
tokens = input().split()
Pi = int(tokens[0])
Ci = int(tokens[1])
Ps.append(Pi)
Cs.append(Ci)
# format a string
indx = [i[0] for i in sorted(enumerate(Ps), reverse=True, key=lambda x:x[1])]
s = ''
for i in indx:
Pi = Ps[i]
Ci = Cs[i]
if len(s) == 0 :
if Ci == 0 and Pi == 0:
s = '0'
break
if Ci == 0:
continue
if Ci == 1:
pass
elif Ci == -1:
s = '-'
else:
s = str(Ci)
else:
if Ci > 0:
s += ' + '
elif Ci < 0:
s += ' - '
else:
continue
if abs(Ci) != 1:
s += str(abs(Ci))
if Pi == 0:
if abs(Ci) == 1:
s += str(abs(Ci))
else:
s += 'x'
if Pi != 1:
s += '^' + str(Pi)
print(s)
Comments
Leave a comment