We all know that math notation is idiosyncratic. Canonical representation of math objects often have irregular grammar rules to improve readability. For example we write a polynomial \$3x^3 + x^2\$ instead of more uniform but more verbose \$3x^3 + 1x^2 + 0x^1 + 0x^0\$. When a coefficient equals 0, you don't write the term, if the power equals \$1\$, you simply write \$x\$, and so on. So I wrote a simple program that outputs a string representation of a polynomial, given a list of coefficients:
def enumerate2(xs, start=0, step=1):
for x in xs:
yield (start, x)
start += step
def poly(xs):
"""Return string representation of a polynomial.
>>> poly([2,1,0])
"2x^2 + x"
"""
res = []
for e, x in enumerate2(xs, len(xs)-1, -1):
variable = 'x'
if x == 1:
coefficient = ''
elif x == -1:
coefficient = '-'
else:
coefficient = str(x)
if e == 1:
power = ''
elif e == 0:
power = ''
variable = ''
else:
power = '^' + str(e)
if x < 0:
coefficient = '(' + coefficient
power = power + ')'
if x != 0:
res.append(coefficient + variable + power)
return ' + '.join(res)
enumerate2
is a custom version of enumerate
that supports variable step. The result looks like this:
>>> poly([2,0,3,-4,-3,2,0,1,10])
'2x^8 + 3x^6 + (-4x^5) + (-3x^4) + 2x^3 + x + 10'
How do I make this code more elegant and probably more generic? Oh, and the result is sub-optimal, as negative terms are enclosed in brackets, instead of changing the preceding plus sign to minus.