1

I've been working on this problem for hours now and I just can't seem to get it. My logic is so off with this one

Objective is to determine the amount of times the word "bob" occurs which is = 2, based on the expected output the problem is asking for.

I just don't know how to get there. I got as far as:

s = 'azcbobobegghakl'
bob = 0
for i in range(len(s)):
    print(s[i: i+3])
print("Number of times bob occurs is: ", bob)

If anyone answers this, please explain to me how you got the answer. Thanks in advance

Sean D
  • 107
  • 1
  • 2
  • 7

3 Answers3

0

Please check the code.

s = 'azcbobobegghakl'
bob = 0
for i in range(len(s)):
    print(s[i: i+3])
    if s[i: i+3] == "bob":
        bob += 1
print("Number of times bob occurs is: ", bob)

The output is,

azc
zcb
cbo
bob
obo
bob
obe
beg
egg
ggh
gha
hak
akl
kl
l
Number of times bob occurs is:  2
youDaily
  • 1,372
  • 13
  • 21
0

The following snippet uses regex library re to find non-overlapping substrings and return all instances found as a list. len() of the list is the number of occurrences.

import re
number_of_bob = len(re.findall("bob", "azcbobobegghakl"))

This approach does not work for overlapping patterns. To find number of overlapping substrings in one line:

number_of_bob = sum(1 for i in range(len(s)-2) if s[i:i+3] == 'bob')
Muposat
  • 1,476
  • 1
  • 11
  • 24
0

Your answer is actual quite simple. You have solved half of the problem. Your iterating over your string by threes. What you need to do know is test if any of those substrings are equal to the string "bob". If so, increment the bob counter by 1:

>>> s = 'azcbobobegghakl'
>>> bob = 0
>>> 
>>> for i in range(len(s)):
    substr = s[i: i + 3]
    # is the current three letter substring equal to "bob"?
    if substr == 'bob':
        # if so, increment the counter by one.
        bob += 1


>>> bob
2
>>> 
Christian Dean
  • 22,138
  • 7
  • 54
  • 87