Search code examples
pythonexpressionsympy

Reorder SymPy Expression


I have a SymPy expression of the form -x + y (where x, y are atoms, not other expressions), but I would like to rearrange them so that they will be y - x, so basically just get rid of the spare + to get the expression shorter.
How can I (if it's possible) do that?

Example input and output:

from sympy import *

expression = -4 + 2*I
reorder(expression) # how can I do that?
print(expression) # expected output: 2*I - 4

Solution

  • Here is a solution for this problem, which can also accept expressions which are not of type sympy.Add and replace only the additions within them with the reordered additions, and eventually return the final latex:

    def negcolast(expr):
        from sympy.core.function import _coeff_isneg as neg
        if isinstance(expr, sympy.Add) and neg(expr.args[0]):
            args = list(expr.args)
            args.append(args.pop(0))
            return sympy.UnevaluatedExpr(sympy.Add(*args,evaluate=False))
        else:
            return expr
    
    def latex(expr):
        expr = expr.replace(sympy.Add, lambda *args: negcolast(sympy.Add(*args)))
        return sympy.latex(expr, order='none')
    

    This was originally added to Revision 2 of the question.