Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String count with overlapping occurrences

What's the best way to count the number of occurrences of a given string, including overlap in Python? This is one way:

def function(string, str_to_search_for):       count = 0       for x in xrange(len(string) - len(str_to_search_for) + 1):            if string[x:x+len(str_to_search_for)] == str_to_search_for:                 count += 1       return count   function('1011101111','11') 

This method returns 5.

Is there a better way in Python?

like image 347
calccrypto Avatar asked Jun 03 '10 23:06

calccrypto


People also ask

How do you check for overlapping strings in Python?

In order to solve this problem, we can use find() function in Python. It returns the start position of the first occurrence of substring in the given string, then we increment this position by 1 and continue the search from that position till the end of the string.

How do you count the number of occurrences of an element in a string?

count() One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string . count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.

What is overlapping in Python?

Now two rectangles overlap if the area of their intersection is positive. So, we can understand that two rectangles that only touch at the corner or edges do not overlap. If we have two (axis-aligned) rectangles, we have to check whether they overlap or not.

What is non overlapping substring?

The substrings do not overlap, that is for any two substrings s[i.. j] and s[x..y] , either j < x or i > y is true. A substring that contains a certain character c must also contain all occurrences of c .


1 Answers

Well, this might be faster since it does the comparing in C:

def occurrences(string, sub):     count = start = 0     while True:         start = string.find(sub, start) + 1         if start > 0:             count+=1         else:             return count 
like image 82
Jochen Ritzel Avatar answered Sep 25 '22 17:09

Jochen Ritzel