| """Parse and analyze finite operations represented by Markdown tables.""" | |
| from __future__ import annotations | |
| import json | |
| def _cells(line: str) -> list[str]: | |
| return [cell.strip() for cell in line.strip().strip("|").split("|")] | |
| def analyze_markdown_operation(text: str) -> str: | |
| """Compute core algebraic properties of a Markdown Cayley table.""" | |
| rows = [_cells(line) for line in text.splitlines() if line.strip().startswith("|")] | |
| rows = [row for row in rows if not all(set(cell) <= {"-", ":"} for cell in row)] | |
| if len(rows) < 2 or len(rows[0]) < 2: | |
| raise ValueError("No Markdown operation table found") | |
| elements = rows[0][1:] | |
| mapping: dict[tuple[str, str], str] = {} | |
| for row in rows[1:]: | |
| if len(row) >= len(elements) + 1: | |
| mapping.update({(row[0], b): value for b, value in zip(elements, row[1:])}) | |
| complete = len(mapping) == len(elements) ** 2 | |
| commutative = complete and all( | |
| mapping[a, b] == mapping[b, a] for a in elements for b in elements | |
| ) | |
| identities = [ | |
| e | |
| for e in elements | |
| if complete and all(mapping[e, a] == a and mapping[a, e] == a for a in elements) | |
| ] | |
| associative = complete and all( | |
| mapping.get((mapping[a, b], c)) == mapping.get((a, mapping[b, c])) | |
| for a in elements | |
| for b in elements | |
| for c in elements | |
| ) | |
| noncommuting = [ | |
| [a, b] | |
| for i, a in enumerate(elements) | |
| for b in elements[i + 1 :] | |
| if complete and mapping[a, b] != mapping[b, a] | |
| ] | |
| violating_elements = sorted({item for pair in noncommuting for item in pair}) | |
| return json.dumps( | |
| { | |
| "elements": elements, | |
| "complete": complete, | |
| "commutative": commutative, | |
| "associative": associative, | |
| "identities": identities, | |
| "noncommuting_unordered_pairs": noncommuting, | |
| "elements_participating_in_violations": violating_elements, | |
| }, | |
| ensure_ascii=False, | |
| ) | |
| def solve_markdown_question(text: str) -> str | None: | |
| """Return an exact deterministic answer for recognized operation-table questions.""" | |
| analysis = json.loads(analyze_markdown_operation(text)) | |
| lowered = text.lower() | |
| if ( | |
| "do not commute" in lowered | |
| or "fail to commute" in lowered | |
| or "noncommut" in lowered | |
| or ("counter-example" in lowered and "commutative" in lowered) | |
| or ("counterexample" in lowered and "commutative" in lowered) | |
| ): | |
| return ", ".join(analysis["elements_participating_in_violations"]) | |
| if "commutative" in lowered and ("is " in lowered or "whether" in lowered): | |
| return "Yes" if analysis["commutative"] else "No" | |
| if "associative" in lowered and ("is " in lowered or "whether" in lowered): | |
| return "Yes" if analysis["associative"] else "No" | |
| if "identity" in lowered: | |
| return ", ".join(analysis["identities"]) | |
| return None | |