Average word length | SoloLearn: Learn to code for FREE!


Average word length

Hello, The question is asking to write 3 functions; word_count, letter_count, and average_word_length. word_count should take as input a string. It should return the number of words in the string. letter_count should take as input a string. It should return the number of letters in the string. average_word_length should take as input a string. It should return the average length of the words in the string. You can find the average length by dividing the number of letters by the number of words. Your implementation for average_word_length *must* call the function word_count and letter_count. Here is the code I have written; def word_count(a_string): words = 0 for letter in a_string: if letter == " ": words += 1 words += 1 return words def letter_count(a_string): letters = 0 for letter in a_string: if not letter == "": letters += 1 return letters def average_word_length(a_string): return (letter_count(a_string)/word_count(a_string)) a_string = "Up with the white and gold" print(average_word_length(a_string)) But according to the reviewer, the answer should be 3.5 and I am getting 4.333333. Please advise where I am going wrong.

9/1/2020 6:50:13 PM


7 Answers

New Answer


And one more mistake You have to exclude the punctuation marks too! So do it like this: lst = [" ", ";", "-", ".", ","] if letter not in lst: letters += 1 And, import the math module via the statement: import math And then use the function math.ceil on your answer and then show it


Also verify that there are non space at the end of the phrase, otherwise, the presence of a space can add a fictive word when counting.


Nathan Sikati is right! ✅ That's why you should use the split tag So do it like this: def word_count(a_string): return len(a_string.split())


Yeah, more efficient and fast.


If not letter =="": must become If letter !=" ": Take note of the space between the apostroph


If string contains a space then don't consider it as a charecter in letter_count if not letter == " ":


Thank you so much. I was counting the space also in the string while counting the characters. That was the problem. Again, thanks for your input.