| 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: Question doesn't start with "What is" |
| 20 | if not question.startswith("What is"): |
| 21 | raise ValueError("unknown operation") |
| 22 | |
| 23 | # Edge Case: Question is just "What is" with no numbers or operations |
| 24 | if question == "What is": |
| 25 | raise ValueError("syntax error") |
| 26 | |
| 27 | # Remove the "What is " prefix and the trailing question mark |
| 28 | expression = question[8:].rstrip('?') |
| 29 | |
| 30 | # Edge Case: Empty expression after removing prefix and question mark |
| 31 | if not expression: |
| 32 | raise ValueError("syntax error") |
| 33 | |
| 34 | # Split the expression into tokens |
| 35 | tokens = expression.split() |
| 36 | |
| 37 | # Edge Case: No tokens after splitting |
| 38 | if not tokens: |
| 39 | raise ValueError("syntax error") |
| 40 | |
| 41 | # Define operation mappings |
| 42 | operations = { |
| 43 | 'plus': '+', |
| 44 | 'minus': '-', |
| 45 | 'multiplied': '*', |
| 46 | 'divided': '/' |
| 47 | } |
| 48 | |
| 49 | # Parse tokens into a list of numbers and operators |
| 50 | parsed_tokens = [] |
| 51 | i = 0 |
| 52 | |
| 53 | while i < len(tokens): |
| 54 | token = tokens[i] |
| 55 | |
| 56 | # Try to parse as number |
| 57 | try: |
| 58 | num = int(token) |
| 59 | parsed_tokens.append(num) |
| 60 | except ValueError: |
| 61 | # Not a number, check if it's a supported operation |
| 62 | if token in operations: |
| 63 | parsed_tokens.append(operations[token]) |
| 64 | elif token == 'by': |
| 65 | # 'by' should follow 'divided' or 'multiplied' |
| 66 | if not parsed_tokens or parsed_tokens[-1] not in ['*', '/']: |
| 67 | raise ValueError("syntax error") |
| 68 | # 'by' is just a connector, skip it |
| 69 | pass |
| 70 | else: |
| 71 | # Edge Case: Unknown operation |
| 72 | raise ValueError("unknown operation") |
| 73 | i += 1 |
| 74 | |
| 75 | # Edge Case: Expression starts with an operator (except negative numbers) |
| 76 | if not parsed_tokens: |
| 77 | raise ValueError("syntax error") |
| 78 | |
| 79 | # Handle negative numbers |
| 80 | # If first token is '-', treat it as negative number if followed by a number |
| 81 | processed_tokens = [] |
| 82 | j = 0 |
| 83 | while j < len(parsed_tokens): |
| 84 | if parsed_tokens[j] == '-' and (j == 0 or isinstance(parsed_tokens[j-1], str)): |
| 85 | # This is a negative sign |
| 86 | if j + 1 < len(parsed_tokens) and isinstance(parsed_tokens[j+1], int): |
| 87 | processed_tokens.append(-parsed_tokens[j+1]) |
| 88 | j += 2 # Skip the '-' and the following number |
| 89 | else: |
| 90 | # Edge Case: '-' not followed by a number |
| 91 | raise ValueError("syntax error") |
| 92 | else: |
| 93 | processed_tokens.append(parsed_tokens[j]) |
| 94 | j += 1 |
| 95 | |
| 96 | # Edge Case: Single number |
| 97 | if len(processed_tokens) == 1 and isinstance(processed_tokens[0], int): |
| 98 | return processed_tokens[0] |
| 99 | |
| 100 | # Edge Case: Invalid sequence (e.g., two numbers in a row, two operators in a row) |
| 101 | if len(processed_tokens) < 3: |
| 102 | raise ValueError("syntax error") |
| 103 | |
| 104 | # Check for valid alternating pattern (number, operator, number, operator, ...) |
| 105 | for k in range(len(processed_tokens)): |
| 106 | if k % 2 == 0: # Even indices should be numbers |
| 107 | if not isinstance(processed_tokens[k], int): |
| 108 | raise ValueError("syntax error") |
| 109 | else: # Odd indices should be operators |
| 110 | if not isinstance(processed_tokens[k], str): |
| 111 | raise ValueError("syntax error") |
| 112 | |
| 113 | # Evaluate left to right |
| 114 | result = processed_tokens[0] |
| 115 | i = 1 |
| 116 | |
| 117 | while i < len(processed_tokens): |
| 118 | operator = processed_tokens[i] |
| 119 | if i + 1 >= len(processed_tokens): |
| 120 | # Edge Case: Operator at the end with no following number |
| 121 | raise ValueError("syntax error") |
| 122 | |
| 123 | next_number = processed_tokens[i + 1] |
| 124 | |
| 125 | if operator == '+': |
| 126 | result += next_number |
| 127 | elif operator == '-': |
| 128 | result -= next_number |
| 129 | elif operator == '*': |
| 130 | result *= next_number |
| 131 | elif operator == '/': |
| 132 | # Edge Case: Division by zero |
| 133 | if next_number == 0: |
| 134 | raise ValueError("syntax error") |
| 135 | result //= next_number # Integer division as specified |
| 136 | else: |
| 137 | # Edge Case: Unsupported operation |
| 138 | raise ValueError("unknown operation") |
| 139 | |
| 140 | i += 2 |
| 141 | |
| 142 | return result |
| 143 | # Handled Edge Cases: Empty input, non-math questions, missing numbers, unknown operations, |
| 144 | # invalid syntax (consecutive operators/numbers), division by zero, |
| 145 | # negative numbers, single number expressions |