In: Computer Science
n this task, you'll be asked to create a simple for-loop to loop over a simple data construct, in this case, to provide the maximum, minimum, and average length of words in a speech performing a lexicographical analysis not unlike what's used to measure reading level.
Specifications
Python Code :
# Method to count the maximum, minimum and average number of # word from the given string to_analyze def lexicographics(to_analyze): # variable max_words = 0 min_words = 10000000 sum = 0 # iterate over each line and count number of words # if words are greater than max_words, change max_words # if words are less than min_words, change min_words # add number of words into sum lines = 0 for i in to_analyze.strip().split('\n'): words = len(i.split()) if words > max_words: max_words = words if words < min_words: min_words = words sum += words lines += 1 # Calculate the average number of words avg_words = sum/lines # return tuple of max_words, min_words and avg_words return (max_words, min_words, avg_words) if __name__ == '__main__': to_analyze = "I am writing this\nto just check the working of my program." \ "\nI love coding." \ "\nHope you like it." \ "\nPlease upvote the answer." ans = lexicographics(to_analyze) print(f"The maximum number of words per line: {ans[0]} \n" f"The minimum number of words per line: {ans[1]} \n" f"The average number of words per line: {ans[2]}")
Output :
The maximum number of words per line: 8
The minimum number of words per line: 3
The average number of words per line: 4.6
Hope you like it
Any Query? Comment Down!
I have written for you, Please upvote the answer as it encourage us to serve you Best !