Problem overview
This is the second version of the wc command-line tool. The method countWords receives a list of strings, lines, and returns the total number of words in all of them as an integer. A word is a run of characters separated from the next one by spaces or tabs.
For ["hello world", "foo bar baz", ""] the answer is 5: the first line has 2 words, the second has 3, and the empty string has none. Extra spaces at the start, at the end or between words don't create words, a line holding only whitespace counts 0, and an empty list gives 0.
Approach: split each line, count the pieces
Counting spaces doesn't work, because "a b" has two spaces and two words, while " a " has four spaces and one word. It is simpler to cut every line into its words and count the pieces. Python's str.split() does exactly that when you call it with no argument.
With no argument, split() treats any run of whitespace as one separator and ignores whitespace at both ends, so it never returns empty pieces:
print(" a \t b ".split())
print("".split())
print("a b".split(" "))
['a', 'b']
[]
['a', '', 'b']
The third line shows the trap. split(" "), with a space as the argument, cuts at every single space, so two spaces in a row produce an empty string between them, and that empty string would be counted as a word. Use the bare split().
The total is the sum of the piece counts of all lines. A line without words contributes 0, which is what len([]) gives.
Step by step
- Create
totaland set it to 0. A running total starts at zero, before any line has been looked at. - Loop over
lineswithfor line in lines, so every line gets the same treatment. - Add the line's word count.
line.split()gives the list of words andlenmeasures it. Empty and whitespace-only lines add 0 without any special case. - Return
totalafter the loop. Thereturnis not indented under thefor, otherwise the function would stop after the first line.
The solution in Python
class Solution:
def countWords(self, lines):
total = 0
for line in lines:
total += len(line.split())
return total
total += len(line.split()) is shorthand for total = total + len(line.split()). The method belongs to a class, so it takes self first; the code never uses it. The lesson's type hints (List[str], -> int) are optional in Python and don't change what runs.
Because split() splits on all whitespace, a tab between words separates them just like a space does: "a\tb" has two words.
Complexity
Time is O(n) in the total number of characters, because split() reads each line once and the loop touches every line once. The extra space is O(w) for the largest list of words that split() builds for a single line, which is thrown away before the next line.
Edge cases and common mistakes
- Splitting on a single space.
"a b".split(" ")has three pieces, so the count is 3 instead of 2. A line made only of spaces, such as" ", would give several empty pieces instead of 0. - Counting spaces and adding 1. This fails for the empty line (it would give 1) and for any line with leading, trailing or repeated spaces.
- Returning inside the loop. Indent the
returnone level too far and only the first line is counted. - An empty list. The loop doesn't run, so
totalstays 0, which is the right answer.
Testing
Inputs worth trying, with the results the solution returns:
| lines | result |
|---|---|
["hello world", "foo bar baz", ""] | 5 |
[" a \t b ", " "] | 2 |
[] | 0 |
["a\tb"] | 2 |
The next version builds on this one.
