-1

Started learning python a couple weeks back. Wrote a python program to count the number of times the sequence 'bob' appears in a string s:

s=input('Enter String')
a=0
b=1
c=2
count=0
for var in s:
    if(s[a]=='b' and s[b]=='o' and s[c]=='b'):
     count+=1
    if (c<(len(s)-1)):
     a+=1
     b+=1
     c+=1
print(count)

The output shows up properly for strings like 'bobbooboboooblobobbobbc'. But, for strings like 'nqsbobobdbtobob', I'm getting output count two more than the actual count of number of occurrences of 'bob'. Can someone please tell me what the cause might be?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
RS404
  • 3
  • 1
  • 1
    Welcome to SO! Please help the people understanding your question by at least applying some proper formatting and syntax hightlighting. Have a look at our guid [How to ask](https://stackoverflow.com/help/how-to-ask) – MrLeeh May 01 '18 at 21:47
  • How many occurrences of "bob" do you expect to find for "nqsbobobdbtobob"? I count 3, with starting points at character 4, 6, and 13. – Jason Aller May 02 '18 at 01:46
  • 3, but getting 5 in the output of the code – RS404 May 02 '18 at 06:15

1 Answers1

0

The quick answer is to use a custom built function for this as is shown in this post:

example of .count(substring)

But my guess is that you aren't all that interested in finding "bob" in a longer string, but more so figuring out how python works and your logic.

I think that the numbers are off because you are iterating over all of s and then catching the 2 extra characters with your second if statement. It might be cleaner to just do that in the for loop itself:

for a in range(0,len(s)-3):
   b = a + 1
   c = b + 1 
   ...

and follow that logic.

sahutchi
  • 2,223
  • 2
  • 19
  • 20