0

What are the other ways to do the same thing in python??

What are the other ways to achieve the same result or task to this code in python: https://code.sololearn.com/c9PYhSZr4d2u/?ref=app

6th Apr 2023, 8:22 PM
Abderrahman Kharroubi
Abderrahman Kharroubi - avatar
3 Respostas
+ 4
You can remove the unwanted characters using a generator expression with a guard (condition): clean = ''.join(c for c in essay if c not in "?@#$%!") Your code works correctly only in the case, when there is only a single whitespace character between each word. Because then the number of whitespaces (along which the split function works) is always one less than the number of words. Therefore the int() will round down the result correctly. But your method can be inaccurate if multiple spaces are between words, or there are multiple lines of text, or even if there are leading or trailing spaces. Example: "hello " To calculate the precise number of characters per word, you could do this: words = essay.split() chars = sum(map(len, words)) avg = chars / len(words)
7th Apr 2023, 5:16 AM
Tibor Santa
Tibor Santa - avatar
+ 3
essay = input() # count the number of characters in the essay num_chars = len(essay)-sum(essay.count(e)for e in "?@#$%!") # count the number of words in the essay num_words = len(essay.split()) # calculating the average avg_char_per_word = num_chars // num_words if num_words else 0 # printing the result print(avg_char_per_word)
6th Apr 2023, 9:25 PM
Solo
Solo - avatar
+ 2
Thanks
8th Apr 2023, 2:03 PM
Abderrahman Kharroubi
Abderrahman Kharroubi - avatar