parse numbers from x,y,z equation
<p>I am parsing numbers from equation. From my code there is little problem. 
It does not recognize the number 1 from equation because normally in equation, number 1 is skipped. </p>

<pre><code>def equationSystem(e):
a = []
for s in e:
    a.append(re.findall("[-]?\d+[\.]?\d*[eE]?[-+]?\d*", s))

print a[0]
</code></pre>

<p>example </p>

<pre><code>equation =  ["-x+y+z=0", "x-3y-2z=5", "5x+y+4z=3"]
</code></pre>

<p>expected output</p>

<pre><code>[[-1, 1, 1, 0], [1, -1, -2, 5], [5, 1, 4, 3]]
</code></pre>

<p>but actual output is </p>

<pre><code>[[0], [-2, 5], [5,1,4,3]]
</code></pre>

<p>can you help me to improve the regular expression?</p>

<p>Suppose instead you look for the known constants "xyz=" as separators, and took everything between them as regular expression groups.</p>

<pre><code>import re

pattern_string = '([^x]*)x([^y]*)y([^z]*)z=(.+)'
pattern = re.compile(pattern_string)

def parse_equation(s):
    results = pattern.search(s)
    return results.groups()

samples =  ["-x+y+z=0", "x-3y-2z=5", "5x+y+4z=3"]
for s in samples:
    print parse_equation(s)
</code></pre>

<p>The output is</p>

<pre><code>('-', '+', '+', '0')
('', '-3', '-2', '5')
('5', '+', '+4', '3')
</code></pre>

<p>And then you only need to worry about converting those strings to a number. For the first three, you know they cannot be zero, so they might have a different conversion function, but that's not necessary. The important thing is that if you don't find any digits in the string, then you return +/- 1.</p>

<p>Since you want to handle floats and E-notation, you will need to do a tiny bit more to strip whitespace, but I will leave that up to you. For example, if you have the equation "0.5x - 36E-4y + z=0" then the space between - and 36, before the y, will throw off a simple float(s) conversion. But if you take out that space, you can do this:</p>

<pre><code>def default_to_one(s):
    try:
        coefficient = float(s)
        return coefficient
    except:
        if -1 != s.find('-'):
            return -1
        else:
            return 1
</code></pre>

<p>and get the coefficients with [default_to_one(x) for x in parse_equation(s)], resulting in this output for the three cases you gave, plus an extra case "0.5x -36E-4y + z=0" to demonstrate handling all the types you intended, according to your original regexp.</p>

<pre><code>[-1, 1, 1, 0.0]
[1, -3.0, -2.0, 5.0]
[5.0, 1, 4.0, 3.0]
[0.5, -0.0036, 1, 0.0]
</code></pre>

python