Python Forum
Get the variables in a sympy expression
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Get the variables in a sympy expression
#1
Hello! I have some equations which I read from a file, and then turn into sympy expressions and I need the variables that appear in each equation. However, for the purpose of my project, I need them in the order in which they appear in the equation. So if the equation is 'a+b*c' I need a program which gives me: a,b,c but not a,c,b or any other combination. Here is what I tried, based on what I found online:

from sympy import *
from sympy.parsing.sympy_parser import parse_expr

eq1 = "x1**(-1.0)*x2" # I normally read this from a file
eq1 = parse_expr(eq1)

print(eq1,eq1.free_symbols)
So, normally, eq1.free_symbols should give me a set of the variables in my expression. However after I ran this code (and other equations, too, with the same problem) several times, I got this output:

x1**(-1.0)*x2 {x1, x2}
x1**(-1.0)*x2 {x1, x2}
x1**(-1.0)*x2 {x2, x1}
x1**(-1.0)*x2 {x2, x1}
x1**(-1.0)*x2 {x2, x1}
x1**(-1.0)*x2 {x2, x1}
x1**(-1.0)*x2 {x1, x2}

So the equation looks fine, but the order of the variables seem to change randomly and this makes it useless for what I need. Can someone tell me how to pick the variables in the order I want (actually any order would be good as long as it doesn't randomly change)? Thank you!
Reply


Messages In This Thread
Get the variables in a sympy expression - by SJ001 - Feb-12-2019, 06:28 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  solve ODE with sympy Sergey_Novak 2 931 Dec-02-2023, 12:33 PM
Last Post: Sergey_Novak
  I need assistance with getting sympy to work alex_0 1 1,499 Apr-05-2021, 09:15 PM
Last Post: snippsat
  Pass results of expression to another expression cmdr_eggplant 2 2,271 Mar-26-2020, 06:59 AM
Last Post: ndc85430
  Sympy error "object is not callable" Cupcake 0 4,879 Feb-08-2020, 02:22 AM
Last Post: Cupcake
  Sympy Import error: "unresolved referrence 'sympy' " BoaCoder3 0 2,665 Jul-27-2018, 12:48 PM
Last Post: BoaCoder3
  SymPy - SolveSet Values Plant_Boy 0 2,489 Jan-01-2018, 09:20 PM
Last Post: Plant_Boy
  Sympy symbolic Point shoulddt 0 2,749 Jul-17-2017, 06:07 PM
Last Post: shoulddt
  Sympy Integration Flexico 5 7,481 Dec-07-2016, 07:24 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020