Two things are wrong:
You are cutting off the last character on each recursive call:
return count_m_recursive(sentence[1:s-1])
Don't limit the call to s-1
, the end index is not included.
You don't want to ignore the rest of the text when you find an m
at the start; your version returns 1
and ignores the rest of the string.
Your function works with:
elif sentence[0] == 'm':
return 1 + count_m_recursive(sentence[1:])
else:
return count_m_recursive(sentence[1:])
or, simplified:
def count_m_recursive(sentence):
if not sentence: # an empty string tests false
return 0
return (1 if sentence[0] == 'm' else 0) + count_m_recursive(sentence[1:])
or even use the fact that bool
is a subclass of int
and True
is 1, False
is 0:
def count_m_recursive(sentence):
if not sentence: # an empty string tests false
return 0
return (sentence[0] == 'm') + count_m_recursive(sentence[1:])
Demo:
>>> def count_m_recursive(sentence):
... if not sentence: # an empty string tests false
... return 0
... return (sentence[0] == 'm') + count_m_recursive(sentence[1:])
...
>>> count_m_recursive('my oh my')
2