0

Check the original domain before trusting a cancelled factor in Python

A cancelled factor can make an equation look easier while quietly changing which inputs are allowed. Consider (x² − 1)/(x − 1) = 2. Factoring the numerator suggests x + 1 = 2, whose candidate is x = 1. Unfortunately, the original denominator is zero there. A program that substitutes only into the simplified expression can approve an answer to a different problem. This small example is useful because we can inspect every assumption without needing a symbolic algebra package.

This tutorial builds a deliberately narrow Python checker for candidate answers. It does not solve arbitrary equations, interpret worksheet photographs, or certify a generated explanation. It evaluates two named expressions using exact rational arithmetic and separates a failed comparison from an input outside the original domain. The limited scope makes the behavior easier to test. You can use the same design habit when reviewing calculator output, a worked solution, or a proposed answer supplied by an AI assistant.

Keep the problem and its domain together

Treat an equation as more than the final line of an explanation. Keep its original left side, original right side, and restrictions together. For our rational example, the restriction is x != 1, not a note that can be discarded after cancellation. A cancellation is valid only where the cancelled factor is nonzero. That restriction survives even if the printed expression no longer contains a denominator. Substitution must therefore check the restriction before doing any division.

We will also support the ordinary linear equation 2x + 3 = 11. Its integer candidate 4 provides a positive control: the checker needs at least one example that should pass. The cancelled-factor example provides a domain failure, while candidate 2 provides a defined but incorrect value. Keeping these three situations separate prevents a misleading test suite in which every example happens to fail and a completely broken implementation appears successful.

Choose an explicit input grammar

For the demonstration, a candidate is one integer or one rational token, such as 4, -3/2, or -2/-4. Outer whitespace is ignored; internal whitespace is not. Decimal notation, scientific notation, arithmetic expressions, and function calls are deliberately rejected. This is not a claim that those mathematical forms are invalid. It is an interface decision that keeps parsing separate from checking and gives the caller a clear, reproducible contract.

Using Python's Fraction preserves exact values for the accepted grammar. A token such as 1/3 does not become a nearby floating-point approximation. That makes equality appropriate for these particular rational expressions. It would not justify exact equality for measured lengths, numerical integration, or rounded sensor readings. Those problems require an explicit error model and tolerance policy. The numeric representation should follow the problem rather than become a universal rule copied into every application.

We cap the token length and the normalized numerator and denominator. These small limits keep a toy command-line tool from accidentally accepting enormous arithmetic inputs. They are not a complete service-level defense: a real network service would also need request limits, timeouts, isolation, and monitoring. Notice that normalization happens before the numerator bound. A large unreduced token can reduce to a small fraction; the initial string-length cap still bounds that preliminary parsing work.

Implement named checks instead of evaluating strings

Save the following program as exact_check.py. There is intentionally no eval, dynamic import, or user-supplied Python expression. The caller chooses an equation identifier from a fixed implementation. Adding another equation means adding its original expression and its restrictions in code, then extending the tests. This is less flexible than a symbolic engine, but the trust boundary is visible: the caller supplies a rational candidate, not executable instructions or a replacement problem.

from fractions import Fraction
import json
import re
import sys

LIMIT = 10**12
TOKEN = re.compile(r"[+-]?[0-9]+(?:/[+-]?[0-9]+)?", re.ASCII)


def parse_exact(raw: str) -> Fraction:
    text = raw.strip()
    if len(text) > 48 or TOKEN.fullmatch(text) is None:
        raise ValueError("Use one integer or fraction token")
    try:
        if "/" in text:
            numerator, denominator = text.split("/")
            value = Fraction(int(numerator), int(denominator))
        else:
            value = Fraction(int(text))
    except (ValueError, ZeroDivisionError) as exc:
        raise ValueError("Invalid rational number") from exc
    if abs(value.numerator) > LIMIT or value.denominator > LIMIT:
        raise ValueError("Candidate exceeds demonstration limits")
    return value


def check_candidate(equation: str, raw: str) -> dict:
    x = parse_exact(raw)
    result = {"equation": equation, "candidate": str(x)}
    if equation == "linear":
        left, right = 2 * x + 3, Fraction(11)
    elif equation == "cancelled_factor":
        if x == 1:
            return {**result, "status": "outside_domain"}
        left, right = (x * x - 1) / (x - 1), Fraction(2)
    else:
        raise ValueError("Unknown equation identifier")
    return {
        **result,
        "left": str(left),
        "right": str(right),
        "status": "matches_original" if left == right else "not_a_solution",
    }


if __name__ == "__main__":
    if len(sys.argv) != 3:
        raise SystemExit("usage: exact_check.py EQUATION CANDIDATE")
    try:
        output = check_candidate(sys.argv[1], sys.argv[2])
    except ValueError as exc:
        output = {"status": "invalid_input", "reason": str(exc)}
    print(json.dumps(output, sort_keys=True))

The domain branch returns before evaluating the rational expression. This is more informative than catching every exception and calling the candidate wrong. The result also keeps the equation identifier and a canonical candidate string. Where evaluation is defined, the left and right values are included as exact strings. A reviewer can inspect those values without reconstructing a floating-point formatting decision or guessing which transformed expression the program actually evaluated.

Read three different outcomes honestly

Run python exact_check.py linear 4. The result should contain matches_original, with left and right both equal to 11. Then run python exact_check.py cancelled_factor 1: the result should be outside_domain, and it should not include computed sides. Finally, run python exact_check.py cancelled_factor 2. This input is defined, but the left side is 3 and the right side is 2, so the status is not_a_solution.

These examples demonstrate why a single Boolean can be a poor interface. A false result might mean an incorrect candidate, a forbidden input, a parser failure, or an unsupported equation. The status vocabulary keeps those meanings apart. The command-line wrapper reports malformed input as invalid_input; it does not silently turn a parsing error into a mathematical conclusion. A downstream interface should preserve that distinction instead of coloring all nonmatching outcomes red with the same explanation.

Do not reinterpret matches_original as proof of an entire derivation. Substitution can establish that one candidate satisfies these implemented expressions. It does not prove that all solutions were found, that an earlier transformation was reversible, or that the original question was transcribed correctly. The rational example actually has no valid solution: the only candidate from the simplified equation is excluded. Establishing that completeness statement still requires reasoning about the transformation and the restricted domain.

Test the boundaries, not just the happy path

A useful test set includes the positive control, the forbidden value, a defined mismatch, negative fractions, and a normalized double-negative denominator. It should also reject a zero denominator, a malformed token containing two slashes, unsupported decimal notation, a value outside the demonstration limits, and an unknown equation identifier. These cases exercise different branches. Changing only the candidate's digits several times would create more test rows without necessarily increasing the behavior covered.

I ran the accompanying implementation locally against these categories before preparing this article. That is a test of this small checker, not a benchmark of an AI product or a claim about arbitrary algebra. Keep that distinction when documenting your own experiments. State the inputs, expected outcomes, and limitations. If you change the grammar or add an equation, rerun the tests and update the examples instead of retaining a success statement that refers to an older implementation.

For a larger project, place tests in a separate file and keep the checking functions importable without running the command-line interface. Assert exact statuses and exact side strings. Assert that a domain failure does not accidentally acquire computed values after a refactor. Avoid snapshotting an entire console session when a few structural assertions express the contract more clearly. A small deterministic suite should be easy to run whenever someone edits the original expression or its domain predicate.

Use the checker as one layer in a study workflow

Start with a transcription record: write the original equation, parentheses, units, and restrictions before requesting or reading a proposed solution. Check the transcription against the source question. Next, obtain a candidate and preserve the explanation separately. Finally, substitute into the original problem using an appropriate independent method. The checker here covers only one narrow part of that last step. It cannot repair a misread exponent, an omitted diagram constraint, or a problem copied into the wrong equation identifier.

Disclosure: I am project-associated with Math AI, linked here as AI homework help for math. This article was prepared with AI assistance and is not an independent review. Math AI accepts typed math questions, word problems, and problem photos and can provide step-by-step explanations for practice. Free credits are limited, and extra usage or features may cost money. Its answers can be wrong. Use explanations as material to examine, respect school or course rules, and do not treat fluent text as a substitute for checking the original question.

Math AI website illustration, not a benchmark or a verification result

That association does not change the checker contract. No request to the Math AI service is made by this program, and no product output was used as ground truth in the local tests. The examples use synthetic equations rather than student records or uploaded worksheets. If you adapt the workflow for real study materials, keep private documents and identifying information out of public test fixtures, screenshots, and issue reports unless you have the necessary permission to share them.

Know when this design stops being enough

The implementation recognizes only rational candidates and two explicit equations. It does not represent intervals, complex values, inequalities, approximate roots, or units. It does not parse natural language and does not attempt symbolic simplification. Extending the interface to those domains requires new representations and new correctness criteria, not merely a longer regular expression. For example, an approximate root needs a documented residual and scale-aware tolerance; an interval answer needs a way to describe endpoints and inclusivity.

There is also an implementation boundary between the intended equation and the code that encodes it. A typo in either left or right expression can produce consistently wrong results while all tests derived from that same typo pass. Have someone compare the implementation with the original written equation, and include independently chosen examples. Tests are useful evidence about specified behavior, not a magical guarantee that the specification itself matches the student's question or the author's intent.

The practical lesson is modest: retain restrictions, evaluate the original relation, and report what was actually checked. Exact fractions make this demonstration transparent, while named equations keep execution under the program author's control. Together, those choices turn a tempting cancelled factor into a visible domain decision. That is a more reliable foundation for reviewing a proposed answer than approving whichever final expression happens to look simplest.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí