# Order multivariable polynomial terms in order of total degree

Given a polynomial, lets say for example $$f(x,y) = (1+x+y)^2 = 1+2x+x^2+2y+2xy+y^2$$, I'd like to be able to order the terms of the polynomial by total degree, either in increasing or decreasing order (and if alphabetical order can be taken into account within terms of the same total order, then that would be great, but not necessary).

I'd like a function to take in $$1+2x+x^2+2y+2xy+y^2$$ and return $$(1) + (2x + 2y) + (x^2 + 2xy + y^2)$$, or in reverse order (and not necessarily with parenthesis, but that would be nice to work with.

I've tried various commands using Collect[], and MonomialList[], and while MonomialList[f(x,y),{x,y},"DegreeLexicographic"] gives a list of the terms in the order I want, I would like the full expression.

• Total[MonomialList[f(x,y),{x,y},"DegreeLexicographic"] will sum the list. Aug 4 '21 at 12:45
• This is true, however, it doesn't retain the order of the terms from the list. Aug 4 '21 at 12:50
• Total[HoldForm /@ CoefficientList[f[t*x, t*y], t]] Aug 4 '21 at 12:59
• 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 the meta Q&A, How to copy code from Mathematica so it looks good on this site, helpful Aug 6 '21 at 3:26

To quote Bob Hanlon's comment as an answer:

Total[HoldForm /@ CoefficientList[f[t*x, t*y], t]]


Perhaps this?:

Collect[(1 + x + y)^2 /. v : x | y :> t*v, t, HoldForm] /. t -> 1


Or this, which works like MatrixForm:

gradedForm /: MakeBoxes[gradedForm[poly_], form_] :=
Module[{t},
With[{vars = Alternatives @@ Variables@poly},
RowBox[
Riffle[
RowBox[{"(", MakeBoxes[#, form], ")"}] & /@
CoefficientList[poly /. v : vars :> t*v, t],
"+"]]
]];

(1 + x + y)^2 // gradedForm
(*  (1) + (2 x + 2 y) + (x^2 + 2 x y + y^2)  *)


The output can be copy-pasted as input, although if a variable is set equal to gradedForm[poly], the poly will remained wrapped in gradedForm, just like with MatrixForm.