Force Sympy to maintain order of terms

I have the following code:

from sympy import *
init_printing()

x,y = symbols('x y')
u = Function('u')(x,y)
ux,uy,uxx,uxy,uyy = symbols("u_x u_y u_xx u_xy u_yy")

mainEvaluation = uxx - 2*sin(x)*uxy - (cos(x) ** 2) * uyy - 2*ux + (2 - cos(x) + 2*sin(x) )*uy

And when the output print(mainExpression)is equal

-2*u_x + u_xx - 2*u_xy*sin(x) + u_y*(2*sin(x) - cos(x) + 2) - u_yy*cos(x)**2

The problem is that I want the original order of the variables.

u_xx - 2*u_xy*sin(x)  - u_yy*cos(x)**2  - 2*u_x + u_y*(2*sin(x) - cos(x) + 2)

All this is done in an IPython laptop. Is there a way to keep order?

+5
source share
2 answers

Unfortunately, SymPy does not track input order (see another question that I related in the comment to the question). You can define your own order function, which orders the expressions, but you do not want to arrange things exactly as they were entered, since this information is not stored.

+5
source

http://docs.sympy.org/0.7.2/modules/utilities/misc.html, ,

:

, . :

>>> a, b = x, 1/x

a 1 , sort_key :

>>> a.sort_key() == a.sort_key('rev-lex')
True

a b , , , :

>>> eq = a + b
>>> eq.sort_key() == eq.sort_key('rev-lex')
False
>>> eq.as_ordered_terms()
[x, 1/x]
>>> eq.as_ordered_terms('rev-lex')
[1/x, x]

, -, :

>>> sorted(eq.args, key=default_sort_key)
[1/x, x]
>>> sorted(eq.args, key=lambda i: default_sort_key(i, order='rev-lex'))
[1/x, x]

, , - , , .

+1

Source: https://habr.com/ru/post/1678711/


All Articles