""" Span merger: given a list of valid line numbers and a list of possible spans, produce a list of output spans that accounts for every line number. Assignment rules ---------------- Each line number is assigned to the span(s) closest to it: distance(line l, span [a, b]) = max(0, a − l, l − b) = 0 if the line is inside the span, a − l if the line is left of the span, l − b if the line is right of the span. A line is assigned to *every* span that achieves the minimum distance. When a line is equidistant between two adjacent spans both spans claim it at assignment time. Tie-breaking at span boundaries ------------------------------- For a given span's intermediate output [start, end]: • start (1st element) – when multiple assigned lines are tied as closest to the span's nominal left boundary, the *smallest* is chosen (biased left). • end (2nd element) – when multiple assigned lines are tied as closest to the span's nominal right boundary, the *largest* is chosen (biased right). Because the intermediate boundaries are simply min / max of the assigned lines these tie-breaking rules are satisfied automatically. Output normalization -------------------- The returned spans are normalized after assignment: • If two consecutive outputs touch at exactly one duplicated boundary point, the earlier span is shrunk so the final output stays disjoint. • If candidate spans overlap enough to create a genuine overlap in the output, those overlapping outputs are merged. Special cases ------------- • Empty line list → empty output. • No possible spans → all lines emitted as one ``missing`` span. • Spans with no lines assigned to them are omitted from the output. """ from __future__ import annotations from typing import TypedDict class SpanResult(TypedDict): start: int end: int missing: bool def _distance_to_span(line: int, start: int, end: int) -> int: return max(0, start - line, line - end) def _normalize_spans(possible_spans: list[list[int]]) -> list[tuple[int, int]]: normalized: list[tuple[int, int]] = [] for idx, span in enumerate(possible_spans): if len(span) != 2: raise ValueError(f"span at index {idx} must contain exactly two integers") start, end = span if not isinstance(start, int) or not isinstance(end, int): raise TypeError(f"span at index {idx} must contain integers") if start > end: raise ValueError( f"span at index {idx} has start > end: [{start}, {end}]" ) normalized.append((start, end)) return sorted(normalized, key=lambda span: (span[0], span[1])) def merge_spans( line_numbers: list[int], possible_spans: list[list[int]], ) -> list[SpanResult]: """ Parameters ---------- line_numbers: Unsorted / duplicate-containing list of valid line numbers. possible_spans: List of [start, end] inclusive span boundaries. Returns ------- List of dicts ``{'start': int, 'end': int, 'missing': bool}``, ordered by start position. Each line is assigned to the span(s) with the smallest ``max(0, a − l, l − b)`` distance. Lines equidistant between two adjacent spans are claimed by *both* at assignment time. The final returned spans are normalized so the output does not contain a duplicated boundary point, and any genuine overlap caused by overlapping candidate spans is merged. The output start / end of each span is the min / max of its assigned lines, which automatically implements the tie-breaking rule: start biased toward smaller values, end toward larger values. Raises ------ ValueError If any span does not contain exactly two integers or if ``start > end``. TypeError If any span boundary is not an integer. """ sorted_lines = sorted(set(line_numbers)) spans = _normalize_spans(possible_spans) if not sorted_lines: return [] if not spans: return [{"start": sorted_lines[0], "end": sorted_lines[-1], "missing": True}] assignments: list[list[int]] = [[] for _ in spans] for line in sorted_lines: min_dist = min(_distance_to_span(line, start, end) for start, end in spans) for idx, (start, end) in enumerate(spans): if _distance_to_span(line, start, end) == min_dist: assignments[idx].append(line) output: list[SpanResult] = [] out_assignments: list[list[int]] = [] for assigned in assignments: if assigned: output.append({"start": assigned[0], "end": assigned[-1], "missing": False}) out_assignments.append(assigned) i = 0 while i < len(output) - 1: if output[i]["end"] == output[i + 1]["start"]: overlap = output[i]["end"] smaller = [line for line in out_assignments[i] if line < overlap] if smaller: output[i]["end"] = smaller[-1] i += 1 else: output.pop(i) out_assignments.pop(i) else: i += 1 i = 0 while i < len(output) - 1: if output[i]["end"] >= output[i + 1]["start"]: output[i] = { "start": output[i]["start"], "end": max(output[i]["end"], output[i + 1]["end"]), "missing": output[i]["missing"] or output[i + 1]["missing"], } output.pop(i + 1) else: i += 1 return output # --------------------------------------------------------------------------- # # Formatting helper # # --------------------------------------------------------------------------- # def format_spans(spans: list[SpanResult]) -> str: parts = [] for s in spans: tag = f"[{s['start']},{s['end']}]" parts.append(tag) return "[" + ", ".join(parts) + "]" # --------------------------------------------------------------------------- # # Smoke-tests # # --------------------------------------------------------------------------- # if __name__ == "__main__": cases = [ # ── Original examples ──────────────────────────────────────────── # { "label": "Example 1 – pre-line absorbed into nearest span; empty span dropped", "lines": [1, 3, 5, 6, 7, 8, 9, 10, 12, 15], "spans": [[2, 5], [6, 15], [16, 20]], "expected": "[[1,5], [6,15]]", }, { "label": "Example 2 – line 5 equidistant → prev span end shrunk from 5→3", "lines": [1, 3, 5, 6, 7, 8, 9, 10, 12, 18], "spans": [[2, 4], [6, 14], [16, 20]], "expected": "[[1,3], [5,12], [18,18]]", }, # ── Edge cases ─────────────────────────────────────────────────── # { "label": "EC-01 empty line list → empty output", "lines": [], "spans": [[1, 5], [6, 10]], "expected": "[]", }, { "label": "EC-02 no spans → all lines become missing groups", # Bug: the old else-branch would double-emit everything. "lines": [2, 3, 7, 8], "spans": [], "expected": "[[2,8]]", }, { "label": "EC-03 all lines left of only span → absorbed as nearest", "lines": [1, 2, 3], "spans": [[10, 20]], "expected": "[[1,3]]", }, { "label": "EC-04 all lines right of only span → absorbed as nearest", "lines": [15, 16, 20], "spans": [[1, 10]], "expected": "[[15,20]]", }, { "label": "EC-05 adjacent spans → each line goes to the span it is inside", "lines": [1, 3, 5, 8], "spans": [[1, 4], [5, 10]], "expected": "[[1,3], [5,8]]", }, { "label": "EC-06 duplicate line numbers → deduplicated before processing", "lines": [3, 3, 5, 5, 7], "spans": [[1, 10]], "expected": "[[3,7]]", }, { "label": "EC-07 line 7 equidistant → prev span end shrunk from 7→3", "lines": [3, 7, 11], "spans": [[1, 5], [9, 15]], "expected": "[[3,3], [7,11]]", }, { "label": "EC-08 empty gap → each line assigned to the span it is inside, no overlap", "lines": [2, 4, 8, 12], "spans": [[1, 5], [7, 15]], "expected": "[[2,4], [8,12]]", }, { "label": "EC-09 single line, span wider than needed → clipped at line", "lines": [5], "spans": [[3, 7]], "expected": "[[5,5]]", }, { "label": "EC-10 line 6 equidistant → prev span end shrunk from 6→2", "lines": [2, 6, 7, 11, 15], "spans": [[1, 4], [8, 12], [14, 20]], "expected": "[[2,2], [6,11], [15,15]]", }, { "label": "EC-11 single span → all lines (pre and inside) absorbed as nearest", "lines": [1, 2, 5, 6, 15], "spans": [[10, 20]], "expected": "[[1,15]]", }, { "label": "EC-12 first span gets no lines; subsequent spans absorb orphans", "lines": [3, 8], "spans": [[1, 2], [5, 7], [10, 15]], "expected": "[[3,3], [8,8]]", }, { "label": "EC-13 line 10 equidistant → prev span end shrunk from 10→5", "lines": [1, 5, 10, 15, 20], "spans": [[3, 8], [12, 18]], "expected": "[[1,5], [10,20]]", }, { "label": "EC-14 overlap where prev span has no smaller line → prev span dropped", # line 7 equidistant between [1,5] and [9,15]: both claim it. # span 0 assigned=[7] only; no line < 7 exists → span 0 is dropped. "lines": [7, 11], "spans": [[1, 5], [9, 15]], "expected": "[[7,11]]", }, { "label": "EC-15 overlapping possible spans → genuine overlap merged in pass 2", # spans [1,8] and [3,10] overlap; lines 4 and 6 are inside both → # both spans claim 4 and 6, so output before pass 2 = [[2,6],[4,9]]. # pass 1 sees 6 != 4 (strict >), skips; pass 2 merges → [[2,9]]. "lines": [2, 4, 6, 9], "spans": [[1, 8], [3, 10]], "expected": "[[2,9]]", }, ] for case in cases: result = merge_spans(case["lines"], case["spans"]) formatted = format_spans(result) status = "✓" if formatted == case["expected"] else "✗" print(f"{status} {case['label']}") print(f" lines: {case['lines']}") print(f" spans: {case['spans']}") print(f" output: {formatted}") print(f" expected: {case['expected']}") print()