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>Here's a one-liner that will do it</p>

<pre><code>import numpy as np

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])
p = np.array([1,2,1])

num = sum(1 for k in 
          [a[j:j+len(p)] for j in range(len(a) - len(p) + 1)]
          if np.array_equal(k, p))
</code></pre>

<p>The innermost part is a list comprehension that generates all pieces of the array that are the same length as the pattern.  The outer part sums 1 for every element of this list which matches the pattern.</p>

python arrays numbers detection