Reputation: 21
i'm using python 3 and i would like to know how to count the amount of times a set of 3 letters comes up in a sentence:
con = ""
count = 0
for i in mystery_string:
if i == "c":
con = "c"
if i == "a" and con == "c":
con = "ca"
if i == "t" and con == "ca":
con = "cat"
if con == "cat":
count +=1
con = ""
print (count)
this is the code i have so far, however it doesn't seem to work for every case can someone help me
the thing i also need to explain is that i cannot use the builtin function count()
Upvotes: 0
Views: 406
Reputation: 11
mystery_string = "my cat your cat"
count = 0
current_search_letter = "c"
if letter == "c":
current_search_letter = "a"
elif letter == "a" and current_search_letter == "a":
current_search_letter = "t"
elif letter == "t" and current_search_letter == "t":
count += 1
current_search_letter = "c"
else:
current_search_letter = "c"
print(count)
Upvotes: 0
Reputation: 559
you can use slicing:
word='cat'
count = 0
for i in range(len(mystery_string)-len(word)+1):
if mystery_string[i:i+len(word)]==word:
count +=1
print (count)
Upvotes: 1