你会得到一个小写字母的字符串str。您需要计算单词doge
在字符串中出现的次数。此外,doge
中的g
可以替换为 a-z 中的任何字母dope
因此它也有效。
这个问题出现在我正在查看的网站上。由于该网站无法讨论该问题,因此我在这里寻求帮助:
def doge_count(str):
count=0
for i in range (0,len(str)):
if (i=="d" and i+1=="o" and i+3=="e"):
count= count+1
return count
对于输入:
2
dog
dogedopedose
您的输出是:
0
0
你的逻辑实际上非常接近。唯一的问题是i
是一个整数,因此比较i=="d" and i+1=="o" and i+3=="e"
将始终为假。你会期望在i==0
时得到一场比赛,但0 !="d"
永远。
解决方法是使用 i
索引到 str
,正如您似乎想要的那样:
if str[i:i+2] == "do" and str[i+3] == "e":
您还需要以不超过字符串末尾的方式进行循环:
for i in range(len(str) - 3):
更强大的解决方案是使用正则表达式。以下模式与所需的字符串匹配:
do[a-z]e
您可以使用re.findall
来计算出现次数:
count = len(re.findall('do[a-z]e]', str))
代码不起作用的原因是您正在检查以下代码行中的整数是否等于字符串:i=="d"
.
这行代码:for i in range (0, len(str))
返回从 0
到 length_of_string - 1
的整数。
您需要做的是检查第 i
个位置的字符串是否等于您想要的搅拌。 如:str[i] == "d"
这将是逻辑中代码的正确版本:
def doge_count(str):
count = 0
for i in range(0, len(str)-3):
if str[i] == "d" and str[i+1] == "o" and str[i+3] == "e":
count = count+1
return count
print(doge_count('dog'))
print(doge_count('dogedopedose'))
您可以使用列表推导式:
>>> [s[i:i+4] for i in range(len(s)-3) if s[i:i+2]=='do' and s[i+3]=='e']
['doge', 'dope', 'dose']
test_patterns='do[a-z]e'
phrase = 'this is doze but Doze again dore then dofe'
list_matches = re.findall(test_patterns,phrase.lower())
print('The number of d(any alphabet)ze : {frequency}'.format(frequency=len(list_matches)))
查找列表中模式的所有匹配项,然后获取列表的计数,您将获得doge或dofe或任何此类的数量
def doge_count(str):i=0计数= 0对于范围(0,len(str)-3)中的 i:如果 str[i]=="d" 和 str[i+1]=='o' 和 str[i+3]=='e' :计数=计数+1返回计数