This might be a very basic question, but I am wondering if I am missing a sympy-functionality after reading through the documentation, or if there is really non included for this use-case.
I have the following expressions:
a = sympify("b + 5")
b = sympify("c + 5")
c = sympify("5")
I am trying to evaluate a. Is there any way that sympy does all the recursive search and replace for you or do I really have to do it manually?
Such as:
eval(str(eval(str(a))))
Make a distinction between the symbols and the expressions:
yields
Above,
a
is a Symbol, buta_expr
is an expression:Given a dict of formulas such as
you could form the equations with a list comprehension
and solve the system of equations with
Why you should not use
sympy.var
:When dealing with dynamic variables -- variables whose names are unknown until run-time -- it is advisable to avoid using
sy.var
.sy.var
adds the name of the variable to the global namespace. The only purpose in doing this is if you are going to reference the variable by name. But by hypothesis the variable names are unknown until run-time. So the script code should not -- in fact, should not be able to -- reference the variables by name. So usingsy.var
should be useless if the variables are truly dynamic.That's no real problem, however. The dynamic variables names (as strings) can be listed with
and the
sy.Symbols
can be listed withSo you can write loops to access each variable without ever having to define a global variable name for each Symbol.