Reputation:
The post "How can I convert a list of strings into sympy variables?" discusses how to generate SymPy symbols from a list of strings. My question is what steps are needed to use these symbols x, y and z in SymPy calculations?
I tried something along the lines
from sympy import symbols, solveset
var_as_strings = ['x', 'y', 'z']
var_as_symbol_objects = [sympy.symbols(v) for v in var_as_strings]
var_as_symbol_objects
for x1, x2 in zip(var_as_symbol_objects, var_as_strings):
x1 = symbols(x2)
soln = solveset(x-y-z, x)
but I get the error "NameError: name 'x' is not defined". Any help is greatly appreciated.
Upvotes: 0
Views: 461
Reputation: 343
that I have a lot of items in my list that I wish to define as symbols
Just FYI, a snippet which can automatically define the symbols in an enhanced fashion
nmax = 7
names = ["phi" + str(i) for i in range(nmax)]
sympy_vars = [symbols("\\" + name.replace("phi", "phi_")) for name in names]
globals().update(dict(zip(names, sympy_vars)))
phi0
This yields a nice LaTeX type output in, e.g., jupyter notebooks.
Upvotes: 0
Reputation: 19115
You can create Python variables in the current namespace from a list of strings (or a string of space or comma separated names) with var
:
>>> names = 'x y z' # or 'x, y, z'
>>> var(names)
(x, y, z)
>>> var(list('xyz'))
[x, y, z]
>>> var(set('xyz'))
{x, y, z}
In all cases, after issuing the var
command you will be able to use variables that have been assigned SymPy symbols with the same name.
Upvotes: 1
Reputation: 2001
This is answered by the first listed gotcha in the documentation.
You need to store your symbols into the required variables manually (x = symbols('x')
), or import them from sympy.abc
(from sympy.abc import x
).
The name error is happening because you haven't defined what x
, y
or z
are in your code.
Upvotes: 2