刚开始学习Python。必须创建一个函数来计算字符串中的子字符串。决定使用字符串模块的count()函数,但它没有做我希望的事情。
似乎count()函数将遍历字符串,如果它确实找到了子字符串,它将移动添加到计数但将继续它在子字符串末尾的迭代。
以下是我运行的代码和测试:
def count(substr,theStr):
counter = 0
counter = theStr.count(substr, 0, len(theStr))
return counter
print(count('is', 'Mississippi'))
# Expected count: 2 pass
print(count('an', 'banana'))
# Expected count: 2 pass
print(count('ana', 'banana'))
# Expected count: 2 test failed: count: 1
print(count('nana', 'banana'))
# Expected count: 1 pass
print(count('nanan', 'banana'))
# Expected count: 0 pass
print(count('aaa', 'aaaaaa'))
# Expected count: 5 test failed: count: 2
答案 0 :(得分:0)
尝试获取所需字符串长度的单个子字符串,并检查它们:
def count(sub, whole):
total = 0
for i in range(0, len(whole)-len(sub)+1):
if sub == whole[i:i+len(sub)]:
total+=1
return total
>>> print(count('is', 'Mississippi'))
2
>>> # Expected count: 2 pass
...
>>> print(count('an', 'banana'))
2
>>> # Expected count: 2 pass
...
>>> print(count('ana', 'banana'))
2
>>> # Expected count: 2 pass
...
>>> print(count('nana', 'banana'))
1
>>> # Expected count: 1 pass
...
>>> print(count('nanan', 'banana'))
0
>>> # Expected count: 0 pass
...
>>> print(count('aaa', 'aaaaaa'))
4
>>> # Expected count: 4 pass
...