Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

python 3.x - sympy unknown assignment

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...