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?
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.
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.
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.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With