I'm making a Polynomial python class and as part of that, I need to print a polynomial nicely. The class is given a list that represents the coefficients of the polynomial and their exponents are given by the position the coefficients are in the list. For example [2,-3,0,5]
would give 2x^3-3x^2+5
.
I have tried to take in to account errors such that instead of having 1x
it just prints x
and if there is a negative, the function just returns a -
and not a +-
This is my code so far
class Polynomial:
def __init__(self, coefficients):
self.coeffs=coefficients
def __str__(self):
out = ''
for i in range(1,len(self.coeffs)):
if self.coeffs[i] != 0:
out += ' + %g*x^%d' % (self.coeffs[i],i)
# Fixing
out = out.replace('+ -', '- ')
out = out.replace('x^0', '1')
out = out.replace(' 1*', ' ')
out = out.replace('x^1 ', 'x ')
if out[0:3] == ' + ': # remove initial +
out = out[3:]
if out[0:3] == ' - ': # fix spaces for initial -
out = '-' + out[3:]
return out
When trying to print p1 = Polynomial([2,3,4])
I get p1 = 3x+4x^2
. The order of the exponents seems to be backwards and the code just ignores the coefficient at the end.