r"""증감표·부호표 자동 복원 (13 해설, 12 문제 본문 공용). 변환 전 (글자 좌표로 표 칸이 사라진 모양): $x \cdots - 1 \cdots 3 \cdots$ $f '(x)+ 0 - 0 +$ $f(x)↗ 5 ↘ - 27 ↗$ 변환 후: $\begin{array}{c|ccccc} x & \cdots & - 1 & \cdots & 3 & \cdots \\ \hline f '(x) & + & 0 & - & 0 & + \\ \hline f(x) & \nearrow & 5 & \searrow & - 27 & \nearrow \end{array}$ 규칙 - 머리 줄: '$x …$' 또는 '$t …$' 로 시작하고 \cdots 가 들어 있는 수식. 칸 = \cdots 하나씩, 그 사이 글자 묶음 하나씩. - 다음 줄들: 'f(x)', "f '(x)", "g ''(t)" 처럼 이름(변수) 로 시작하는 수식. - 화살표(↗ ↘ ↑ ↓ 등)가 있으면: 화살표 하나 = 한 칸, 화살표 사이 글자 묶음 = 한 칸. - 없으면: 공백으로 나눈 '+', '-', '0' 하나 = 한 칸 (부호표). - 어느 줄이든 칸 수가 머리 줄과 다르면 그 표는 바꾸지 않는다(손으로 고침). 추측해서 칸을 채우지 않음. """ from __future__ import annotations import re ARROWS = {"↗": r"\nearrow", "↘": r"\searrow", "↑": r"\nearrow", "↓": r"\searrow", "↙": r"\swarrow", "↖": r"\nwarrow"} HEAD = re.compile(r"\$(?P[a-z]) (?P[^$]*\\cdots[^$]*)\$") ROW = re.compile(r"^(?P[a-z](?: *')*\([^()$]*\))(?P.*)$") def _head_cols(body: str): cols, cur = [], [] for tok in body.split(): if tok == r"\cdots": if cur: cols.append(" ".join(cur)) cur = [] cols.append(r"\cdots") else: cur.append(tok) if cur: cols.append(" ".join(cur)) return cols def _row_cols(body: str): body = body.strip() if any(a in body for a in ARROWS): cols, cur = [], [] # 화살표 앞뒤로 공백을 넣어 나눈다 for a in ARROWS: body = body.replace(a, f" {a} ") for tok in body.split(): if tok in ARROWS: if cur: cols.append(" ".join(cur)) cur = [] cols.append(ARROWS[tok]) else: cur.append(tok) if cur: cols.append(" ".join(cur)) return cols toks = body.split() if toks and all(t in ("+", "-", "0") for t in toks): return toks return None MERGE = re.compile(r"(\$[^$]*[↗↘↑↓][^$]*)\$ ?(극대|극소|최대|최소) ?\$") def convert_tables(text: str) -> str: # 화살표 줄 사이에 끼어 수식 밖으로 나간 '극대'·'극소' 를 칸으로 합침: '$f(x)↗$극대 $↘$' -> '$f(x)↗ \text{극대} ↘$' while True: t2 = MERGE.sub(lambda m: m.group(1) + r" \text{" + m.group(2) + "} ", text) if t2 == text: break text = t2 out, pos = [], 0 for m in HEAD.finditer(text): if m.start() < pos: continue head = _head_cols(m.group("body")) rows, end = [], m.end() # 이어지는 '$이름(x)…$' 수식들 while True: m2 = re.match(r" ?\$([^$]*)\$", text[end:]) if not m2: break r = ROW.match(m2.group(1).strip()) if not r: break cols = _row_cols(r.group("body")) if cols is None: break rows.append((r.group("name"), cols)) end += m2.end() if not rows or any(len(c) != len(head) for _, c in rows): continue lines = [m.group("var") + " & " + " & ".join(head)] + [n + " & " + " & ".join(c) for n, c in rows] tex = r"$\begin{array}{c|" + "c" * len(head) + "} " + r" \\ \hline ".join(lines) + r" \end{array}$" out.append(text[pos:m.start()]) out.append(tex) pos = end out.append(text[pos:]) return "".join(out) if __name__ == "__main__": s = r"표로 나타내면 $x \cdots - 1 \cdots 3 \cdots$ $f '(x)+ 0 - 0 +$ $f(x)↗ 5 ↘ - 27 ↗$ 이고" print(convert_tables(s))