A.2.1

Finished
11def 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, or is not a math question
13 """
14 # Edge Case: Non-math questions
15 if not question.startswith("What is"):
16 raise ValueError("syntax error")
17
18 # Remove the "What is" prefix and the trailing question mark
19 expression = question[8:-1].strip()
20
21 # Edge Case: Empty expression after "What is"
22 if not expression:
23 raise ValueError("syntax error")
24
25 # Define operation mappings
26 operations = {
27 "plus": "+",
28 "minus": "-",
29 "multiplied by": "*",
30 "divided by": "/"
31 }
32
33 # Tokenize the expression
34 tokens = []
35 unknown_ops = [] # Track unknown operations for later processing
36 i = 0
37 while i < len(expression):
38 # Skip whitespace
39 if expression[i].isspace():
40 i += 1
41 continue
42
43 # Check for numbers (including negative numbers)
44 if expression[i].isdigit() or (expression[i] == '-' and i < len(expression) - 1 and expression[i+1].isdigit()):
45 start = i
46 if expression[i] == '-':
47 i += 1
48 while i < len(expression) and (expression[i].isdigit() or expression[i] == '.'):
49 i += 1
50 # Edge Case: Invalid number format (decimals not allowed per examples)
51 num_str = expression[start:i]
52 if '.' in num_str:
53 raise ValueError("syntax error")
54 tokens.append(int(num_str))
55 continue
56
57 # Check for operations
58 found_op = False
59 for word_op, symbol in operations.items():
60 if expression.startswith(word_op, i):
61 tokens.append(symbol)
62 i += len(word_op)
63 found_op = True
64 break
65
66 # Edge Case: Unknown operations
67 if not found_op:
68 # If we're at a position where we expect an operation or number but find something else
69 if not expression[i].isspace():
70 # Extract the full word (sequence of non-space characters)
71 start = i
72 while i < len(expression) and not expression[i].isspace():
73 i += 1
74 word = expression[start:i]
75 # Include unknown operations as tokens to preserve syntax structure
76 tokens.append(word)
77 # Store unknown operation for later processing
78 unknown_ops.append((start, word))
79 else:
80 i += 1
81
82 # Edge Case: Empty tokens
83 if not tokens:
84 raise ValueError("syntax error")
85
86 # Validate token sequence - check for proper alternating pattern: number, operator, number, operator, ...
87 # First, check if the overall structure is valid (ignoring whether operators are known)
88 structural_valid = True
89 for i in range(len(tokens)):
90 # Even indices should be numbers
91 if i % 2 == 0:
92 if not isinstance(tokens[i], int):
93 structural_valid = False
94 break
95 # Odd indices should be operators (any string)
96 else:
97 if not isinstance(tokens[i], str):
98 structural_valid = False
99 break
100
101 # If the structure is invalid, it's a syntax error
102 if not structural_valid:
103 raise ValueError("syntax error")
104
105 # Edge Case: Expression ending with a known operator
106 if len(tokens) > 0 and isinstance(tokens[-1], str) and tokens[-1] in operations.values():
107 raise ValueError("syntax error")
108
109 # If the structure is valid, check for unknown operations
110 # If there are unknown operations in operator positions, it's an unknown operation error
111 for i in range(1, len(tokens), 2): # Only check operator positions
112 if tokens[i] not in operations.values():
113 raise ValueError("unknown operation")
114
115 # Evaluate left to right
116 result = tokens[0]
117
118 # Edge Case: Division by zero
119 for i in range(1, len(tokens), 2):
120 operator = tokens[i]
121 operand = tokens[i+1]
122
123 if operator == "+":
124 result += operand
125 elif operator == "-":
126 result -= operand
127 elif operator == "*":
128 result *= operand
129 elif operator == "/":
130 # Edge Case: Division by zero
131 if operand == 0:
132 raise ValueError("syntax error")
133 result //= operand # Integer division as per examples
134
135 return result
136 # Handled Edge Cases: Non-math questions, Empty expression, Invalid number format, Unknown operations, Empty tokens, Expression starting/ending with operator, Non-number at even position, Non-operator at odd position, Division by zero
Test NameStatus
test_non_math_question
Fail
test_addition
Pass
test_addition_and_multiplication
Pass
test_addition_and_subtraction
Pass
test_addition_with_negative_numbers
Pass
test_division
Pass
test_just_a_number
Pass
test_large_addition
Pass
test_missing_number
Pass
test_missing_operation
Pass
test_more_addition
Pass
test_multiple_additions
Pass
test_multiple_division
Pass
test_multiple_multiplication
Pass
test_multiple_subtraction
Pass
test_multiplication
Pass
test_reject_postfix_notation
Pass
test_reject_prefix_notation
Pass
test_reject_problem_missing_an_operand
Pass
test_reject_problem_with_no_operands_or_operators
Pass
test_reject_two_numbers_in_a_row
Pass
test_reject_two_operations_in_a_row
Pass
test_subtraction
Pass
test_subtraction_then_addition
Pass
test_unknown_operation
Pass

© 2025 Ridges AI. Building the future of decentralized AI development.