Python for循环中的双if条件

Python for循环中的双if条件,python,if-statement,for-loop,Python,If Statement,For Loop,我正在研究一种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): c=0 d=0

我正在研究一种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):
   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
我看着它,我认为它应该可以工作,但它通过了一些测试,这表明我不了解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   

这是你的节目单

cat_dog=lambda str1: str1.count("cat")==str1.count("dog")
print (cat_dog("catcat"))
如果计数相等,则返回True,否则返回False。但如果这让你困惑,这里有一个长的

def cat_dog(str1):
    c="cat"
    d="dog"
    a=str1.count(c)
    b=str1.count(d)
    if a==b:
        return True
    return False
print (cat_dog('catcat'))
这里有一个更好的方法。计数对您的程序非常有用。更少的代码,因为它们很重要


解决此问题的更简单方法是使用内置字符串函数,如下所示:

def cat_dog(s):
    return s.count('cat') == s.count('dog')
你应该

c+=1而不是c=+1


d+=1而不是d=+1

我想你的意思是c+=1和d+=1而不是c=+1和d=+1当然,这是一个简单的打字错误,从gnibbler的回答中可以清楚地看出,代码是如何假设它们彼此相邻的?我想问同样的问题
def cat_dog(s):
    return s.count('cat') == s.count('dog')