Hi all.
I have been doing the practice questions for strings in Python. Here is one that I’m stuck with conceptually. Found here.
Here is the specific question:
Write a function called
m_word_count
that takes a string as an input and returns a count of the words in the string that start with the letter M.For example, if
my_sentence = "My gosh, what a beautiful Monday morning this is."
, thenm_word_count(my_sentence)
should return3
.
My code is below:
my_sentence = "My gosh, what a beautiful Monday morning this is."
def m_word_count(strng):
count = 0
ms = my_sentence.upper().split(" ")
for word in ms:
if word[0] == "M":
count += 1
return count
print(m_word_count(my_sentence))
My thought process is as follows:
Split string into seperate items in a list with uniform case to prevent differing ASCII values, then I will iterate through the list and create a condition if list item begins with “M” using index of [0]. If it is true, it will add 1 to the count variable until all items in list have been iterated.
My code above returns “3”, which is what should be returned. I tried adding extra words to the “my_sentence” string with upper and lower case "M"s to test if my function would work outside of the given string.
It gives the right count, but I am still getting an error:
Your
m_word_count
function did not correctly count the number ofm
s
This leads me to believe that the way I have constructed my function is incorrect.
Can someone please explain to me why my function might not be accepted by the tests they have in place for this question?
And also, if my thought process function is conceptually flawed?