131k views
2 votes
(count_word_lengths_test: 2 points). Write a function count_word_lengths(s) that, given a string consisting of words separated by spaces, returns a list containing the length of each word. Words will consist of lowercase alphabetic characters, and they may be separated by multiple consecutive spaces. If a string is empty or has no spaces, the function should return an empty list.

User Undg
by
5.2k points

1 Answer

5 votes

Answer:

The solution code is writing in Python.

  1. import re
  2. def count_word_lengths(s):
  3. processed_str = re.sub(' +', ' ', s)
  4. count = 0
  5. word_list = processed_str.split(" ")
  6. word_length_list = []
  7. if(len(word_list) == 1):
  8. return []
  9. else:
  10. for x in word_list:
  11. word_length_list.append(len(x))
  12. return word_length_list
  13. print(count_word_lengths("i have a dream"))

Step-by-step explanation:

Since this program is expected to handle multiple consecutive spaces, we need to import Python regular expression module, re (Line 1). The usage of re is to use its sub method to substitute those multiple spaces with single space ' ' and assigned the modified string to variable processed_str (Line 4).

Next, use the string split() method to transform the processed_str into a list of individual words using single space " " as separator and assign the list to variable word_list (Line 7).

If the word_list contains only one word, this means the input string is either empty or no spaces and therefore it return empty list (Line 10). Otherwise, the program will proceed to a for loop that traverse through each word in the word_list and use len() method to get the length of the individual word and add the length value to the word_length_list (Line 13-14). At last, return the word_length_list as output (Line 16).

We can test the function using a sample string as in Line 19 and the output is [1, 4, 1, 5].

User Lynnmarie
by
5.1k points