Building off of the previous sympy
answer, here is an approach which is dynamic with respect to the size and content of the in_dict
variables. The biggest step is to map the sympy symbols (python vars of x, y, z
) to their symbolic representations that get passed through your in_dict
import sympy
def eval_eqn(eqn,in_dict):
subs = {sympy.symbols(key):item for key,item in in_dict.items()}
ans = sympy.simplify(eqn).evalf(subs = subs)
return ans
The original inputs:
in_dict = {"x":2,"y":"x+2","z":"y+2"}
eqn = "(x+2)*y/z"
print(eval_eqn(eqn,in_dict))
2.66666666666667
A different set of inputs:
in_dict = {"a":2, "b": 4, "c":"a+2*b","d":"4*b + c"}
eqn = "c**2 + d**2"
print(eval_eqn(eqn,in_dict))
776.000000000000