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
This should print: 2*x^2 + 3*x + 4*1 for p1
class Polynomial:
def __init__(self, coefficients):
self.coeffs=coefficients
def __str__(self):
out = ''
size = len(self.coeffs)
for i in range(size): #To Solve the ignored coefficient
if self.coeffs[i] != 0:
out += ' + %g*x^%d' % (self.coeffs[i],size-i-1) #To solve Backwards order
# 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
a = Polynomial([2,3,4])
print(a)