Problem overview
Version 1 of this head project always kept 10 lines. In this version the method takes the count as a second argument: head(self, lines, n) returns the first n lines, joined with newline characters (\n). For this version, n is between 0 and len(lines), so there is no need to handle a count that is too big or negative. When n is 0, the result is an empty string.
For ["alpha", "beta", "gamma", "delta", "epsilon"] and n = 3, the result is 'alpha\nbeta\ngamma', which prints as:
alpha
beta
gamma
Approach: replace the constant with n
The idea is the one from version 1, with the fixed 10 replaced by the variable n. A slice from the start, lines[:n], holds the items at indexes 0 up to but not including n, which is exactly the first n lines. Joining that slice with "\n" gives the result.
The special case takes care of itself. With n = 0, the slice lines[:0] is an empty list, and joining an empty list gives ''. No if is needed, and no loop either: the slice does the counting and the join does the gluing.
Step by step
The lesson has a single step. The method now has two parameters besides self, lines and n, and it returns "\n".join(lines[:n]). The only change from the previous version is that the slice's end is the parameter and no longer the number 10.
The solution in Python
class Solution:
def head(self, lines, n):
return "\n".join(lines[:n])
What to know about it:
- A slice end can be any expression. A variable works the same as a literal number, so
lines[:n]andlines[:3]behave alike whennis 3. - The count is the number of items kept.
lines[:3]holds items 0, 1 and 2, so three lines come back, and the item at index 3 is left out. - The slice is a copy.
lineskeeps all its items after the call. - The method has the same name as in version 1, with a different signature. Each lesson defines its own
Solutionclass, so the two versions don't conflict. Python itself has no overloading: a seconddef headin the same class would replace the first.
Edge cases and common mistakes
n = 0. The result is''. For["a", "b"]andn = 0, the slice is empty, so nothing is joined.nequal to the length. All lines come back:head(["a", "b"], 2)returns'a\nb'.- Using
lines[n]orlines[n - 1]. Those are single items, not the firstn. The colon makes it a slice. - Writing
lines[:n - 1]to "fix" the counting. Indexes start at 0, but a slice end already excludes its own position, so[:n]is already right. Withn = 3,lines[:2]would return only two lines. - Looping and adding a newline after every line. That leaves a newline at the end of the result.
joinputs the separator only between lines. - Mixing up the argument order. The signature is
head(lines, n): the list first, then the count.
Testing
["alpha", "beta", "gamma", "delta", "epsilon"]withn = 3gives'alpha\nbeta\ngamma'.["a", "b"]withn = 0gives''.["a", "b"]withn = 2gives'a\nb'.
The next version builds on this one.
