Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...