I am looking for a Python solution that takes a string of a linear equation and outputs a vector of the coefficients.
To make things simple for the start, assume I have a set of equations:
- given in string form
- each with no more than 4 elements
- all are linear
- in all of them
x
appears only once
then I would like to get a vectorized representation where
- the first element is the
x
coefficient - other elements are other coefficients in the equation (not evaluated, but as they are), as if they appeared on the other side of the equation as
x
- zeros to complete the 4-d vector
I give here several input-output equations to get a sense of some of the challenges:
'2*x+3=2+5' => [2, -3, 2, 5]
'88/8=x' => [8, 88, 0, 0]
'74=(35+18)+3*x' => [3, 74, -35, -18]
'((4+4)*6)=x'] => [1/6, 4, 4, 0]
'-X=(91.0+88.0)' => [-1, 91, 88, 0]
'X=(30.0/10.0)' => [10, 30, 0, 0]
'0.16 + 0.41 = 2*x - 0.08' => [2, 0.16, 0.41, 0.08]
'(0.25 + 0.37)*2 = x' => [1/2, 0.25, 0.37, 0]
I started coding a "brute force" solution that is highly rigorous and tedious, stumbled several times along the way, and figured there must be a nicer and more clever way to do this...
- I am using the
sympy
package, which makes things a bit easier. Withsympify
andformula.split
and such I am able to extract thex
coefficient and the result of the equation (although I really don't care about the result, but only the vector representation)- I saw this and this but they are both in different languages, and not quite what I am looking for.
Sooo, anyone has any idea how to do it in Python?
Thanks! :)