Python Forum
some question!help - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: some question!help (/thread-14583.html)



some question!help - Allen - Dec-07-2018

from codebat:

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



here is my code:
def cat_dog(str):
  for i in range(len(str)-2):
    count_dog =0
    count_cat=0
    if str[i:i+3] == "cat":
      count_cat+=1
    elif str[i:i+3] =="dog":
      count_dog+=1
      
    if count_dog ==count_cat:
      return True
    else:
      return False
where is the err?


RE: some question!help - micseydel - Dec-07-2018

You're doing everything within the loop. You should define the count variables before the loop, update them within the loop, and then only examine them after the loop.