You receive text generated by an LLM together with a collection of phrases taken from source material. Locate exact occurrences of those phrases and surround the corresponding portions of the text with <yellow> and </yellow>.
The interview version commonly has two stages:
The first stage centers on combining character intervals. The second stage checks whether merged spans still retain the source phrases that produced them.
The specifications below settle the matching, adjacency, counting, and ordering details for this version.
Create this function:
def highlight_matches(document: str, sources: list[str]) -> str:
pass
A phrase is considered a match only when its entire text appears in document with valid word boundaries.
For this task:
"blue" does not match the occurrence of those letters within "blueprint".Produce the original document with each combined matching span enclosed by <yellow> and </yellow>.
document = "The quick brown fox jumps over the lazy dog."
sources = ["quick brown", "brown fox jumps"]
highlight_matches(document, sources)
# Returns:
# "The <yellow>quick brown fox jumps</yellow> over the lazy dog."
The phrases share the word "brown", so their overlapping ranges are emitted as one highlighted span.
document = "blueprint" and sources = ["blue"], nothing is highlighted because "blue" is not a whole word there.sources remain distinct sources because citation identity is based on the positions in the input list.document without modification.Modify the implementation so that every highlighted span records which sources helped create it.
For each source, do the following:
[source_id].Return the tagged text, the count for every source, and the citation list associated with each highlighted span.
from dataclasses import dataclass
@dataclass
class CitationResult:
tagged_document: str
counts: dict[int, int]
citations: list[list[int]]
def highlight_with_citations(
document: str,
sources: list[str],
) -> CitationResult:
pass
document = "The quick brown fox jumps over the quick blue fox."
sources = [
"quick brown", # source 0, one occurrence
"brown fox jumps", # source 1, one occurrence
"quick", # source 2, two occurrences
"blue", # source 3, one occurrence
]
result = highlight_with_citations(document, sources)
result.tagged_document
# "The <yellow>quick brown fox jumps</yellow>[2][0][1] over the "
# "<yellow>quick blue</yellow>[2][3] fox."
result.counts
# {0: 1, 1: 1, 2: 2, 3: 1}
result.citations
# [[2, 0, 1], [2, 3]]
Source 2 comes first in both citation arrays because its global frequency is higher. The remaining sources have equal frequencies, so their smaller input indices come first.