Problem overview
This lesson builds a tiny grep. The method grep(self, lines, pattern) receives a list of strings and a search text. It returns every line that contains the pattern as a substring, in the original order, joined into one string with newline characters. The match is case-sensitive.
With pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"] the result is "error: foo\nanother error". Printed, that is two lines. If no line matches, the result is the empty string.
The pattern is plain text. In the real tool it is a regular expression by default, but here characters such as . and * have no special meaning: the pattern "a.c" matches "a.c" and doesn't match "abc".
Approach: filter, then join
The job has two parts. First, decide for each line whether to keep it. Second, glue the kept lines together. Python's in operator answers the first part: pattern in line is True when the pattern appears anywhere inside line, not only at the start. For the second part, "\n".join(result) puts a newline between each two items of a list.
Collect the kept lines in a list and join once at the end. Building the string with += would need extra care to avoid a newline at the start or the end.
Step by step
- Create an empty list named
result. Nothing has matched before the first line is checked. - Loop over
lineswithfor line in lines. One pass visits every line. - Test
pattern in lineinside the loop. The check is true when the pattern occurs anywhere in the line. - Append the line to
resultinside theif, so only lines that passed the test are kept. - Return
"\n".join(result)after the loop. When nothing matched, the list is empty and joining an empty list gives"", which is the result the lesson wants.
The solution in Python
class Solution:
def grep(self, lines, pattern):
result = []
for line in lines:
if pattern in line:
result.append(line)
return "\n".join(result)
The returned value is one string that contains \n characters, not a list. Calling print on it shows each kept line on its own row. The separator goes only between lines, so the result has no newline after the last line.
The in test on strings is a substring test, and it is literal. That is why the dot in "a.c" means a dot and nothing else:
print(repr(Solution().grep(["a.c", "abc", "Err"], "a.c")))
print(repr(Solution().grep(["Error: 1", "ok"], "err")))
'a.c'
''
The second call returns the empty string because "err" doesn't match "Error": the capital E is part of the text, and the comparison is case-sensitive.
Complexity
Each in test scans one line, so the time is about O(total length of the lines) times the pattern length in the worst case, and in practice close to the total length. The result list holds references to the kept lines, so extra space is O(k) for k kept lines, plus the final joined string.
Edge cases and common mistakes
- No match. The result is
"", notNoneand not a list. - Returning the list. Forgetting
"\n".join(result)returns a list, which is not the string the lesson expects. - Case.
"err"finds"error"but not"ERROR". - Matching only the start.
line.startswith(pattern)would miss"another error".infinds the pattern anywhere. - Trailing newline. Joining with
"\n"adds no newline after the last line, which is what the expected output has. - An indented
return. Placed inside the loop, it would stop after the first line.
Testing
With lines = ["error: foo", "warning", "another error", "ok"]:
| pattern | result |
|---|---|
"err" | "error: foo\nanother error" |
"zzz" | "" |
The next version builds on this one.
