3
$\begingroup$

I want to count the number of times the contiguous sublist 0,1,0 occurs in the binary word 0,1,0,1,0,0,1. It occurs twice. I tried

Cases[{0, 1, 0, 1, 0, 0, 1}, {___, 0, 1, 0, ___}
$\endgroup$

3 Answers 3

8
$\begingroup$

Probably the simplest way is to use SequenceCount:

SequenceCount[{0,1,0,1,0,0,1}, {0,1,0}, Overlaps->True]

2

If you have a long list and performance matters, than a version based on ListCorrelate might be better:

l=RandomInteger[1,10^6];
SequenceCount[l, {0,1,0}, Overlaps->True] //RepeatedTiming
Total @ UnitStep @ (ListCorrelate[{-1,1,-1}, l]-1)//RepeatedTiming

{0.06, 124777}

{0.020, 124777}

$\endgroup$
2
  • $\begingroup$ Is SequenceCount a new function? I am using Mma 9 and it doesn't seem to work. $\endgroup$ May 24, 2019 at 15:38
  • $\begingroup$ @GeoffreyCritzer Yes, it's new in M10.1. You can always use the ListCorrelate version then. $\endgroup$
    – Carl Woll
    May 24, 2019 at 15:47
1
$\begingroup$
list = {0, 1, 0, 1, 0, 0, 1};

Using Subsequences (new in 10.4)

Count[{0, 1, 0}] @ Subsequences[list, {3}]

2

Using Partition

Count[{0, 1, 0}] @ Partition[list, 3, 1]

2

$\endgroup$
1
$\begingroup$

Using SequenceCases:

Length@SequenceCases[{0, 1, 0, 1, 0, 0, 1}, s : {0, 1, 0} :> s, Overlaps -> True]

(*2*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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