Detect and count numerical sequence in Python array
<p>In a numerical sequence (e.g. one-dimensional array) I want to find different patterns of numbers and count each finding separately. However, the numbers can occur repeatedly but only the basic pattern is important. </p>

<pre><code># Example signal (1d array)
a = np.array([1,1,2,2,2,2,1,1,1,2,1,1,2,3,3,3,3,3,2,2,1,1,1])

# Search for these exact following "patterns": [1,2,1], [1,2,3], [3,2,1]

# Count the number of pattern occurrences
# [1,2,1] = 2 (occurs 2 times)
# [1,2,3] = 1 
# [3,2,1] = 1
</code></pre>

<p>I have come up with the Knuth-Morris-Pratt string matching (<a href="http://code.activestate.com/recipes/117214/" rel="nofollow">http://code.activestate.com/recipes/117214/</a>), which gives me the index of the searched pattern.</p>

<pre><code>for s in KnuthMorrisPratt(list(a), [1,2,1]):
    print('s')
</code></pre>

<p>The problem is, I don't know how to find the case, where the pattern [1,2,1] "hides" in the sequence [1,2,2,2,1]. I need to find a way to reduce this sequence of repeated numbers in order to get to [1,2,1]. Any ideas?</p>

<p>The only way I could think of solving your problem with the 
subpatterns matching was to use <code>regex</code>.</p>

<p>The following is a demonstration for findind for example the sequence <code>[1,2,1]</code> in <code>list1</code>:</p>

<pre><code>import re

list1 = [1,1,2,2,2,2,1,1,1,2,1,1,2,3,3,3,3,3,2,2,1,1,1]
str_list = ''.join(str(i) for i in list1)
print re.findall(r'1+2+1', str_list)
</code></pre>

<p>This will give you as a result:</p>

<pre><code>&gt;&gt;&gt; print re.findall(r'1+2+1', str_list)
['1122221', '1121']
</code></pre>

python arrays numbers detection