Search code examples
pythonmathevalmathematical-expressions

How to evaluate a list of symbolic expressions


I have a dictionary dictionary1 that contains variables as : x1, x2, x3, y1, y2 .. they are each associated with a structure of data containing mostly list of datas. Each variable of the dict has a list of integers of the same size.

I have a list of equations as :

equationsList = ["x1+2*2", "(x2*3)+4","x3+6*y1", "(x4*3)+y2"] #etc ...

My idea was to replace the strings recognized in the dictionary by their associated values in order to apply the formula on every element of the list :

for equation in equationList:
    for item in equation.split():
        if item in dictionary1:
            for ValueElement in dictionary1[item].ValueList:
                equation = re.sub(item, str(ValueElement), equation)
                ValueElement = eval(equation)

And my code works perfectly when there is only one variable (x or y) from the dictionary but when it comes to an equation with 2+ variables only the first one is remplaced.


Solution

  • using sympy you could to this:

    from sympy import symbols, sympify
    
    x1, x2, x3, x4, y1, y2 = symbols('x1 x2 x3 x4 y1 y2')
    
    equationsList = ["x1+2*2", "(x2*3)+4", "x3+6*y1", "(x4*3)+y2"]
    expressions = [sympify(expr) for expr in equationsList]
    
    values = {x1: 1, x2: 2, x3: 3, x4: 4, y1: -1, y2: -2}
    
    for expression in expressions:
        print('{:10s} ->  {:4d}'.format(str(expression),
                                        int(expression.subs(values))))
    

    which will output

    x1 + 4     ->     5
    3*x2 + 4   ->    10
    x3 + 6*y1  ->    -3
    3*x4 + y2  ->    10