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)
Advertisement
Answer
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?