-3

That program should print the number of times the string "bob" occurs in a string, for example: if s = "azcbobobegghakl", then the program should print 2. it works in some cases but other times it doesn't count correctly. What seems to be the problem?

numbob = 0
i = 0
if len(s) > 2:
    for letter in s:
        if letter == "b":
            if len(s) < 3:
                break
            i = s.index(letter)
            s = s[i: ]
            if s[0] == "b" and s[1] == "o" and s[2] == "b":
                numbob += 1
                s = s[2: ]
            else:
                s = s[i+1: ]
print(numbob)
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
Ash
  • 41
  • 8

2 Answers2

0

You may use re.findall() like so:

import re
>>> len(re.findall("(?=bob)", "azcbobobegghakl"))
2
Bharel
  • 20,128
  • 3
  • 33
  • 62
  • @AshwiniChaudhary Noticed it, using `re.findall()` with lookahead assertion. Probably fastest there is. – Bharel Sep 18 '16 at 20:47
0

perhaps something like this (not very efficient though):

def fn(s):
    cnt = 0
    n = len(s)
    for i in range(0, n):
        if s[i:i+3] == "bob":
            cnt += 1
    return cnt
ewcz
  • 12,064
  • 1
  • 21
  • 44