| 1 | 1 | def answer(question: str) -> int: |
| 2 | | pass |
| 2 | """ |
| 3 | Parse and evaluate a simple math word problem. |
| 4 | |
| 5 | Args: |
| 6 | question: A string representing a math word problem |
| 7 | |
| 8 | Returns: |
| 9 | int: The result of evaluating the math expression |
| 10 | |
| 11 | Raises: |
| 12 | ValueError: If the question is malformed, contains unsupported operations, |
| 13 | or is not a valid math question |
| 14 | """ |
| 15 | # Edge Case: Empty or None input |
| 16 | if not question: |
| 17 | raise ValueError("syntax error") |
| 18 | |
| 19 | # Edge Case: Non-math questions |
| 20 | if not question.startswith("What is"): |
| 21 | raise ValueError("unknown operation") |
| 22 | |
| 23 | # Edge Case: Malformed question without ending question mark |
| 24 | if not question.endswith("?"): |
| 25 | raise ValueError("syntax error") |
| 26 | |
| 27 | # Remove "What is" prefix and question mark |
| 28 | expression = question[8:-1].strip() |
| 29 | |
| 30 | # Edge Case: Empty expression after removing prefix and suffix |
| 31 | if not expression: |
| 32 | raise ValueError("syntax error") |
| 33 | |
| 34 | # Define operation mappings |
| 35 | operations = { |
| 36 | "plus": "+", |
| 37 | "minus": "-", |
| 38 | "multiplied by": "*", |
| 39 | "divided by": "/" |
| 40 | } |
| 41 | |
| 42 | # Tokenize the expression |
| 43 | tokens = [] |
| 44 | i = 0 |
| 45 | while i < len(expression): |
| 46 | # Skip whitespace |
| 47 | if expression[i].isspace(): |
| 48 | i += 1 |
| 49 | continue |
| 50 | |
| 51 | # Parse numbers (including negative numbers) |
| 52 | if expression[i].isdigit() or (expression[i] == '-' and i < len(expression) - 1 and expression[i+1].isdigit()): |
| 53 | start = i |
| 54 | if expression[i] == '-': |
| 55 | i += 1 |
| 56 | while i < len(expression) and (expression[i].isdigit() or expression[i] == '.'): |
| 57 | i += 1 |
| 58 | # Edge Case: Invalid number format (decimal points) |
| 59 | if '.' in expression[start:i]: |
| 60 | raise ValueError("syntax error") |
| 61 | tokens.append(int(expression[start:i])) |
| 62 | continue |
| 63 | |
| 64 | # Check for multi-word operations |
| 65 | matched = False |
| 66 | for op_text, op_symbol in operations.items(): |
| 67 | if expression.startswith(op_text, i): |
| 68 | tokens.append(op_symbol) |
| 69 | i += len(op_text) |
| 70 | matched = True |
| 71 | break |
| 72 | |
| 73 | if matched: |
| 74 | continue |
| 75 | |
| 76 | # Check for single word operations (for backward compatibility) |
| 77 | if expression.startswith("plus", i): |
| 78 | tokens.append("+") |
| 79 | i += 4 |
| 80 | elif expression.startswith("minus", i): |
| 81 | tokens.append("-") |
| 82 | i += 5 |
| 83 | elif expression.startswith("multiplied", i): |
| 84 | tokens.append("*") |
| 85 | i += 10 |
| 86 | elif expression.startswith("divided", i): |
| 87 | tokens.append("/") |
| 88 | i += 7 |
| 89 | else: |
| 90 | # Edge Case: Unknown operations |
| 91 | raise ValueError("unknown operation") |
| 92 | |
| 93 | # Edge Case: Empty tokens list |
| 94 | if not tokens: |
| 95 | raise ValueError("syntax error") |
| 96 | |
| 97 | # Edge Case: Expression starting with an operator (except negative numbers handled above) |
| 98 | if tokens[0] in ["+", "*", "/"]: |
| 99 | raise ValueError("syntax error") |
| 100 | |
| 101 | # Edge Case: Expression ending with an operator |
| 102 | if tokens[-1] in ["+", "-", "*", "/"]: |
| 103 | raise ValueError("syntax error") |
| 104 | |
| 105 | # Evaluate the expression from left to right |
| 106 | # Edge Case: Single number |
| 107 | if len(tokens) == 1: |
| 108 | if isinstance(tokens[0], int): |
| 109 | return tokens[0] |
| 110 | else: |
| 111 | raise ValueError("syntax error") |
| 112 | |
| 113 | # Edge Case: Invalid syntax (consecutive operators or numbers) |
| 114 | for i in range(len(tokens) - 1): |
| 115 | if isinstance(tokens[i], int) == isinstance(tokens[i+1], int): |
| 116 | raise ValueError("syntax error") |
| 117 | if isinstance(tokens[i], str) and isinstance(tokens[i+1], str): |
| 118 | if not (tokens[i] == "-" and isinstance(tokens[i+1], int)): |
| 119 | raise ValueError("syntax error") |
| 120 | |
| 121 | result = tokens[0] |
| 122 | i = 1 |
| 123 | while i < len(tokens): |
| 124 | # Edge Case: Missing operand |
| 125 | if i + 1 >= len(tokens): |
| 126 | raise ValueError("syntax error") |
| 127 | |
| 128 | operator = tokens[i] |
| 129 | operand = tokens[i + 1] |
| 130 | |
| 131 | # Edge Case: Non-numeric operand |
| 132 | if not isinstance(operand, int): |
| 133 | raise ValueError("syntax error") |
| 134 | |
| 135 | if operator == "+": |
| 136 | result += operand |
| 137 | elif operator == "-": |
| 138 | result -= operand |
| 139 | elif operator == "*": |
| 140 | result *= operand |
| 141 | elif operator == "/": |
| 142 | # Edge Case: Division by zero |
| 143 | if operand == 0: |
| 144 | raise ValueError("syntax error") |
| 145 | result //= operand # Integer division as per examples |
| 146 | else: |
| 147 | # Edge Case: Unknown operator |
| 148 | raise ValueError("syntax error") |
| 149 | |
| 150 | i += 2 |
| 151 | |
| 152 | return result |
| 153 | # Handled Edge Cases: Empty input, None input, non-math questions, missing question mark, |
| 154 | # empty expression, invalid number format, unknown operations, |
| 155 | # expression starting/ending with operator, single number, |
| 156 | # consecutive operators/numbers, missing operands, non-numeric operands, |
| 157 | # division by zero, unknown operators |