Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding patterns in a list

Tags:

python

I'm trying to write a python script to find patterns in a list.

Eg. Given this list

[1,2,3,4,5,6,4,5,6,4,5,6,4,5,6]

The script would determine that 4,5,6 ocurred 3 times and then print out

3 (4,5,6)

I was hoping if anyone had any insights algorithmically (I can only think of n^2 algorithms where I check for patterns of size 1, then 2, then 3, etc iterating through the string each time) or if there might be any Python built-in libraries which might help do the same things. Thanks!

like image 499
aerain Avatar asked Mar 06 '26 14:03

aerain


1 Answers

Here is a function providing a solution to the pattern matching problem:

import itertools

def pattern_match(pattern, sequence):
    """Count the number of times that pattern occurs in the sequence."""
    pattern = tuple(pattern)
    k = len(pattern)

    # create k iterators for the sequence
    i = itertools.tee(sequence, k)

    # advance the iterators
    for j in range(k):
        for _ in range(j):
            next(i[j])

    count = 0
    for q in zip(*i):
        if pattern == q:
            count += 1

    return count

To solve the stated problem, call with:

p = [4, 5, 6]
l = [1, 2, 3, 4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]
count = pattern_match(p, l)

Here is a Gist with the complete code solving the example problem.

(I believe the correct answer is that the pattern repeats 4 times, not 3 times, as stated in the question.)

I'm not sure if the complexity of this algorithm is actually less than O(n^2).

like image 153
jcbsv Avatar answered Mar 09 '26 03:03

jcbsv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!