In: Computer Science
This function takes in a string as a parameter and prints the average number of characters per word in each sentence in the string. Print the average character count per word for each sentence with 1 decimal precision (see test cases below).
Assume a sentence always ends with a period (.) or when the string ends.
Assume there is always a blank space character (" ") between each word.
Do not count the blank spaces between words or the periods as a character.
Two example test cases are:
>>> processString("An example. Dog")
4.5 3.0
(Note that the first sentence has 2 words with a total of 9
characters, so 4.5 characters per word on average. The second
sentence has 1 word of 3 characters, so 3 characters on
average.)
>>> processString("This is the first sentence. The
second sentence starts after the period. Then a final
sentence")
4.4 5.3 4.5
def processString(string):
'''convert string into list and separator is "."'''
string = string.split(".")
answer = 0
''' traverse sentence by sentence from string'''
for sentence in string:
word_count = 0
total_char =0
'''split sentence into word'''
for word in sentence.split():
'''count the total character and total word in each sentence'''
total_char+=len(word)
word_count+=1
''' round is use for printing one value after decimal'''
print(round((total_char/word_count),1),end=" ")
print()
processString("An example. Dog")
processString("This is the first sentence. The second sentence starts after the period. Then a final sentence")
Function "process String" takes a string as a parameter. Then
string is converted in to list of sentences. Now we go through the
each sentence and count number of words and characters.
After counting in one sentence then I print average.
average=total number of character/total word in one sentence
I use round function for printing the average. I pass 1 because I
have to print only one digit after the decimal.
working of round function:
x = round(6.8834,2)
print(x)
output: 6.88
if you like this answer then please upvote it.