1
$\begingroup$

How to sort a "+" sequence like

1+5+3+2+4

to get back

1+2+3+4+5

Same sorting problem with polynoms (but I am mainly interested in the above simple "1+5+3+2+4" sorting):

Expand[(x^3 - x + 5)^6]

TraditionalForm[Expand[(x^3 - x + 5)^6]]

Expand[(x^3 - a*x + 5)^6]

Collect[Expand[(x^3 - a*x + b)^6], x, Factor]

TraditionalForm[Collect[Expand[(x^3 - a*x + b)^6], x, Factor]]

Thank you beforehand for an answer.

Regards.

Gianni

$\endgroup$
3
  • 7
    $\begingroup$ Can you please provide more concrete example for 1+5+3+2+4? This obviously gets evaluated to 15. Are you using inactivated operators? In that case: Sort@Inactivate[1 + 5 + 3 + 2 + 4, Plus] does the job. As for the polynomials: they are sorted by the descending power of $x$. How would you want them to be sorted? By the prefactors? $\endgroup$
    – Domen
    Mar 15 at 13:53
  • $\begingroup$ Plus has the attribute Orderless, which means that terms are automatically sorted into canonical order. $\endgroup$
    – Michael E2
    Mar 15 at 22:16
  • $\begingroup$ Some possibly related links may be found here: mathematica.stackexchange.com/questions/108147/… $\endgroup$
    – Michael E2
    Mar 15 at 22:19

1 Answer 1

0
$\begingroup$
sum="{14+5+9+7}";a=ToString[Sort[ToExpression[StringReplace[sum,"+"->","]]]];
a=StringReplace[a,", "->"+"];
a=StringReplace[a,"{"->""];
a=StringReplace[a,"}"->""]

a sequence 14+5+9+7 is sorted 5+7+9+14

This code can be used or developed in a polynome with variable x.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.