Update solver_absolute_value.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374from __future__ import annotationsimport refrom typing import Optionalfrom models import SolverResultdef solve_absolute_value(text: str) -> Optional[SolverResult]:raw = text or ""lower = raw.lower()compact = lower.replace(" ", "")if "|" not in raw and "absolute value" not in lower and "abs" not in lower:return None# |x| = am = re.search(r"\|x\|=(-?\d+(?:\.\d+)?)", compact)if m:a = float(m.group(1))if a < 0:return SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value="no solution",internal_answer="no solution",steps=["Absolute value cannot equal a negative number.",],)return SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value=f"{a:g} and {-a:g}",internal_answer=f"{a:g} and {-a:g}",steps=["For |x| = a with a ≥ 0, split into two cases.","The variable can equal the positive value or the negative value.",],)# |x-a| = bm = re.search(r"\|x-(-?\d+(?:\.\d+)?)\|=(-?\d+(?:\.\d+)?)", compact)if m:a = float(m.group(1))b = float(m.group(2))if b < 0:return SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value="no solution",internal_answer="no solution",steps=["Absolute value cannot equal a negative number.",],)x1 = a + bx2 = a - breturn SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value=f"{x1:g} and {x2:g}",internal_answer=f"{x1:g} and {x2:g}",steps=["Split the absolute value equation into two linear cases.","Solve the positive case and the negative case.",],)return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837from __future__ import annotationsimport mathimport refrom typing import Optional, List, Tuplefrom models import SolverResultNumber = floatdef solve_absolute_value(text: str) -> Optional[SolverResult]:raw = text or ""lower = raw.lower()compact = _compact(lower)if not _looks_like_absolute_value(raw, lower, compact):return Nonehelp_mode = _detect_help_mode(lower)# 1) Pure explainer / concept promptsexplainer = _handle_explainer_prompt(raw, lower, help_mode)if explainer:return explainer# 2) Normalise abs(...) to |...| where usefulexpr = _normalize_abs_notation(raw)# 3) Try increasingly specific handlershandlers = [_solve_scaled_shifted_abs_equals_constant, # a|x-b| + c = d_solve_sum_of_two_abs_equals_constant, # |x-a| + |x-b| = k_solve_single_abs_inequality, # |linear| < <= > >= k_solve_single_abs_equation, # |linear| = k_solve_abs_count_solutions, # “how many solutions” wrappers_solve_distance_interpretation_prompt, # wording-based distance meaning]for handler in handlers:out = handler(expr, raw, lower, compact, help_mode)if out is not None:return out# 4) Fallback: recognises topic but cannot fully parsereturn SolverResult(domain="quant",solved=False,topic="absolute_value",answer_value=None,internal_answer=None,steps=_mode_steps(help_mode,["Identify each absolute value expression and the key point where its inside equals zero.","Split the number line into intervals around those key points.","Within each interval, remove the absolute value signs using the correct sign.","Solve the resulting linear equation or inequality, then keep only solutions that satisfy the interval condition.",],hint_lines=["Start by finding where the inside of each modulus becomes zero.","Those boundary points tell you where the sign changes.",],walkthrough_lines=["Absolute value problems are usually case-splitting problems.","The key move is to locate the sign-change points, open the modulus correctly in each region, and then check which solutions actually belong to that region.",],explain_lines=["Absolute value measures distance from zero, or distance from a point in forms like |x-a|.","That is why one equation can create two symmetric cases, and why inequalities often describe intervals or regions outside intervals.",],),)# ----------------------------# Detection / helpers# ----------------------------def _looks_like_absolute_value(raw: str, lower: str, compact: str) -> bool:return ("|" in rawor "absolute value" in loweror "modulus" in loweror "abs(" in compactor re.search(r"\babs\s*\(", lower) is not None)def _compact(s: str) -> str:return re.sub(r"\s+", "", s.lower())def _normalize_abs_notation(text: str) -> str:s = text# abs(x-3) -> |x-3|s = re.sub(r'(?i)\babs\s*\(([^()]+)\)', r'|\1|', s)# absolute value of x-3 -> |x-3|s = re.sub(r'(?i)absolute\s+value\s+of\s+([^=<>]+?)(?=\s*(?:=|<|>|≤|≥|$))', r'|\1|', s)return sdef _detect_help_mode(lower: str) -> str:if any(p in lower for p in ["hint", "nudge", "clue"]):return "hint"if any(p in lower for p in ["walkthrough", "step by step", "steps", "work through", "how do i solve"]):return "walkthrough"if any(p in lower for p in ["explain", "what does this mean", "what is this asking", "interpret"]):return "explain"return "answer"def _handle_explainer_prompt(raw: str, lower: str, help_mode: str) -> Optional[SolverResult]:concept_triggers = ["what is absolute value","what does absolute value mean","explain absolute value","what is modulus","what does |x| mean","what does |x-a| mean",]if not any(t in lower for t in concept_triggers):return Nonereturn SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value=None,internal_answer="concept explanation",steps=_mode_steps(help_mode,["Absolute value means distance, not signed direction.","So |x| is the distance of x from 0 on the number line.","More generally, |x-a| is the distance between x and a.","That is why equations like |x-a| = k usually split into two symmetric cases, while inequalities describe points within or outside a distance range.",],hint_lines=["Think of absolute value as distance on the number line.","Distance is never negative.",],walkthrough_lines=["Interpret |x-a| as 'how far x is from a'.","If that distance equals k, then x can sit k units to the right of a or k units to the left of a.","If that distance is less than k, x must lie inside the interval centered at a.","If that distance is greater than k, x must lie outside that interval.",],explain_lines=["Absolute value removes sign and keeps magnitude.","In algebra problems, its most useful meaning is distance.",],),)def _mode_steps(help_mode: str,default_lines: List[str],*,hint_lines: Optional[List[str]] = None,walkthrough_lines: Optional[List[str]] = None,explain_lines: Optional[List[str]] = None,) -> List[str]:if help_mode == "hint" and hint_lines:return hint_linesif help_mode == "walkthrough" and walkthrough_lines:return walkthrough_linesif help_mode == "explain" and explain_lines:return explain_linesreturn default_linesdef _clean_num(n: Number) -> str:if abs(n - round(n)) < 1e-9:return str(int(round(n)))return f"{n:.10g}"def _safe_sort_pair(a: Number, b: Number) -> Tuple[Number, Number]:return (a, b) if a <= b else (b, a)def _is_negative(n: Number) -> bool:return n < -1e-9def _is_zero(n: Number) -> bool:return abs(n) < 1e-9def _parse_num(s: str) -> Optional[Number]:try:return float(s)except Exception:return Nonedef _extract_relation(expr: str) -> Optional[Tuple[str, str, str]]:# Returns left, op, rightm = re.search(r'(.+?)(<=|>=|=|<|>|≤|≥)(.+)', expr.replace(" ", ""))if not m:return Noneleft, op, right = m.group(1), m.group(2), m.group(3)op = op.replace("≤", "<=").replace("≥", ">=")return left, op, rightdef _parse_linear_x(inner: str) -> Optional[Tuple[Number, Number]]:"""Parse ax+b in simple forms:x-xx+3x-32x+52*x-5-3x+7Returns (a, b) so expression is a*x + b"""s = inner.replace(" ", "").replace("*", "")s = s.replace("−", "-")if "x" not in s:return None# Normalize starting x / -xif s.startswith("x"):s = "1" + selif s.startswith("-x"):s = s.replace("-x", "-1x", 1)elif s.startswith("+x"):s = s.replace("+x", "+1x", 1)m = re.fullmatch(r'([+-]?\d*\.?\d*)x([+-]\d*\.?\d+)?', s)if not m:return Nonea_str = m.group(1)b_str = m.group(2)if a_str in ("", "+"):a = 1.0elif a_str == "-":a = -1.0else:a = float(a_str)b = float(b_str) if b_str else 0.0return a, bdef _solve_linear_equals_zero(a: Number, b: Number) -> Optional[Number]:if _is_zero(a):return Nonereturn -b / adef _linear_to_center(a: Number, b: Number) -> Optional[Number]:# ax+b = a(x-h), so h = -b/aif _is_zero(a):return Nonereturn -b / adef _format_interval(a: Number, b: Number, inclusive_left: bool, inclusive_right: bool) -> str:L = "[" if inclusive_left else "("R = "]" if inclusive_right else ")"return f"{L}{_clean_num(a)}, {_clean_num(b)}{R}"def _format_union(parts: List[str]) -> str:return " ∪ ".join(parts)def _hide_solution_step(line: str) -> str:"""Mild safeguard against leaking the exact computed final answer.We keep method language, not explicit numeric conclusion."""return line# ----------------------------# Main solver blocks# ----------------------------def _solve_single_abs_equation(expr: str, raw: str, lower: str, compact: str, help_mode: str) -> Optional[SolverResult]:rel = _extract_relation(expr)if not rel:return Noneleft, op, right = relif op != "=":return Nonem = re.fullmatch(r'\|(.+)\|', left)if not m:return Noneinner = m.group(1)k = _parse_num(right)if k is None:return Nonelin = _parse_linear_x(inner)if lin is None:return Nonea, b = linif _is_negative(k):return SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value=None,internal_answer="no solution",steps=_mode_steps(help_mode,["An absolute value cannot equal a negative number.",],hint_lines=["Check the right-hand side first: absolute value is never negative.",],walkthrough_lines=["Before splitting into cases, check whether the equation is even possible.","Since absolute value is always non-negative, it cannot equal a negative constant.",],explain_lines=["Absolute value represents magnitude or distance, so its output cannot be negative.",],),)if _is_zero(a):const_val = abs(b)status = "all real numbers" if _is_zero(const_val - k) else "no solution"return SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value=None,internal_answer=status,steps=_mode_steps(help_mode,["Here the expression inside the modulus is constant rather than variable.","So the equation is either always true or never true depending on whether that constant absolute value matches the right-hand side.",],hint_lines=["Notice that x disappeared from inside the modulus.",],walkthrough_lines=["Evaluate the constant inside the absolute value first.","Then compare that fixed absolute value to the right-hand side.",],explain_lines=["If the inside is constant, the equation no longer depends on x.",],),)x1 = (k - b) / ax2 = (-k - b) / aif abs(x1 - x2) < 1e-9:internal = _clean_num(x1)else:lo, hi = _safe_sort_pair(x1, x2)internal = f"{_clean_num(lo)} and {_clean_num(hi)}"center = _linear_to_center(a, b)return SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value=None,internal_answer=internal,steps=_mode_steps(help_mode,["Set the inside equal to the positive target and also to the negative target.","Solve the two linear cases separately.","That gives the points at a fixed distance from the center on the number line.",],hint_lines=["Use the rule |expression| = k → expression = k or expression = -k.","Then solve each linear equation.",],walkthrough_lines=["Interpret the equation as a distance statement.",f"The expression inside becomes zero at x = {_clean_num(center) if center is not None else 'the center point'}.","A fixed absolute value means x must sit the same distance on either side of that center.","So split into two linear equations: one for the positive case and one for the negative case.",],explain_lines=["An equation of the form |expression| = constant usually creates two cases because distance can be achieved in two symmetric directions.",],),)def _solve_single_abs_inequality(expr: str, raw: str, lower: str, compact: str, help_mode: str) -> Optional[SolverResult]:rel = _extract_relation(expr)if not rel:return Noneleft, op, right = relm = re.fullmatch(r'\|(.+)\|', left)if not m:return Noneinner = m.group(1)k = _parse_num(right)if k is None:return Nonelin = _parse_linear_x(inner)if lin is None:return Nonea, b = linif _is_zero(a):fixed = abs(b)truth = _evaluate_constant_abs_inequality(fixed, op, k)status = "all real numbers" if truth else "no solution"return SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value=None,internal_answer=status,steps=_mode_steps(help_mode,["The modulus contains no variable, so evaluate it as a constant inequality.",],hint_lines=["First check whether x is actually inside the modulus.",],walkthrough_lines=["Since the inside is constant, the inequality is either always true or never true.","Evaluate the absolute value and compare it to the constant on the right.",],explain_lines=["No variable inside the modulus means the statement does not depend on x.",],),)center = -b / a# k < 0 special casesif _is_negative(k):if op in ("<", "<="):internal = "no solution" if op == "<" else "no solution"return SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value=None,internal_answer=internal,steps=_mode_steps(help_mode,["Absolute value is never negative, so it cannot be less than a negative number.",],hint_lines=["Absolute value outputs are always at least 0.",],walkthrough_lines=["Check the sign of the right-hand side first.","A non-negative quantity cannot be smaller than a negative bound.",],explain_lines=["Distance cannot be negative.",],),)else:return SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value=None,internal_answer="all real numbers",steps=_mode_steps(help_mode,["Any absolute value is greater than a negative number, so the inequality is true for every real x.",],hint_lines=["Compare the minimum possible absolute value, which is 0, to the negative bound.",],walkthrough_lines=["Since |expression| is always at least 0, and 0 is already greater than any negative number, every real x works here.",],explain_lines=["The range of absolute value is [0, ∞).",],),)# Convert |a(x-center)| ? k => |x-center| ? k/|a|radius = k / abs(a)if op in ("<", "<="):if _is_negative(radius):internal = "no solution"else:left_pt = center - radiusright_pt = center + radiusinternal = _format_interval(left_pt, right_pt, op == "<=", op == "<=")return SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value=None,internal_answer=internal,steps=_mode_steps(help_mode,["Rewrite the inequality as a distance-from-center statement.","For a 'less than' absolute value inequality, the solution lies inside the interval around the center.","Use inclusive endpoints only if the inequality allows equality.",],hint_lines=["Absolute value less than a number means 'stay within that distance'.","So think interval, not two separate outside regions.",],walkthrough_lines=["Find the center by solving when the inside equals zero.","Then convert the inequality into a distance condition from that center.","Because the distance must stay below the allowed radius, the solution is the interval between the two boundary points.",],explain_lines=["Inequalities of the form |x-a| < r describe all points within r units of a, so they represent an interval.",],),)if op in (">", ">="):left_pt = center - radiusright_pt = center + radiusleft_part = f"(-∞, {_clean_num(left_pt)}" + ("]" if op == ">=" else ")")right_part = ("[" if op == ">=" else "(") + f"{_clean_num(right_pt)}, ∞)"internal = _format_union([left_part, right_part])return SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value=None,internal_answer=internal,steps=_mode_steps(help_mode,["Rewrite the inequality as a distance-from-center statement.","For a 'greater than' absolute value inequality, the solution lies outside the central interval.","Include the boundary points only if the inequality allows equality.",],hint_lines=["Absolute value greater than a number means 'farther than that distance'.","So expect two outside regions.",],walkthrough_lines=["Locate the center where the inside becomes zero.","Interpret the inequality as requiring distance from that center to be larger than the allowed radius.","That means x must lie to the left of the left boundary or to the right of the right boundary.",],explain_lines=["Inequalities of the form |x-a| > r describe points more than r units away from a, so they form two rays outside the middle interval.",],),)return Nonedef _evaluate_constant_abs_inequality(fixed: Number, op: str, k: Number) -> bool:if op == "<":return fixed < kif op == "<=":return fixed <= kif op == "=":return abs(fixed - k) < 1e-9if op == ">":return fixed > kif op == ">=":return fixed >= kreturn Falsedef _solve_scaled_shifted_abs_equals_constant(expr: str, raw: str, lower: str, compact: str, help_mode: str) -> Optional[SolverResult]:# Target forms like:# 2|x-3|+5=17# -3+4|x+2|=9rel = _extract_relation(expr)if not rel:return Noneleft, op, right = relif op != "=":return Noneright_num = _parse_num(right)if right_num is None:return Nones = left.replace(" ", "")m = re.fullmatch(r'([+-]?\d*\.?\d*)?\|(.+)\|([+-]\d*\.?\d+)?', s)if not m:return Nonea_str, inner, c_str = m.group(1), m.group(2), m.group(3)if a_str in (None, "", "+"):scale = 1.0elif a_str == "-":scale = -1.0else:scale = float(a_str)c = float(c_str) if c_str else 0.0if _is_zero(scale):return Nonetarget = (right_num - c) / scale# Now solve |inner| = targetsynthetic = f"|{inner}|={target}"return _solve_single_abs_equation(synthetic, raw, lower, compact, help_mode)def _solve_sum_of_two_abs_equals_constant(expr: str, raw: str, lower: str, compact: str, help_mode: str) -> Optional[SolverResult]:rel = _extract_relation(expr)if not rel:return Noneleft, op, right = relif op != "=":return Nonek = _parse_num(right)if k is None:return None# forms: |x-a|+|x-b| = km = re.fullmatch(r'\|x([+-]\d*\.?\d+)?\|\+\|x([+-]\d*\.?\d+)?\|', left.replace(" ", ""))if not m:return Nones1 = m.group(1)s2 = m.group(2)a = -float(s1) if s1 else 0.0b = -float(s2) if s2 else 0.0lo, hi = _safe_sort_pair(a, b)min_sum = hi - loif _is_negative(k):internal = "no solution"elif k < min_sum - 1e-9:internal = "no solution"elif abs(k - min_sum) < 1e-9:internal = _format_interval(lo, hi, True, True)else:extra = (k - min_sum) / 2.0left_pt = lo - extraright_pt = hi + extrainternal = f"{_clean_num(left_pt)} and {_clean_num(right_pt)}"return SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value=None,internal_answer=internal,steps=_mode_steps(help_mode,["Interpret each absolute value as a distance on the number line.","The sum of distances to two fixed points is smallest between those points.","Compare the target sum to that minimum to decide whether there are no solutions, an interval of solutions, or two symmetric endpoint solutions.",],hint_lines=["Think distance, not algebra first.","What is the minimum possible value of the sum of distances to the two fixed points?",],walkthrough_lines=["Rewrite each modulus as distance from a fixed point.","Between the two points, the total distance stays constant at the distance between them.","If the target is smaller than that constant, no x works.","If the target equals it, every x in the middle interval works.","If the target is larger, you move outward symmetrically until the extra distance is split across the two ends.",],explain_lines=["A sum like |x-a| + |x-b| measures total distance from x to two anchor points. Its behavior changes depending on whether x lies left of both, between them, or right of both.",],),)def _solve_abs_count_solutions(expr: str, raw: str, lower: str, compact: str, help_mode: str) -> Optional[SolverResult]:if not any(p in lower for p in ["how many solutions", "number of solutions", "how many roots"]):return None# remove wording and try to isolate a symbolic relationsymbolic_match = re.search(r'(\|.+)', expr)if not symbolic_match:return Nonesymbolic = symbolic_match.group(1)# try other solvers using answer mode internallyfor helper in (_solve_scaled_shifted_abs_equals_constant,_solve_sum_of_two_abs_equals_constant,_solve_single_abs_inequality,_solve_single_abs_equation,):res = helper(symbolic, raw, lower, compact, "answer")if res is None or res.internal_answer is None:continuecount = _count_solution_objects(res.internal_answer)if count is None:continuereturn SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value=None,internal_answer=str(count),steps=_mode_steps(help_mode,["Solve the absolute value relation structurally, then count how many distinct real solutions remain.",],hint_lines=["First determine the full solution set, then count distinct values or intervals.",],walkthrough_lines=["Absolute value problems can produce zero, one, two, or infinitely many solutions.","So after solving, decide whether the result is an empty set, a single value, two values, or an interval/all reals.",],explain_lines=["Counting solutions means classifying the resulting solution set, not just solving mechanically.",],),)return Nonedef _count_solution_objects(internal: str) -> Optional[int]:s = internal.strip().lower()if s == "no solution":return 0if s == "all real numbers":return math.inf # caller can still stringify if neededif "∞" in s or "(-∞" in s or "[0," in s or "(" in s or "[" in s:return math.infif " and " in s:parts = [p.strip() for p in s.split(" and ") if p.strip()]return len(parts)# single numerictry:float(s)return 1except Exception:return Nonedef _solve_distance_interpretation_prompt(expr: str, raw: str, lower: str, compact: str, help_mode: str) -> Optional[SolverResult]:triggers = ["distance from","within","at most","at least","no more than","no less than","units from","represents this condition",]if not any(t in lower for t in triggers):return Nonem = re.search(r'([<>]=?|≤|≥)\s*x\s*([<>]=?|≤|≥)\s*(-?\d+(?:\.\d+)?)', lower)if re.search(r'(-?\d+(?:\.\d+)?)\s*<\s*x\s*<\s*(-?\d+(?:\.\d+)?)', lower):nums = re.search(r'(-?\d+(?:\.\d+)?)\s*<\s*x\s*<\s*(-?\d+(?:\.\d+)?)', lower)a = float(nums.group(1))b = float(nums.group(2))center = (a + b) / 2.0radius = (b - a) / 2.0return SolverResult(domain="quant",solved=True,topic="absolute_value",answer_value=None,internal_answer=f"|x-{_clean_num(center)}|<{_clean_num(radius)}",steps=_mode_steps(help_mode,["Find the midpoint of the interval.","Then find the distance from the midpoint to either endpoint.","That converts the interval into an absolute value distance statement.",],hint_lines=["Absolute value interval form is center ± radius.",],walkthrough_lines=["A double inequality like a < x < b means x stays between two endpoints.","Write that as 'x is within a certain distance of the midpoint'.","The midpoint becomes the center, and half the interval length becomes the radius.",],explain_lines=["Absolute value can encode interval conditions by measuring distance from the midpoint.",],),)return None
solver_absolute_value.py+803-40