1

I have some string,like "3+(3*(2+5))", obvious that some brackets are unnecessary. It can write like "3+3*(2+5)", so I try to use Inactive.

ToExpression["3+(3*(2+5))",StandardForm,Hold]
    //Inactivate[#,Plus|Times] & // ReleaseHold

ToExpression["((3+4)+(5+6))+((7-8)*(9*(1*2)))",StandardForm,Hold]
    //Inactivate[#,Plus|Times] & // ReleaseHold

Blockquote

Sometimes it works,but sometimes it does not work.

Could someone help me? Thanks.

Apple
  • 3,663
  • 16
  • 25

2 Answers2

2

The problem is that the head Inactive[Plus] etc. does not inherit the Flat attribute of Plus and Times. One way is to Flatten manually:

expr = ToExpression["((3+4)+(5+6))+((7-8)*(9*(1*2)))", InputForm, 
     Hold] // Inactivate[#, Plus | Times] & // ReleaseHold;
Simplify[expr, TransformationFunctions -> {
    # /. e : Inactive[Plus][__] :> Flatten[e] &,
    # /. e : Inactive[Times][__] :> Flatten[e] &}]

Mathematica graphics

Another way is to get it, by replacing Inactive[Plus] etc. by temporary heads with the Flat attribute.

Module[{p, t},
 SetAttributes[p, Flat];
 SetAttributes[t, Flat];
 ReleaseHold[
   ToExpression["((3+4)+(5+6))+((7-8)*(9*(1*2)))", StandardForm, 
     Hold] /. {Plus -> p, Times -> t}
   ] /. {p -> Inactive[Plus], t -> Inactive[Times]}
 ]

Mathematica graphics

Michael E2
  • 235,386
  • 17
  • 334
  • 747
1
(ToExpression["((3+4)+(5+6))+((7-8)*(9*(1*2)))",StandardForm,Hold]//Inactivate[#,Plus|Times]&//ReleaseHold)//.{Inactive[Plus][a___,Inactive[Plus][b_,c_],d___]->Inactive[Plus][a,b,c,d],
Inactive[Times][a___,Inactive[Times][b_,c_],d___]->Inactive[Times][a,b,c,d]}

and one more way, but it suits only for expressions with reals and integers

(ToExpression["((3+4)+(5+6))+((7-8)*(9*(1*2)))", StandardForm, 
    Hold] /. x : _Integer | _Real :> ToString[x]) // ReleaseHold

and this one can take into account non standard symbols like named variables

(ToExpression["((3+4)+(5+6))+((7-8)*(9*(1*2)))", StandardForm, 
    Hold]/. x : _Integer | _Real | _Symbol?Not@NameQ :> ToString[x] // ReleaseHold
k_v
  • 579
  • 5
  • 6