0

I am working on a python exercise that asks:

# 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 current code:

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

I look at it and I think it should work but it failed some of the tests, which suggest to me I am not understanding something in how Python logic works. Any explanation as to why my solution is not working would be great. These are all the test results:

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   
2
  • 1
    I think you mean c += 1 and d += 1 instead of c=+1 and d=+1 Commented Jan 15, 2015 at 3:28
  • of course, a simple typo, as clear from gnibbler's answer Commented Jan 15, 2015 at 3:33

3 Answers 3

6

You should have

c += 1 instead of c = +1

and

d += 1 instead of d = +1

Sign up to request clarification or add additional context in comments.

Comments

5

A simpler way to solve this problem would be to use built-in string functions, like this:

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

2 Comments

how is the code making the assumption that they appear next to one another?
I was going to ask the same
3

Here is a one-liner for your program;

cat_dog=lambda str1: str1.count("cat")==str1.count("dog")
print (cat_dog("catcat"))

It will return True if counts are equal, else returning False. But if this confused you, here long one.

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'))

Here is a better method. count is very usefull for your program. Less codes, because readability counts.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.