首页 > 解决方案 > Getting errors in a python code

问题描述

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?

标签: python-3.x

解决方案


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.


推荐阅读