summaryrefslogtreecommitdiff
path: root/libremath/arithcheck.py
diff options
context:
space:
mode:
Diffstat (limited to 'libremath/arithcheck.py')
-rw-r--r--libremath/arithcheck.py27
1 files changed, 27 insertions, 0 deletions
diff --git a/libremath/arithcheck.py b/libremath/arithcheck.py
new file mode 100644
index 0000000..d8f78ac
--- /dev/null
+++ b/libremath/arithcheck.py
@@ -0,0 +1,27 @@
+"""Recompute every simple binary step "a op b = c" written in a solution.
+Returns the list of wrong steps (empty if all check out). Times (10:20), ratios (3:4) and
+fractions written inside larger expressions are skipped rather than misread."""
+import re
+NUM = r"\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?"
+STEP = re.compile(rf"(?<![\d.:/,])(?<!\d\s)({NUM})\s*([+\-−–×x*÷/])\s*({NUM})\s*=\s*\$?({NUM})(?![\d:/])(?!,\d)(?!\s*[+\-−–×x*÷/(^])")
+
+
+def bad_steps(text):
+ bad = []
+ for m in STEP.finditer(text):
+ a, op, b, c = m.groups()
+ # skip if this is the tail of a longer expression, e.g. "2 + 3 × 4 = 14"
+ pre = text[max(0, m.start() - 3):m.start()]
+ if re.search(r"[+\-−–×x*÷/(]\s*$", pre): continue
+ a, b, c = (float(v.replace(",", "")) for v in (a, b, c))
+ if op in "×x*": v = a * b
+ elif op == "+": v = a + b
+ elif op in "-−–": v = a - b
+ else:
+ if b == 0: continue
+ v = a / b
+ if abs(v - c) > 1e-6 and abs(round(v, 2) - c) < 0.006: continue # rounded quotient
+ if c == int(a // b): continue # whole-number quotient (remainder stated separately)
+ if abs(v - c) > 1e-6 * max(1, abs(v)) and abs(round(v, 2) - c) > 1e-9:
+ bad.append(m.group(0))
+ return bad