I'm trying to find a way to efficiently pull the coefficients out of a string that contains a symbolic polynomial and put them into a list, where the powers are the indeces. For example, a string
x^10+6x^4-5x^2+x-11
would be the list
[-11, 1, -5, 0, 6, 0, 0, 0, 0, 0, 1]
I'm currently trying to learn regex to handle it, but my understanding of it isn't good enough to inspire confidence in its robustness (obviously, logic tells me otherwise). Can anyone set me on the right track to solving this problem?
Here's a way to parse the equation into a list of dictionaries with self-documenting keys. This approach is similar in spirit to Jmac's very fine answer.
eq = 'x^10+6x^4-5x^2+x-11'
patt = r'(?P<sign>[-+]?)(?P<coeff>\d*)(?P<x>x?)(?:\^(?P<exp>\d+))?'
rgx = re.compile(patt)
eq_parts = [m.groupdict() for m in rgx.finditer(eq)][0:-1]
for eqp in eq_parts:
print eqp
Output:
{'x': 'x', 'coeff': '', 'exp': '10', 'sign': ''}
{'x': 'x', 'coeff': '6', 'exp': '4', 'sign': '+'}
{'x': 'x', 'coeff': '5', 'exp': '2', 'sign': '-'}
{'x': 'x', 'coeff': '', 'exp': None, 'sign': '+'}
{'x': '', 'coeff': '11', 'exp': None, 'sign': '-'}