Efficient way to find the index of repeated sequence in a list?
<p>I have a large list of numbers in python, and I want to write a function that finds sections of the list where the same number is repeated more than n times. For example, if n is 3 then my function should return the following results for the following examples:</p>

<blockquote>
  <p>When applied to example = [1,2,1,1,1,1,2,3] the function should return [(2,6)], because example[2:6] is a sequence containing all the same value.</p>
  
  <p>When applied to example = [0,0,0,7,3,2,2,2,2,1] the function should return [(0,3), (5,9)] because both example[0:3] and example[5:9] contain repeated sequences of the same value.</p>
  
  <p>When applied to example = [1,2,1,2,1,2,1,2,1,2] the function should return [] because there is no sequence of three or more elements that are all the same number.</p>
</blockquote>

<p>I know I could write a bunch of loops to get what I want, but that seems kind of inefficient, and I was wondering if there was an easier option to obtain what I wanted.</p>

<p>You can do this in a single loop by following the current algorithm:</p>

<pre><code>def find_pairs (array, n):
    result_pairs = []
    prev = idx = 0
    count = 1
    for i in range (0, len(array)):
        if(i &gt; 0):
            if(array[i] == prev):
                count += 1
            else:
                if(count &gt;= n):
                    result_pairs.append((idx, i))
                else:
                    prev = array[i]
                    idx = i
                count = 1
        else:
            prev = array[i]
            idx = i
    return result_pairs
</code></pre>

<p>And you call the function like this: <code>find_pairs(list, n)</code>. The is the most efficient way you can perform this task, as it has complexity O(len(array)). I think is pretty simple to understand, but if you have any doubts just ask.</p>

python python-3.x