2
$\begingroup$

I would like to replace the occurrence of "a(x)" and "b(x)" in a list with "a(x-na)" and "b(x-nb)" where na and nb are the number of a's and b's respectively. x-na should be evaluated. I've tried

list = {"a(1)", "a(2)", "a(3)", "b(4)", "b(5)", "b(6)"}
na = Total[StringCount[list, "a"]]
nb = Total[StringCount[list, "b"]]
StringReplace[list, {"a(" ~~ n___ ~~ ")" -> 
   "a(" <> ToString[n - na] <> ")"}]
{"a(-3 + n)", "a(-3 + n)", "a(-3 + n)", "b(4)", "b(5)", "b(6)"} 

But as you can see it is not working as intended.

Can you help me please?

$\endgroup$
2
$\begingroup$
StringReplace[
 list,
 {h_ ~~ "(" ~~ n_ ~~ ")" :> 
   h <> "(" <> ToString[ToExpression[n] - Symbol["n" <> h]] <> ")"
}]
 {"a(-2)", "a(-1)", "a(0)", "b(1)", "b(2)", "b(3)"} 

Tell me if anything is not clear.

And some fun:

Composition[
  Map[ToString@ToString[#, TraditionalForm] &],
  # /. h_[n_Integer] :> h[n - CountsBy[#, Head][h]] &,
  Map[ToExpression[#, TraditionalForm] &]

  ]@{"a(1)", "a(2)", "a(3)", "b(4)", "b(5)", "b(6)"}
{"a(-2)", "a(-1)", "a(0)", "b(1)", "b(2)", "b(3)"} 
$\endgroup$
  • $\begingroup$ That is good. You did more than I requested since I can do two StringReplace for a and b separately. Thanks! $\endgroup$ – Fabio Dec 3 '15 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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