MyC*_*rta 0 python for-loop if-statement
我正在进行一项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):
c=0
d=0
for i in range(len(str)-2):
if str[i:i+3]=="cat":
c=+1
if str[i:i+3]=="dog":
d=+1
return (c-d)==0.0
Run Code Online (Sandbox Code Playgroud)
我看着它,我认为它应该工作,但它失败了一些测试,这告诉我,我不理解Python逻辑如何工作.关于为什么我的解决方案不起作用的任何解释都会很棒.这些都是测试结果:
cat_dog('catdog') ? True True OK
cat_dog('catcat') ? False False OK
cat_dog('1cat1cadodog') ? True True OK
cat_dog('catxxdogxxxdog') ? False True X
cat_dog('catxdogxdogxcat') ? True True OK
cat_dog('catxdogxdogxca') ? False True X
cat_dog('dogdogcat') ? False True X
cat_dog('dogdogcat') ? False True OK
cat_dog('dog') ? False False OK
cat_dog('cat') ? False False OK
cat_dog('ca') ? True True OK
cat_dog('c') ? True True OK
cat_dog('') ? True True OK
Run Code Online (Sandbox Code Playgroud)
解决此问题的一种更简单的方法是使用内置字符串函数,如下所示:
def cat_dog(s):
return s.count('cat') == s.count('dog')
Run Code Online (Sandbox Code Playgroud)