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
3 Réponses
+ 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)
+ 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)
+ 2
Thanks