hit counter

Timeline

My development logbook

Sometimes It Is Quite Fun to Answer Some Questions in Stackoverflow: You Can Help Someone Seeking Answer and You May Also Learn a New Thing or Two Yourself in the Process.

Sometimes it is quite fun to answer some questions in Stackoverflow: you can help someone seeking answer and you may also learn a new thing or two yourself in the process.

This is one such example:

http://stackoverflow.com/questions/11707151/python-make-a-global-condition-break.

Essentially the OP is asking if there is an easy to find the number of occurrence of a substring in a longer string. For example “assesses” has the substring “sses” 2 times.

It is a very simple question, but there is still something new I learn: while re.findall is the most elegant solution, it may not work in finding overlapped occurrence of pattern. To do so one needs to include a ‘lookahead’ in the regular expression.

My proposed solution is simply an improved version of OP’s code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
first = "an"
second = "trans-Panamanian banana"

def count_needle(first, second):

        location = str.find(second,first)
        if location == -1:
                return 0 # none whatsoever
        else:
                count = 1
                while location < len(second):
                   location = str.find(second,first,location +1)
                   if location < 0:
                      break
                   count = count + 1
        return count

print(count_needle(first, second))

Here is a even shorter version which takes advantage of python’s flexible comparison syntax:

1
2
3
4
5
6
7
8
9
10
11
12
first = "an"
second = "trans-Panamanian banana"

def count_needle(first, second):
        count = 0
        location = str.find(second,first)
        while (0 <= location < len(second)):
                   count += 1
                   location = str.find(second,first,location +1)
        return count

print(count_needle(first, second))