Problem overview
This is the first version of a small wc project, a copy of the Unix word-count command. In this version the method countLines(self, lines) receives a list of lines and returns how many there are, as an integer.
For ["hello", "world", "foo", "bar", "baz"] the answer is 5. Every entry of the list counts as one line, even an empty string. An empty list has 0 lines.
Approach: the length of the list is the answer
The input is already split into lines, one list item per line. Counting lines therefore means counting items, and Python's built-in len does that directly. No loop and no counter variable are needed.
A loop that adds 1 for each item would give the same number, but it repeats work that len already does, and it adds code in which a bug could hide.
If the text arrives as one string instead, splitting it on newlines first gives the list: "a\n\nb".split("\n") is ['a', '', 'b'], which has 3 lines, the middle one blank. In this lesson that splitting has already been done for you, so the method only counts.
Step by step
The lesson has one step: inside countLines, return how many entries lines has. That is len(lines). The method returns the number and does not print it.
The solution in Python
class Solution:
def countLines(self, lines):
return len(lines)
Some details worth knowing:
lencounts the items of the list, not the characters inside them. For["hello", "world"]it gives 2, whilelen("hello")on a single string gives 5.- It is fast. A list stores its size, so
lendoes not walk through the items, however long the list is. - It gives an integer. The result is an
int, which is what the method's signature promises. - It counts entries, not their content. An empty string is one entry, so
len([""])is 1. - Nested lists count once each.
len([["a", "b"], ["c"]])is 2, because each inner list is a single item of the outer one.
Edge cases and common mistakes
- An empty list.
countLines([])returns0. - Blank lines.
countLines([""])returns1, andcountLines(["", "", ""])returns3. A blank line is still a line, so skipping empty strings would give the wrong answer. - Newlines inside an entry. The method counts list entries, not
\ncharacters. An entry such as"a\nb"still counts once:countLines(["a\nb"])returns1. - Counting characters by mistake. Calling
lenon one line, such aslen(lines[0]), gives the length of that text, not the number of lines. - Printing instead of returning. The lesson's tests read the returned value.
- Off-by-one from a counter. A hand-written loop that starts the counter at 1, or adds after the loop, can be off by one.
lenavoids the whole class of mistakes.
Testing
Try these inputs in the editor above and compare the returned values.
["hello", "world", "foo", "bar", "baz"]gives5.[]gives0.[""]gives1.["", "", ""]gives3.["a\nb"]gives1.
The next version builds on this one.
