猿问

检查一个字符串在一个特定单词中出现多少次

我正在这个网站上练习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

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


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


元芳怎么了
浏览 199回答 2
2回答

翻阅古今

您不需要创建函数,只需一行就可以了,例如:return s.count('cat') == s.count('dog')

四季花海

没有循环的替代方法:> def cat_dog(str):>&nbsp; &nbsp; &nbsp;total_len = len(str)>&nbsp; &nbsp; &nbsp;cat = str.replace("cat", "")>&nbsp; &nbsp; &nbsp;dog = str.replace("dog", "")>&nbsp; &nbsp; &nbsp;if len(cat) == len(dog):>&nbsp; &nbsp; &nbsp; &nbsp;if len(cat) < len(str):>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if len(dog) < len(str):>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return True>&nbsp; &nbsp; &nbsp;if len(cat) == len(str) and len(dog) == len(str):>&nbsp; &nbsp; &nbsp; &nbsp;return True>&nbsp;>&nbsp; &nbsp; &nbsp;else: return False
随时随地看视频慕课网APP

相关分类

Python
我要回答