为猫计算字符串中的单词

时间:2020-06-13 01:27:57

标签: python algorithm

我试图计算单词或字符串“ cat”在给定的可变字符串p中出现的次数。但是,尽管我认为我的逻辑是正确的,但是我的代码并不正确。我需要输出打印一次“出现的猫数:2”。任何帮助或建议将不胜感激!

p = 'thecatisnapingandtheothercatiseating'
count = 0
word = 'cat'
for i in range(0, len(p)+1):
    if p[i:i+3] == word:
        count += 1
        print('Number of times cat occurs: ' + str(count))

3 个答案:

答案 0 :(得分:2)

您只需要将打印内容移至for循环之外:

p = 'thecatisnapingandtheothercatiseating'
count = 0
word = 'cat'
for i in range(0, len(p)+1):
    if p[i:i+3] == word:
        count += 1


print('Number of times cat occurs: ' + str(count))
>>>Number of times cat occurs: 2

看@Tim,补充并扩展@ pythonic833答案,您的for循环语句应为for i in range(0, len(p)-2):,为此i=0,1,2,...,len(p)-3, 因为例如以p = 'thecatisnap', len(p)=11为例,您将要比较这样的字符串:

'the'=='cat', 'hec'=='cat', 'eca'=='cat', ... , p[i:i+3] == 'cat'

因此,正如@ pythonic833所说,您只需要迭代最后一个字母的第三位, 因为在那之后,您将比较少于三个字母的单词:

#iterarion 
i=len(p)-3=8
p[i:i+3]='nap'

Compare 'nap'=='cat'

#iterarion 
i=len(p)-2=9
p[i:i+3]='ap'

Compare 'ap'=='cat'

#iterarion
i=len(p)-1=10
p[i:i+3]='p'

Compare 'p'=='cat'

#iteration 
i=len(p)=11
p[i:i+3]=''
Compare ''=='cat'

因此,在i=len(p)-2迭代之后,继续比较就没有意义了。

答案 1 :(得分:1)

您也可以使用re.findall

import re

p = 'thecatisnapingandtheothercatiseating'
word = 'cat'
print(f'Number of times cat occurs: {len(re.findall(word, p))}')

打印

Number of times cat occurs: 2

或者更具可读性的版本:

import re

p = 'thecatisnapingandtheothercatiseating'
word = 'cat'
count = len(re.findall(word, p))
print(f'Number of times cat occurs: {count}')

您自己的代码也可以,只需稍作修改即可:

p = 'thecatisnapingandtheothercatiseatingcat'
count = 0
word = 'cat'
for i in range(-~len(p) - len(word)):
    if p[i:i + len(word)] == word:
        count += 1
print(f'Number of times cat occurs: {count}')

或者:

p = 'thecatisnapingandtheothercatiseatingcat'
count = 0
word = 'cat'
for i in range(len(p) + 1 - len(word)):
    if p[i:i + len(word)] == word:
        count += 1
print(f'Number of times cat occurs: {count}')

-~len(p)是用于递增的按位运算。 -~i仅表示i + 1

答案 2 :(得分:1)

总是可以使用count方法:

p = 'thecatisnapingandtheothercatiseating'
word = 'cat'
print(f'Number of times cat occurs: {p.count(word)}')

输出:

Number of times cat occurs: 2