-1

I recently started to learn Python programming. It goes as following:

For s = 'xasdkbobobasdvobob', find the number of occurences of 'bob' in s.

I've been able to write a code that will give me an output of 2 however the answer I'm looking for is 3.

halfer
  • 19,824
  • 17
  • 99
  • 186

3 Answers3

0

You can also try using the new Python regex module, which supports overlapping matches.

import re
s = 'xasdkbobobasdvobob'
print(len(list(re.finditer('(?=bob)', s))))

Python regex module

https://pypi.python.org/pypi/regex

Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27
0

There are regular expression-based solutions to this elsewhere on SO, but you can do this by iteratively finding each "bob" without the need for REs:

s = 'xasdkbobobasdvobob'
pos = -1
count = 0
while True:
    pos = s.find('bob', pos + 1) # search from the character after the start of the last find
    if pos > -1: # found an instance
        count += 1
    else: # no more instances
        break
print count
Synook
  • 339
  • 1
  • 8
0

Option 1

Use the regex module:

import regex


len(regex.findall(r"bob", s, overlapped=True))
# 3

sum(1 for _ in regex.finditer(r"bob", s, overlapped=True))
# 3

Option 2

Apply the sliding window algorithm. Here we use the third-party tool more_itertools.windowed:

import more_itertools as mit


sum(1 for w in mit.windowed(s, 3) if w == tuple("bob"))
# 3

Install the library via > pip install more_itertools.

pylang
  • 40,867
  • 14
  • 129
  • 121