| 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 unknown operations, |
| 13 | or is not a valid math word problem |
| 14 | """ |
| 15 | # Edge Case: Non-math questions |
| 16 | if not question.startswith("What is"): |
| 17 | raise ValueError("syntax error") |
| 18 | |
| 19 | # Remove the "What is" prefix and the trailing question mark |
| 20 | expression = question[8:].rstrip('?') |
| 21 | |
| 22 | # Edge Case: Empty expression after "What is" |
| 23 | if not expression: |
| 24 | raise ValueError("syntax error") |
| 25 | |
| 26 | # Tokenize the expression |
| 27 | tokens = expression.split() |
| 28 | |
| 29 | # Edge Case: Expression with no tokens |
| 30 | if not tokens: |
| 31 | raise ValueError("syntax error") |
| 32 | |
| 33 | # Parse the first token as a number |
| 34 | try: |
| 35 | result = int(tokens[0]) |
| 36 | except ValueError: |
| 37 | # Edge Case: First token is not a number |
| 38 | raise ValueError("syntax error") |
| 39 | |
| 40 | # Process the remaining tokens in pairs (operator, number) |
| 41 | i = 1 |
| 42 | while i < len(tokens): |
| 43 | # Edge Case: Incomplete expression (odd number of tokens after first number) |
| 44 | if i + 1 >= len(tokens): |
| 45 | raise ValueError("syntax error") |
| 46 | |
| 47 | operator = tokens[i] |
| 48 | operand_str = tokens[i + 1] |
| 49 | |
| 50 | # Convert operand to integer |
| 51 | try: |
| 52 | operand = int(operand_str) |
| 53 | except ValueError: |
| 54 | # Edge Case: Operand is not a number |
| 55 | raise ValueError("syntax error") |
| 56 | |
| 57 | # Apply the operation |
| 58 | if operator == "plus": |
| 59 | result += operand |
| 60 | elif operator == "minus": |
| 61 | result -= operand |
| 62 | elif operator == "multiplied" and i + 2 < len(tokens) and tokens[i + 1] == "by": |
| 63 | # Handle "multiplied by" as a two-token operator |
| 64 | result *= operand |
| 65 | i += 1 # Skip the "by" token |
| 66 | elif operator == "divided" and i + 2 < len(tokens) and tokens[i + 1] == "by": |
| 67 | # Handle "divided by" as a two-token operator |
| 68 | # Edge Case: Division by zero |
| 69 | if operand == 0: |
| 70 | raise ValueError("syntax error") |
| 71 | result //= operand # Integer division as per examples |
| 72 | i += 1 # Skip the "by" token |
| 73 | else: |
| 74 | # Edge Case: Unknown operation |
| 75 | raise ValueError("unknown operation") |
| 76 | |
| 77 | i += 2 |
| 78 | |
| 79 | return result |
| 80 | # Handled Edge Cases: Non-math questions, empty expression, expression with no tokens, |
| 81 | # first token not a number, incomplete expression, operand not a number, |
| 82 | # division by zero, unknown operation |