Search code examples
pythonarrayselementsimilarity

Sequence of similar items in an array


I am working in Python for the first time and I need to find an efficient way to search if a continuous sequence of three, four or five elements are the same in a larger array.

For example:

array = [1, 0, 0, 0, 1]

Output:

number_same = 3
element = 0
positions = [1, 2, 3]

Any suggestions or help?

Thx!


Solution

  • The following line will give you a list of tuples of a value and its locations within the array (grouped by repetition):

    from itertools import groupby
    [(k, [x[0] for x in g]) for k, g in groupby(enumerate(array), lambda x: x[1])]
    >>> [(1, [0]), (0, [1, 2, 3]), (1, [4])]
    

    You can later filter it to get only repetitions of 3 and over:

    filter(lambda x: len(x[1])>2, grouped_array)
    

    Used the following answer as reference: What's the most Pythonic way to identify consecutive duplicates in a list?