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

+2

# Average word length

Given a sentence as input, calculate and output the average word length of that sentence. Sample Input: this is some text Sample Output: 3.5 Explanation: There are 4 words in the given input, with a total of 14 letters, so the average length will be: 14/4 = 3.5 I tried this, and n1 and n2 are correct, but n1/n2 turns out to be wrong. text = input() n1 = len(text) n2 = len(text.split()) print((n1/n2))

+8

As Indira and Simon pointed out, n1 is also counting space. So we can remove unnessary space with replace () text = input() n1 = len(text.replace(" ","")) n2 = len(text.split()) print((n1/n2))

+6

Indira , i thought that you are counting spaces. hmmm.... anyway: what i have seen is that if the input for your code is "yes" , the result shown is 4, which is not correct. using input "yes yes yes", n1 will show 10 letters instead of 9. the reason is that your counter 'n1' is initialized with 1 instead of 0.

+4

U are counting space too here... U are supposed to count letters only in n1.. Do this.. Hope it helps text = input() n1=0 for i in text: if(i!=' '): n1+=1 n2 = len(text.split()) print((n1/n2))

+3

Jieyu Wang , to get the average word length, we need to know how many words the sentence has. we can split the input at the word boundary by using .split(). this will result in a list. the length (number of elements or words) of the list is the number of words. the next step is to calculate the total number of characters. we can use the join() function with the list and create a string from the elements in the list. join() has to be used with an "empty" string. the result of this operation is a string that contains only characters but no spaces. the length of the string is the number of characters. finally you can use the number of words and the number of total characters to get the result. please be aware, that there might be a kind of rounding is required by the task description.

+3

Indira , there might be a risk by counting the spaces (as you have done) and assume that they give you the correct number of words. this will work as long as there are no multiple spaces between the words and as long as there are no leading or trailing white spaces. if we have these accidently issues the calculation will not be correct.

+2

In n1 you're counting spaces as letters.

+2

Lothar I'm not counting spaces there.. it is if (i!=' ' ) means if i is not equal to space then count+1..Otherwise ignore.. It's only counting letters..

+1

Thank you everyone, I tried the replace method and it works!

+1

Lothar Yeah.. n1 will be 0..

0

sum(len(i) for i in text.split()) / len(text.split())