检查字符串在特定单词中出现的次数

use*_*926 0 python debugging

我正在这个网站上练习我的 python 编码。这就是问题

Return True if the string "cat" and "dog" appear 
the same number of times in the given string. 

cat_dog('catdog') ? True
cat_dog('catcat') ? False
cat_dog('1cat1cadodog') ? True
Run Code Online (Sandbox Code Playgroud)

这是我的代码,由于某些未知原因,我没有通过所有测试用例。我在调试时遇到问题

def cat_dog(str):

    length=len(str)-2
    i=0
    catcount=0
    dogcount=0



    for i in range (0,length):
        animal=str[i:i+2]

        if ("cat" in animal):
            catcount=catcount+1

        if ("dog" in animal):
            dogcount=dogcount+1

    if (dogcount==catcount):
        return True
    else:
        return False
Run Code Online (Sandbox Code Playgroud)

JZA*_*ZAU 5

你不需要创建一个函数,一行就足够了。比如:

return s.count('cat') == s.count('dog')