1

This was my attempt , I wanted to take a window of 3 letters and walk through the string, But not getting the expected answer of 2 . I am getting into some infinite loop. Wondering why .

def find_bob(s1):
    check_list = 'bob'
    count = 0
    n=0
    cmp_chars=0
    while n<=len(s1):
        while cmp_chars == s1[n:3]:
            if cmp_chars == check_list:
                count += 1
                continue
    return count

s1= 'azcbobobegghakl'
#check_list='bob'
val1 = find_bob(s1)
Quixote_82
  • 25
  • 6

3 Answers3

2

You can use str.find() to find your bobs by using the start param, e.g.:

def find_bob(s):
    check_list = 'bob'
    c, n = 0, s.find(check_list)
    while n != -1:
        c += 1
        n = s.find(check_list, n+1)
    return c

In []:
find_bob('azcbobobegghakl')

Out[]:
2
AChampion
  • 29,683
  • 4
  • 59
  • 75
2

You can use a regex with a zero width lookahead and just count the matches:

>>> import re
>>> s1= 'azcbobobegghakl'
>>> len([m for m in re.finditer(r'(?=bob)', s1)])
2
dawg
  • 98,345
  • 23
  • 131
  • 206
0

Wondering why...

n=0
cmp_chars=0
while n<=len(s1):
    while cmp_chars == s1[n:3]:
        if cmp_chars == check_list:
            count += 1
            continue

n starts at zero and does not change within the loop so the while condition is always True.

while cmp_chars == s1[n:3]: Not sure what to make of this, cmp_chars starts at zero and will never equal a string so this loop condition is always False.

Try

while n<=len(s1):
    if s1[n:n+3] == check_list:
        count += 1
    n = n +1
wwii
  • 23,232
  • 7
  • 37
  • 77