Counting Bobs!

在MITx: 6.00.1x Introduction to Computer Science and Programming Using Python的week2-problem set1中有一个有趣的Counting Bobs的习题.
他的要求是:
Write a program that prints the number of times the string ‘bob’ occurs in s.
For example, if s = ‘azcbobobegghakl’, then your program should print

Number of times bob occurs is: 2

我就想这还不简单,直接使用字符串类型内建方法string.count不就行了?
所以写出了如下代码:

def istherebob(s):
     count = s.count('bob')
     return count
print ('Number of times bob occurs is:' + str(istherebob('azcbobobegghakl')))

输出之后发现结果是:

这里写图片描述

什么!?说好的结果是2呢,怎么变成1了?
于是赶紧打开书找到了

string.count(str, beg=0, end=len(string)):返回str在string里面出现的次数,如果beg或者end指定返回指定范围内str出现的次数.

可是依然没有明白,于是又在习题的下面找到了解释

That is to say, any time the count method locates your substring ‘bob’, it continues searching at the END of the previous substring.
Therefore, this method will not work for the example string given in the exercise: s = ‘azcbobobegghakl’

So consider what happens as the count method works on the example string
axc**BOB**obegghakl - first ‘bob’ located

Now, the count method will start seeking the next occurrence of ‘bob’ with this string:
‘obegghakl’ - no ‘bob’ located

So this time, the count method will not find another occurrence of ‘bob’, because the ‘b’ which would have begun the next occurrence was stripped out of the string because it was also the FINAL character of the first occurrence of ‘bob’.

What you need is a solution that will find every occurrence of ‘bob’ whether they are overlapped or not. Your solution finds only one instance of ‘bob’, but there are actually two. See below.
s = ‘azc*bob*obegghakl’ - first occurrence
s = ‘azcbo*bob*egghakl’ - second occurrence

恍然大悟啊!原来在应用.count时一旦其检测到’bob’就会把它locate,然后从下一个字符开始检索,所以像’bobob’这样的自然无法检索到.
解决办法呢,就是如下代码.

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

具体来说就是先检索前三个字符,之后从第二个字符开始再检索三个依此类推检索到最后三个字符为止.
真是有趣~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值