+ 2

[Answered] Average Word Length problem

I have tried multiple times to solve this question. I've also viewed the other posts on this, but nothin worked out for me. Here is my code: string_to_calc = input() string_to_calc = ''.join(filter(lambda x: x not in '",;!?-', string_to_calc)) len_of_each_word = [len(word) for word in string_to_calc.split()] average_word_len = sum(len_of_each_word) / len(len_of_each_word) if average_word_len % 1 >= 0.5: average_word_len = int(average_word_len + 1) else: average_word_len = int(average_word_len) print(average_word_len)

3rd Nov 2020, 6:13 AM
Harsh Kothari
Harsh Kothari - avatar
6 Respuestas
+ 1
Harsh Kothari , just use the ceil function, you don't need the if-else part. Don't forget to import math module first.
3rd Nov 2020, 6:33 AM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 2
Harsh Kothari , in fact not the same. The if part will be always false because modulus division to 1 will give always 0 and 0 >= 0.5 is false.
3rd Nov 2020, 6:41 AM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 2
from math import ceil as ce phrase = "".join(c for c in input() if c.isalpha() or c == " ") words = phrase.split() print(ce(sum(len(word) for word in words) / len(words)))
3rd Nov 2020, 8:23 AM
David Ashton
David Ashton - avatar
0
TheWh¡teCat 🇧🇬 That worked, but I don't know the reason why it did, cause didn't I do the same thing?
3rd Nov 2020, 6:37 AM
Harsh Kothari
Harsh Kothari - avatar
3rd Nov 2020, 6:37 AM
Harsh Kothari
Harsh Kothari - avatar
0
TheWh¡teCat 🇧🇬 so it wont give the decimal places?
3rd Nov 2020, 6:42 AM
Harsh Kothari
Harsh Kothari - avatar