Initial implementation with unit and integration tests

Reads value1=value2 pairs from a configuration file and replaces every
non-overlapping occurrence of value1 with value2 in a text file, printing
the resulting lines sorted by the number of symbols replaced.

Overlapping patterns resolve to the longest match so the result does not
depend on configuration file ordering. Ties keep their original file order.
This commit is contained in:
2026-08-25 21:21:38 +02:00
commit 40ea68be11
17 changed files with 556 additions and 0 deletions

46
replacer.py Normal file
View File

@@ -0,0 +1,46 @@
"""Core text replacement logic."""
def prepare_pairs(pairs: list[tuple[str, str]]) -> list[tuple[str, str]]:
"""Order the pairs so the longest value1 comes first.
`replace_line` relies on this ordering to select the longest match at
each position, which makes the result deterministic when configuration
values overlap (for example "b" and "bb"). Preparing the pairs once
here keeps that cost out of the per-line loop.
"""
return sorted(pairs, key=lambda pair: len(pair[0]), reverse=True)
def replace_line(line: str, pairs: list[tuple[str, str]]) -> tuple[str, int]:
"""Replace all non-overlapping matches in the line.
At each position the first matching value1 wins, so `pairs` must be
ordered by `prepare_pairs` for the longest match to be selected.
Returns the changed line and the number of symbols replaced.
"""
result = []
replaced_symbols = 0
position = 0
while position < len(line):
match = None
for value1, value2 in pairs:
if line.startswith(value1, position):
match = (value1, value2)
break
if match is None:
result.append(line[position])
position += 1
continue
value1, value2 = match
result.append(value2)
replaced_symbols += len(value1)
position += len(value1)
return "".join(result), replaced_symbols