Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
some question!help
#1
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?
Reply
#2
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020