Problem overview
This is the third version of the wc tool. The method countChars receives a list of strings, lines, and returns the total number of characters in all of them. The convention is simple: add up the length of each line, and don't count the newlines that would separate the lines in a file. Spaces and tabs inside a line count as one character each.
For ["hello", "world"] the answer is 10, because each word has 5 characters. An empty line adds 0 and an empty list gives 0. The lesson only uses plain ASCII text, where one character is one byte.
Approach: sum the lengths
The answer is the sum of len(line) over all lines. You could write a loop with a running total, as in the previous version, but this lesson introduces the shorter Python form: a generator expression passed to sum.
len(line) for line in lines reads like the loop header, with the value to produce written first. It hands out one length at a time, and sum adds them as they arrive. Nothing needs to be stored in a list first.
lines = ["a b", "", "\tx"]
print([len(line) for line in lines])
print(sum(len(line) for line in lines))
[3, 0, 2]
5
The first line shows the individual lengths in a list; the second adds them. "a b" is 3 characters, the empty line is 0, and "\tx" is 2, because the tab counts as one character.
Step by step
- Return the sum of the lengths. The whole method is one
return. The generator expression produceslen(line)for everylineinlines, andsumadds them. Whenlinesis empty,sumof nothing is 0, so no special case is needed.
The solution in Python
class Solution:
def countChars(self, lines):
return sum(len(line) for line in lines)
When a generator expression is the only argument of a function call, it doesn't need its own parentheses: sum(len(line) for line in lines) is enough. It does the same as this loop:
total = 0
for line in lines:
total += len(line)
return total
In Python 3, len of a string counts characters (code points), not bytes. For ASCII text the two agree. A string such as "é" is one character but takes two bytes when encoded as UTF-8, which is why the real wc -c and wc -m can disagree.
Complexity
Time is O(m) in the number of lines, since len of a string takes constant time in Python. Extra space is O(1), because the generator produces one number at a time.
Edge cases and common mistakes
- Counting newlines. The real
wc -madds one per line break. Here the total is only the sum of the line lengths, so["hello", "world"]is 10, not 11 or 12. - Counting words instead.
len(lines)is the number of lines, andlen(line.split())the number of words. Neither is the character count. - Using a list where a generator will do.
sum([len(line) for line in lines])gives the same number but builds a list first. The version without brackets is the idiomatic one. - Empty input.
[]gives 0, and so does[""].
Testing
| lines | result |
|---|---|
["hello", "world"] | 10 |
["a b", "", "\tx"] | 5 |
[] | 0 |
The next version builds on this one.
