Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of occurences of a pattern in a list in Python

Given a pattern [1,1,0,1,1], and a binary list of length 100, [0,1,1,0,0,...,0,1]. I want to count the number of occurences of this pattern in this list. Is there a simple way to do this without the need to track the each item at every index with a variable?

Note something like this, [...,1, 1, 0, 1, 1, 1, 1, 0, 1, 1,...,0] can occur but this should be counted as 2 occurrences.

like image 387
Teodorico Levoff Avatar asked Apr 10 '18 07:04

Teodorico Levoff


1 Answers

Convert your list to string using join. Then do:

text.count(pattern)

If you need to count overlapping matches then you will have to use regex matching or define your own function.

Edit Here is the full code:

def overlapping_occurences(string, sub):
    count = start = 0
    while True:
        start = string.find(sub, start) + 1
        if start > 0:
            count+=1
        else:
            return count

given_list = [1, 1, 0, 1, 1, 1, 1, 0, 1, 1]
pattern = [1,1,0,1,1]

text = ''.join(str(x) for x in given_list)
print(text)
pattern = ''.join(str(x) for x in pattern)
print(pattern)
print(text.count(pattern)) #for no overlapping
print(overlapping_occurences(text, pattern))
like image 173
Abhishek Keshri Avatar answered Oct 03 '22 00:10

Abhishek Keshri