Extract and normalise a final answer for a math verifier

Why it matters A verifier is only as good as its answer extraction; RL with verifiable rewards and benchmark scores both depend on it.

Math benchmarks grade only the final answer, so the grader must pull it out of free text reliably, including nested braces like \boxed{\frac{1}{2}}.

Write extract_answer(text).
1. If text contains "\boxed{", take the content of the LAST \boxed{...}, matching braces so nested {} are kept.
2. Otherwise take the last number in the text, matching the regex -?\d[\d,]*(\.\d+)?. If there is none, return None.
3. Normalise: remove commas, "$" and spaces. If the result is a plain number (regex -?\d+(\.\d+)?), strip trailing zeros after a decimal point and a trailing ".".
Return the string.

Signaturedef extract_answer(text)

Example

extract_answer("so x = \\boxed{\\frac{1}{2}}") is "\\frac{1}{2}" and extract_answer("Total: 1,250.50 dollars") is "1250.5".

Understand the idea

Reasoning models write a lot before the answer, and graders compare only the final answer with the reference. By convention many maths prompts ask the model to put it in \boxed{...}. Pulling it out is like finding the circled answer on an exam sheet, except the circle can contain more brackets.

Example: "x = \boxed{\frac{1}{2}}". Start after "\boxed{" with depth 1. "{" after "frac" makes depth 2, "}" makes 1, "{" 2, "}" 1, and the final "}" makes 0: stop. The answer is \frac{1}{2}. A naive "up to the first }" would give \frac{1.

Rule: last box with brace counting; else last number; then strip commas, $ and spaces, and trailing decimal zeros.

RL training with verifiable rewards uses an extractor like this as the reward function, so a bug here directly teaches the model the wrong thing. Stronger graders also check mathematical equivalence (1/2 versus 0.5).

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 5.

  • Sample 1: exampleextract_answer('so x = \\boxed{\\frac{1}{2}}')
  • Sample 2: plain numberextract_answer('Total: 1,250.50 dollars')
  • Test 3: last boxed winsextract_answer('first \\boxed{3} then \\boxed{ 4 }')
  • Test 4: trailing zeroextract_answer('answer is 3.00')
  • Test 5: nothingextract_answer('no idea')