Home > Net >  Find the average length of all words in a sentence
Find the average length of all words in a sentence

Time:07-08

Given a string consisting of words separated by spaces (one or more). Find the average length of all words. Average word length = total number of characters in words (excluding spaces) divided by the number of words. My attempt: But input is incorrect, can you help me?

sentence = input("sentence: ")
words = sentence.split()
total_number_of_characters = 0
number_of_words = 0

for word in words:
    total_number_of_characters  = len(sentence)
    number_of_words  = len(words)

average_word_length = total_number_of_characters / number_of_words
print(average_word_length)

CodePudding user response:

When you're stuck, one nice trick is to use very verbose variable names that match the task description as closely as possible, for example:

words = sentence.split()

total_number_of_characters = 0
number_of_words = 0

for word in words:
    total_number_of_characters  = WHAT?
    number_of_words  = WHAT?

average_word_length = total_number_of_characters / number_of_words

Can you do the rest?

CodePudding user response:

I think maybe it should be

for char in word:

Rather than

for char in words:

CodePudding user response:

You may use mean() function to calculate the average.

>>> from statistics import mean()
>>> sentence = 'The quick brown fox jumps over the lazy dog'
>>> mean(len(word) for word in sentence.split())
3.888888888888889

The statistics library was introduced with Python 3.4. https://docs.python.org/3/library/statistics.html#statistics.mean

CodePudding user response:

There is a simpler way to solve this problem. You can get the amount of words by getting len(words) and the number of letters by taking the original sentence and removing all spaces in it (check the replace() method).

Now your turn to piece these infos together!

Edit: Here's an example:

sentence = input("Sentence: ")

words = len(sentence.split())
chars = len(sentence.replace(" ", ""))

print(chars / words)
  • Related