Return the number of times that the string
"code"
appears anywhere in the given string, except we’ll accept any letter for the'd'
, so"cope"
and"cooe"
count.
I have achieved this with the following code using regular expressions:
import re
def count_code(str):
exp = '^co[a-z|A-Z]e$'
count = 0
for i in range(len(str) - 1):
if re.match(exp, str[i:i + 4]):
count = count + 1
return count
print count_code('aaacodebbb') # prints 1
print count_code('codexxcode') # prints 2
print count_code('cozexxcope') # prints 2
Is there any other way of achieving this without using regular expression
solution
this is a simple and clean solution for this problem:
def count_code(str):
count = 0
for i in range(len(str)):
if str[i:i+2] == "co" and str[i+3:i+4] == "e":
count+=1
return count
def count_code(str):
a = 0
for i in range(len(str) - 3):
if str[i:i+2] + str[i+3] == 'coe':
a += 1
return a
Using Python String Method ‘count’
def count_code1(str):
counts=0
for i in range(97,123): #all the lowercase ASCII characters
count+= str.count('co'+chr(i)+'e')
return counts
This should work too:
def count_code(str):
counter = 0
for i in range(len(str)-3):
if str[i:i+2] == 'co' and str[i+3] == 'e':
counter +=1
return counter
Answer
One way is you can make every possible string with co*e where * is any alphabet
Like
x=["co"+i+"e" for i in string.lowercase]
Then iterate
for i in x:
if i in <your string>:
count+=<your string>.count(i)
You can try this:
def count_code(str):
x=["co"+i+"e" for i in str.lower()]
count = 0
index = 0
for i in x:
if i in str[index:]:
index = str.find(i)+1
count+=1
return count
print count_code('aaacodebbb') # prints 1
print count_code('codexxcode') # prints 2
print count_code('cozexxcope') # prints 2
You can try also : using Python String Method ‘count’
def count_code1(str):
counts=0
for i in range(97,123): #all the lowercase ASCII characters
count+= str.count('co'+chr(i)+'e')
return counts