pippy
New Member
Posts: 6
|
Post by pippy on Feb 28, 2014 15:07:32 GMT
Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s.
Is this the correct way to think this through:
bobs = 0 Move through string until you come to a 'b',
if the next character is an 'o', look at the next character, if that character is a 'b', increase 'bobs' by 1 if the next character is not an 'o', move onto the next character print 'The number of bobs: %d' % bobs
|
|
|
Post by batmanbury on Mar 2, 2014 10:47:11 GMT
Your logic looks sound to me, as long as you're looking at a single character at a time at the beginning.
There are a number of ways to do it. You could also check 3 indexes at a time while looking for 'bob' like this:
[012],[123],[234],[345],[456]...
|
|
|
Post by andreareina on Mar 2, 2014 23:36:00 GMT
Remember to account for the case where the last "b" can also be the first of another "bob"
|
|
|
Post by batmanbury on Mar 3, 2014 9:05:37 GMT
Remember to account for the case where the last "b" can also be the first of another "bob" Good point. "bobobobob" is actually 4 bobs. If you're iterating over each character, one by one, that should take care of it naturally.
|
|
|
Post by nick3499 on Jan 11, 2017 18:23:47 GMT
here are a couple of ways to solve that:
s = 'aksjdfhkjadfboboblkajsdhfkljasdkfs'
count = 0 p = 0
while s.find('bob', p) != -1: p = s.find('bob', p) p += 1 count += 1
print("Number of times bob occurs is: " + str(count))
s = 'obobcobooloafbobb' count = 0
for i in range(len(s)): if s[i] == 'b' and not i >= (len(s) - 2): if s[i + 1] == 'o': if s[i + 2] == 'b': count += 1
print("Number of times bob occurs is: " + str(count))
|
|