我正在这个网站上练习python编码。这就是问题Return True if the string "cat" and "dog" appear the same number of times in the given string. cat_dog('catdog') → Truecat_dog('catcat') → Falsecat_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
2 回答

四季花海
TA贡献1811条经验 获得超5个赞
没有循环的替代方法:
> def cat_dog(str):
> total_len = len(str)
> cat = str.replace("cat", "")
> dog = str.replace("dog", "")
> if len(cat) == len(dog):
> if len(cat) < len(str):
> if len(dog) < len(str):
> return True
> if len(cat) == len(str) and len(dog) == len(str):
> return True
>
> else: return False
添加回答
举报
0/150
提交
取消