问题
I'm trying to create a python program for solving equations:
from sympy import symbols, Eq, solve
list1 = ['x', 'y'] #<--- Letters of the user input
list1[0] = symbols(list1[0]) #<--- Assignment of the unknown x
list1[1] = symbols(list1[1]) #<--- Assignment of the unknown y
eq1 = Eq(x*2 - 5*x + 6 + y, 0) #<--- Equation
res = solve(eq1, dict=True) #<--- Solving
print(res)
I want assign a value to the first and the second object of the 'list1', in this case 'x = symbols('x')' and 'y = symbols('y')'. So I tried replacing the 'x' with list1[0] and the 'y' with list1[1] because it can be any letter based on user input. But the script still saying 'x is not defined' at the sixth line. So, is there a way to assign a value to an item of an array?
回答1:
When you are getting started with SymPy it takes a while to keep straight the difference between SymPy objects and Python variables. Try to keep in mind that every variable is a Python variable and what you assign to it is up to you.
In line 6 you want to use variables x
and y
. You can look in the preceding lines to see that you never defined an x
(which would have to be on the lhs of an =
). This will remedy the situation:
>>> x, y = map(Symbol, list1)
It doesn't matter what is in list1
in terms of strings. They could even be ['a', 'b']
. Whatever they are they will be used to create SymPy symbols and they will be assigned to the Python variables x
and y
. They will then appear in the results of the equation that you are solving:
>>> list1 = list('ab')
>>> x, y = map(Symbol, list1)
>>> solve(Eq(x*2 - 5*x + 6 + y, 0), dict=True)
[{a: b/3 + 2}]
回答2:
The issue is that you are creating the symbols in the context of the list.
When you are executing the equation, Python is not finding the variable 'x' or 'y' because they are not exposed/visible outside of the list.
You can try:
eq1 = Eq(list1[0]*2 - 5*list1[0] + 6 + list1[1], 0)
to get the results but it isn't pretty
Or the following should work:
x = Symbol('a')
y = Symbol('y')
eq1 = Eq(x*2 - 5*x + 6 + y, 0)
But if you really want the symbols exposed in the module, you can do something like:
def symbol_references(in_list):
for e in in_list:
globals()[e] = Symbol(e)
symbol_references(['x', 'y'])
print(type(x))
print(type(y))
来源:https://stackoverflow.com/questions/60469399/sympy-unknown-assignment