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
Python has really powerful iteration that will help you out here.
For starters, don't pass the len of something to range. Iterate over the something directly.
for x in self.coeffs:
This won't completely help you, though, since the index of the iteration is needed for the power. enumerate can be used for that.
for i, x in enumerate(self.coeffs):
This presents another problem, however. The powers are backwards. For this, you want reversed.
for i, x in enumerate(reversed(self.coeffs)):
From here you just need to handle your output:
items = []
for i, x in enumerate(reversed(self.coeffs)):
if not x:
continue
items.append('{}x^{}'.format(x if x != 1 else '', i))
result = ' + '.join(items)
result = result.replace('x^0', '')
result = result.replace('^1 ', ' ')
result = result.replace('+ -', '- ')