File size: 2,967 Bytes
c641d5f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | """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
|