user19401771
user19401771

Reputation:

Find the average length of all words in a sentence

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)

Upvotes: 1

Views: 988

Answers (4)

loggeek
loggeek

Reputation: 143

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)

Upvotes: 0

xqt
xqt

Reputation: 333

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

Upvotes: 1

lawliet1035
lawliet1035

Reputation: 171

I think maybe it should be

for char in word:

Rather than

for char in words:

Upvotes: 1

gog
gog

Reputation: 11347

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?

Upvotes: 2

Related Questions