0

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

Edit:

In case someone needs it, 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')
Yuval.R
  • 1,182
  • 4
  • 15

1 Answers1

1

This is a printing issue. No matter what order you put the args, they will be printed the same way. This comes up periodically and I have answers here and especially here. So if you have two args you need to find out if only one of them has a negative sign (e.g. using sympy.core.function._coeff_isneg), create an unevaluated Add (Add(pos, neg, evaulate=False)) and then print that with the printer after telling it not to re-order terms.

>>> def negcolast(expr):
...     from sympy.core.function import _coeff_isneg as neg
...     if isinstance(expr, Add) and neg(expr.args[0]):
...         args = list(expr.args)
...         args.append(args.pop(0))
...         return LatexPrinter({'order':'none'})._print_Add(Add(*args,evaluate=False))
...     else:
...         return latex(expr)
... 
>>> negcolast(-4+2*I)
2iāˆ’4
smichr
  • 16,948
  • 2
  • 27
  • 34
  • Do you have a simple idea how to implement it into the `sympy.latex` function at least? – Yuval.R Feb 18 '22 at 20:30
  • see updated answer – smichr Feb 18 '22 at 21:06
  • I had an equation that is like x-1 and in the above code, it was outputting it as -1+x so I suggest you to change the last line to `return latex(expr, order='none')`. That fixed my issue. – wondim Aug 12 '22 at 11:30