Build a tiny version of the Unix head command. Given a list of lines, return the first 10 lines joined by newline characters (\n). If the input has fewer than 10 lines, return all of them. If there are no lines at all, return the empty string.
Function signature:
def head(self, lines: List[str]) -> str:
Example:
Input: lines = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"] Output: "a\nb\nc\nd\ne\nf\ng\nh\ni\nj" When printed: a b c d e f g h i j
Get the first 10 elements out of
lines, then join them with "\n". Python slicing is the easiest way to grab the first 10 — and slicing is safe even when the list is shorter.
Use the slice
lines[:10] — this returns up to 10 elements. Then call "\n".join(...) on the slice.
The full solution:
class Solution:
def head(self, lines):
return "\n".join(lines[:10])
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
