Problem overview
This is the first version of a small head project, a copy of the Unix command that prints the beginning of a text. The method head(self, lines) receives a list of lines and returns the first 10 of them, joined with newline characters (\n). If there are fewer than 10 lines, it returns all of them. With no lines at all, it returns an empty string.
Given the thirteen lines "a" through "m", the result is 'a\nb\nc\nd\ne\nf\ng\nh\ni\nj', which prints as the letters a to j, one per row:
a
b
c
d
e
f
g
h
i
j
Approach: slice, then join
There are two jobs: pick at most 10 lines, then glue them into one string. Python has a tool for each.
A slice such as lines[:10] means "from the start up to, but not including, index 10", so it takes the items at indexes 0 to 9. Slicing never raises an error when the list is too short: it simply stops at the end. A list of 3 lines gives all 3, and an empty list gives an empty list.
The string method join then glues the pieces together with "\n" between each two, so the last line has no newline after it. Joining an empty list gives an empty string. Because slice and join both cope with short and empty input, the method needs no if at all.
Step by step
The lesson has one step: return the first 10 lines glued into one string. Reading it from the inside out, lines[:10] takes up to the first 10 items, and "\n".join(...) turns that slice into the result. The method returns that string rather than printing it.
The solution in Python
class Solution:
def head(self, lines):
return "\n".join(lines[:10])
Some details that matter:
- The end of a slice is excluded.
lines[:10]holds exactly 10 items when the list is long enough, not 11. Both[:10]and[0:10]mean the same thing. - A slice is a new list. The original
linesis not changed: afterlines[:2]on["a", "b", "c"], the list still has all three items. - An index past the end is forgiving in a slice only.
lines[10]on a short list raisesIndexError, butlines[:10]never does. - The items must be strings for
join. Joining numbers raises aTypeError.
Edge cases and common mistakes
- Fewer than 10 lines.
head(["a", "b", "c"])returns'a\nb\nc', all three lines. - Exactly 10 lines. All ten come back, and the result is the same as for the thirteen-line example:
headof the lettersatojreturns'a\nb\nc\nd\ne\nf\ng\nh\ni\nj'. - An empty list.
head([])returns''. - Off-by-one in the slice.
lines[:9]would return nine lines andlines[:11]eleven. The number in the slice is the count to keep. - Indexing instead of slicing.
lines[10]is a single item, the eleventh, not the first ten. - A trailing newline. The result does not end with
\n, becausejoinputs separators only between lines.
Testing
- The letters
atom(13 lines) give'a\nb\nc\nd\ne\nf\ng\nh\ni\nj'. ["a", "b", "c"]gives'a\nb\nc'.[]gives''.
The next version builds on this one.
