In: Computer Science
Python Program
complete theprocessString(string)function. 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
PYTHON PROGRAM
#called function
def processString(string):
count = 0
word = 0
# runs the loop
for i in range(len(string)):
# condition is used to keep track of words in a sentence
if(string[i]==" " or string[i] == "."):
word+=1
# condition is used to keep track of characters in a sentence
elif(string[i] != " " and string[i]!="."):
count+=1
# condition checks when character is "." it prints the average
if(string[i]=="."):
#calculates average and print it
print(count/word,end=" ")
word = -1
count = 0
# condition is useful when the sentence is end without any space
if(i == len(string)-1 and string[i]!=" "):
# word is increased
word+=1
#calculates average and print it
print(count/word)
# condition is useful when the sentence is end with a space
if(i==len(string)-1 and string[i] == " "):
# calculates average and print it
print(count/word)
#calling a function and passing the parameter
processString("This is the first sentence. The second sentence starts after the period. Then a final sentence")