I am practicing my python coding on this website. This is the problem
JavaScript
x
7
1
Return True if the string "cat" and "dog" appear
2
the same number of times in the given string.
3
4
cat_dog('catdog') → True
5
cat_dog('catcat') → False
6
cat_dog('1cat1cadodog') → True
7
This is my code , for some unknown reason , i dont pass all the testcases. I have problems debugging it
JavaScript
1
23
23
1
def cat_dog(str):
2
3
length=len(str)-2
4
i=0
5
catcount=0
6
dogcount=0
7
8
9
10
for i in range (0,length):
11
animal=str[i:i+2]
12
13
if ("cat" in animal):
14
catcount=catcount+1
15
16
if ("dog" in animal):
17
dogcount=dogcount+1
18
19
if (dogcount==catcount):
20
return True
21
else:
22
return False
23
Advertisement
Answer
You don’t need to creat a function,just a line is enough.like:
return s.count('cat') == s.count('dog')