Skip to content
Advertisement

Check how many times a string appears in a particular word

I am practicing my python coding on this website. This is the problem

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

This is my code , for some unknown reason , i dont pass all the testcases. I have problems debugging it

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

Advertisement

Answer

You don’t need to creat a function,just a line is enough.like:

return s.count('cat') == s.count('dog')

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement