user2284926
user2284926

Reputation: 651

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

Upvotes: 1

Views: 2378

Answers (3)

Farha Rubena
Farha Rubena

Reputation: 1

def cat_dog(str):
    count_cat = str.count('cat')
    count_dog = str.count('dog')
      
    if count_cat == count_dog:
        return True
    else:
        return False

Upvotes: 0

Rafael Sartori
Rafael Sartori

Reputation: 11

An alternative without loop:

> def cat_dog(str):
>     total_len = len(str)
>     cat = str.replace("cat", "")
>     dog = str.replace("dog", "")
>     if len(cat) == len(dog):
>       if len(cat) < len(str):
>         if len(dog) < len(str):
>           return True
>     if len(cat) == len(str) and len(dog) == len(str):
>       return True
> 
>     else: return False

Upvotes: 0

JZAU
JZAU

Reputation: 3567

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

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

Upvotes: 5

Related Questions