-1

I'm taking MIT 6.00.1x from edX.org and I'm on problem set 1 problem 2. I'm having trouble getting bob from this variable

s = 'azcbobobegghakl'

I have this code

s = 'azcbobobegghakl'
bobTimes = 0

for bobWord in s:
  if 'b' and 'o' and 'b' in bobWord:
    bobTimes += 1

print(bobTimes)

The code works for this variable, but when you add on another b and o, like this:

s = 'azcbobobegghaklbobddbtto'

It adds one to the bobTimes variable. I don't see how I can extract the word 'bob' from this variable.

Jordan Baron
  • 25
  • 1
  • 1
  • 9

2 Answers2

0

Just get the next 3 characters of the string using python's list slices.

s = 'azcbobobegghakl' #prints 2
s = 'azcbobobegghaklbobddbtto' #prints 3
bobTimes = 0

for i in range(len(s)):
  if s[i:i+3] == 'bob':
    bobTimes += 1

print(bobTimes)
MooingRawr
  • 4,901
  • 3
  • 24
  • 31
0

Could you clarify the extraction requirements? Specifically:

is bobob two bobs, or just one? is bobobob three? or must they all be seperate i.e. bobasdfbobwwwwbob

s.count("bob") would count how many instances of "bob" occur with non overlapping letters. i.e bob is 1, bobbob is 2, bobob is only one because the middle b only counts towards the first one, leaving only ob, but bobobob is 2 better read as bob o bob

you could iterate through the characters one at a time, and check if that character and the next 3 are equal to "bob"

for k,v in enumerate(s):
   if s[k:k+3]=="bob": bobcount+=1

this approach counts bobob as two, and bobobob as three. or you could resort to using regular expressions, but thats not my strong suit, and i'll leave that to someone else to explain/update a bit later with info on that.

deadPix3l
  • 41
  • 2