# How to use Collect to group negative terms?

For example, I have: $$-d^2-k^{d+1}+d k^d+d+k-1$$. I want to get: $$-\left(d^2+k^{d+1}+1\right)+d k^d+d+k$$.

• People here generally like users to post code as Mathematica code instead of just images or TeX, so they can copy-paste it. It makes it convenient for them and more likely you will get someone to help you. You may find this meta Q&A helpful Aug 23, 2020 at 13:56
• One problem is that you cannot conveniently prevent from the minus sign in -(a + b) from being automatically distributed. The internal form seems unimportant (from what is said in questions), so perhaps you're only interested in formatting the output? Aug 23, 2020 at 14:08
• Thank you for the solution and for the comments. I don't even care about the format. In fact, I have long equations (type LHS == 0) and my goal is to achieve LHS == RHS with only positive terms. I thought that grouping negative members would make it easier for me to move them to the right. Aug 23, 2020 at 18:10
• You're welcome. This is called an XY problem. Try Simplify[Expand@poly == 0] on my poly. See if it works for your case. Aug 23, 2020 at 18:34
• I'm afraid it doesn't work. mypoly = 1 - d - 2 k - 2 d k + 2 k ^ d + 2 d k ^ d - 4 k ^ (1 + d) + 4 d k ^ (1 + d) Simplify [Expand @ mypoly == 0] gives (* d (1 + 2 k) (-1 + 2 k ^ d) == (- 1 + 2 k) (1 + 2 k ^ d) *) I used your help and found: tmp = -Plus @@ Select[List @@ mypoly, InternalSyntacticNegativeQ]; balancedpoly = tmp == mypoly + tmp Thank you again. Aug 23, 2020 at 20:05

Test example:

SeedRandom[0];
poly = FromDigits[RandomInteger[{-5, 5}, 10], x]

(*  1 - 5 x + 3 x^2 + x^8 (2 + 5 x) + x^4 (-4 - 3 x + (3 - 5 x) x^2)  *)


The problem is that if you separate the added and subtracted terms, when it is evaluated, the minus sign is automatically distributed and the terms sorted (since Plus has the Attribute Orderless).

1 + 3 x^2 + 3 x^6 + 2 x^8 + 5 x^9 - (5 x^7 + 3 x^5 + 4 x^4 + 5 x)

(*  1 - 5 x + 3 x^2 - 4 x^4 - 3 x^5 + 3 x^6 - 5 x^7 + 2 x^8 + 5 x^9  *)


For output formatting: You can prevent Plus from being evaluated and sorting the monomials. This is inconvenient for further computation — I would just let the polynomial be reordered. However, for making a human-readable presentation, it can be done with Defer or HoldForm. Here is one way:

Plus @@ KeyValueMap[
# /. {False -> #2, True -> -Defer@Evaluate[-#2]} &,
Total /@ GroupBy[MonomialList[poly], InternalSyntacticNegativeQ]
]

(*  1 + 3 x^2 + 3 x^6 + 2 x^8 + 5 x^9 - (5 x + 4 x^4 + 3 x^5 + 5 x^7)  *)

• If your expression is not a polynomial, then instead of MonomialList, you could use List@@Expand[expr]. Aug 23, 2020 at 14:52