| 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 has invalid syntax |
| 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 | # Remove "What is" and "?" from the question |
| 24 | question = question[8:-1].strip() |
| 25 | |
| 26 | # Edge Case: Empty question after removing prefix/suffix |
| 27 | if not question: |
| 28 | raise ValueError("syntax error") |
| 29 | |
| 30 | # Define operation mappings |
| 31 | operations = { |
| 32 | "plus": "+", |
| 33 | "minus": "-", |
| 34 | "multiplied by": "*", |
| 35 | "divided by": "/" |
| 36 | } |
| 37 | |
| 38 | # Tokenize the question |
| 39 | tokens = [] |
| 40 | i = 0 |
| 41 | while i < len(question): |
| 42 | # Try to parse a number |
| 43 | if question[i].isdigit() or question[i] == '-': |
| 44 | # Edge Case: Negative number handling |
| 45 | start = i |
| 46 | if question[i] == '-': |
| 47 | i += 1 |
| 48 | while i < len(question) and (question[i].isdigit() or question[i] == ' '): |
| 49 | if question[i] != ' ': |
| 50 | i += 1 |
| 51 | else: |
| 52 | # Edge Case: Space in middle of number |
| 53 | if i+1 < len(question) and question[i+1].isdigit(): |
| 54 | i += 1 |
| 55 | else: |
| 56 | break |
| 57 | try: |
| 58 | num = int(question[start:i].replace(' ', '')) |
| 59 | tokens.append(num) |
| 60 | except ValueError: |
| 61 | # Edge Case: Invalid number format |
| 62 | raise ValueError("syntax error") |
| 63 | # Try to match operations |
| 64 | elif question[i].isalpha(): |
| 65 | matched = False |
| 66 | for op_text, op_symbol in operations.items(): |
| 67 | if question[i:].startswith(op_text): |
| 68 | tokens.append(op_symbol) |
| 69 | i += len(op_text) |
| 70 | matched = True |
| 71 | break |
| 72 | # Edge Case: Unknown operation |
| 73 | if not matched: |
| 74 | word_end = i |
| 75 | while word_end < len(question) and question[word_end] != ' ': |
| 76 | word_end += 1 |
| 77 | word = question[i:word_end] |
| 78 | # Check if it's a valid word that could be part of a multi-word operation |
| 79 | valid_continuation = any(op.startswith(word) for op in operations.keys()) |
| 80 | if not valid_continuation: |
| 81 | raise ValueError("unknown operation") |
| 82 | i = word_end |
| 83 | elif question[i] == ' ': |
| 84 | i += 1 |
| 85 | else: |
| 86 | # Edge Case: Invalid character |
| 87 | raise ValueError("syntax error") |
| 88 | |
| 89 | # Edge Case: No tokens parsed |
| 90 | if not tokens: |
| 91 | raise ValueError("syntax error") |
| 92 | |
| 93 | # Edge Case: Single number |
| 94 | if len(tokens) == 1: |
| 95 | if isinstance(tokens[0], int): |
| 96 | return tokens[0] |
| 97 | else: |
| 98 | # Edge Case: Single token that is not a number |
| 99 | raise ValueError("syntax error") |
| 100 | |
| 101 | # Validate token sequence (number, operation, number, operation, ...) |
| 102 | for i in range(len(tokens)): |
| 103 | if i % 2 == 0: # Even positions should be numbers |
| 104 | # Edge Case: Expected number but found operation |
| 105 | if not isinstance(tokens[i], int): |
| 106 | raise ValueError("syntax error") |
| 107 | else: # Odd positions should be operations |
| 108 | # Edge Case: Expected operation but found number |
| 109 | if not isinstance(tokens[i], str): |
| 110 | raise ValueError("syntax error") |
| 111 | |
| 112 | # Edge Case: Even number of tokens (incomplete expression) |
| 113 | if len(tokens) % 2 == 0: |
| 114 | raise ValueError("syntax error") |
| 115 | |
| 116 | # Evaluate from left to right |
| 117 | result = tokens[0] |
| 118 | for i in range(1, len(tokens), 2): |
| 119 | operation = tokens[i] |
| 120 | operand = tokens[i+1] |
| 121 | |
| 122 | # Edge Case: Division by zero |
| 123 | if operation == '/' and operand == 0: |
| 124 | raise ValueError("syntax error") |
| 125 | |
| 126 | if operation == '+': |
| 127 | result += operand |
| 128 | elif operation == '-': |
| 129 | result -= operand |
| 130 | elif operation == '*': |
| 131 | result *= operand |
| 132 | elif operation == '/': |
| 133 | result //= operand # Integer division as specified |
| 134 | else: |
| 135 | # Edge Case: Unsupported operation |
| 136 | raise ValueError("unknown operation") |
| 137 | |
| 138 | return result |
| 139 | # Handled Edge Cases: Empty input, None input, question not starting with "What is", |
| 140 | # empty question after processing, negative numbers, spaces in numbers, |
| 141 | # invalid number format, unknown operations, invalid characters, |
| 142 | # no tokens parsed, single non-number token, expected number but found operation, |
| 143 | # expected operation but found number, even number of tokens (incomplete expression), |
| 144 | # division by zero, unsupported operations during evaluation |