Python for 循环中的 double if 条件

double if condition in a Python for loop

我正在研究一个 python exercise 问题:

# 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"))

如果计数相等,它将 return True,否则 return 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'))

这是一个更好的方法。 count 对您的程序非常有用。更少的代码,因为 readability 很重要。

print (cat_dog('catcat')) -False
print (cat_dog('catdog')) -True

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

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

你应该

c += 1 而不是 c = +1

d += 1 而不是 d = +1