again, I have a list like this:
list={0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, \
0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, \
0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}
I want to search for the pattern: {1,0,0} and mark all the numbers matching this sequence in Red with the Style option. I tried to use Cases to help me out, which does not work. Checked the help a few times, but no idea so far :/
Cases[list, {1,0,0}]
Answer
Using string manipulations seems to speed things up significantly:
randomList = RandomInteger[{0, 1}, 1000];
m1 = randomList //. {b___, PatternSequence[1, 0, 0], a___} -> {b,
Sequence @@ (Style[#, Red] & /@ {1, 0, 0}), a} //
AbsoluteTiming;
m2 = StringSplit[StringJoin @@ (ToString /@ randomList),
"100" -> Sequence @@ (Style[#, Red] & /@ {1, 0, 0})] /.
s_String :> Sequence @@ (ToExpression /@ Characters[s]) //
AbsoluteTiming;
(* Checking answers from both methods *)
Equal @@ (Rest /@ {m1, m2})
(* True *)
(* Timings *)
First /@ {m1, m2}
(* {0.938379, 0.017024} *)
Comments
Post a Comment