Files
Technical-Assignment-CQG-Br…/replacer.py
Martin Stajnko dc401be837 fix: reject a configuration entry with an empty value1
A line such as "=z" parsed into the pair ("", "z"). An empty value1
matches at every position and consumes nothing, so the scan in
replace_line never advanced and the program looped forever, printing
nothing and growing its output buffer until it was killed.

Reject the entry while parsing, reporting the offending line the same
way as a line with no "=" at all, and document the termination
invariant the loop depends on.
2026-08-26 14:35:32 +02:00

49 lines
1.5 KiB
Python

"""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
# Terminates because every branch below advances `position`, which
# holds only while no value1 is empty. `load_config` rejects those.
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