Given polynomial, write a program that prints polynomial in Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0 format.
Input
The 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.
Output
Print 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.
def printpoly(coeff):
"""Prints polinominal CN*x^PN + ... + C2*x^2 + C1*x^1 + C0*x^0
given by array of its coefficients Ci.
>>> printpoly([5, 0, 10, 6])
6x^3 + 10x^2 + 5
>>> printpoly([2, 3, 1, 6, 7])
7x^4 + 6x^3 + x^2 + 3x + 2
>>> printpoly([0, -2, -1])
-x^2 - 2x
>>> printpoly([-1])
-1
>>> printpoly([0, 0, 0])
0
>>> printpoly([0, 1000])
1000x
"""
s = []
first = True
PLUS = ' + '
MINUS = ' - '
for Pi in range(len(coeff)-1, -1, -1):
Ci = coeff[Pi]
if 0 == Ci:
if 0 == Pi and first:
s.append('0')
continue
if Ci < 0:
sign = MINUS
Ci = -Ci
else:
sign = PLUS
if first:
first = False
sign = '-' if MINUS == sign else ''
s.append(sign)
if 1 != Ci or 0 == Pi:
s.append(str(Ci))
if 0 < Pi:
s.append('x')
if 1 < Pi:
s.append('^')
s.append(str(Pi))
print(''.join(s))
# Program
def main():
N = int(input('N: '))
C = [0 for _ in range(N)]
for i in range(N):
Pi, Ci = list(map(int, input('Pi, Ci: ').split()))
C[Pi] = Ci
printpoly(C)
if __name__ == '__main__':
import doctest
doctest.testmod()
main()
Comments
Leave a comment