# What is the number of contiguous subsequences in this binary word?

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, ___}


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}

• Is SequenceCount a new function? I am using Mma 9 and it doesn't seem to work. May 24, 2019 at 15:38
• @GeoffreyCritzer Yes, it's new in M10.1. You can always use the ListCorrelate version then. May 24, 2019 at 15:47
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

Using SequenceCases:

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

(*2*)