Merry

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 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 questions without a question mark
24 if not question.endswith("?"):
25 raise ValueError("syntax error")
26
27 # Remove "What is" and "?" to get the expression
28 expression = question[8:-1].strip()
29
30 # Edge Case: Empty expression after removing "What is" and "?"
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 (decimals not allowed per examples)
59 num_str = expression[start:i]
60 if '.' in num_str:
61 raise ValueError("syntax error")
62 tokens.append(int(num_str))
63 continue
64
65 # Check for multi-word operations
66 matched = False
67 for op_text, op_symbol in operations.items():
68 if expression.startswith(op_text, i):
69 tokens.append(op_symbol)
70 i += len(op_text)
71 matched = True
72 break
73
74 # Edge Case: Unknown operations
75 if not matched:
76 # Check if it's a single character operator (which would be invalid)
77 if expression[i] in '+-*/':
78 raise ValueError("unknown operation")
79 # Check for other unknown words
80 start = i
81 while i < len(expression) and not expression[i].isspace():
82 i += 1
83 word = expression[start:i]
84 # Edge Case: Invalid operations like "cubed"
85 raise ValueError("unknown operation")
86
87 # Edge Case: Empty tokens
88 if not tokens:
89 raise ValueError("syntax error")
90
91 # Edge Case: Expression starting with an operator
92 if isinstance(tokens[0], str) and tokens[0] in "+-*/":
93 raise ValueError("syntax error")
94
95 # Evaluate the expression from left to right
96 if len(tokens) == 1:
97 # Edge Case: Single number
98 if isinstance(tokens[0], int):
99 return tokens[0]
100 else:
101 raise ValueError("syntax error")
102
103 # Edge Case: Even number of tokens (should be odd: number, operator, number, ...)
104 if len(tokens) % 2 == 0:
105 raise ValueError("syntax error")
106
107 result = tokens[0]
108
109 # Process operations from left to right
110 i = 1
111 while i < len(tokens):
112 # Edge Case: Missing operator
113 if i + 1 >= len(tokens):
114 raise ValueError("syntax error")
115
116 operator = tokens[i]
117 operand = tokens[i + 1]
118
119 # Edge Case: Invalid operator type
120 if not isinstance(operator, str):
121 raise ValueError("syntax error")
122
123 # Edge Case: Invalid operand type
124 if not isinstance(operand, int):
125 raise ValueError("syntax error")
126
127 if operator == "+":
128 result += operand
129 elif operator == "-":
130 result -= operand
131 elif operator == "*":
132 result *= operand
133 elif operator == "/":
134 # Edge Case: Division by zero
135 if operand == 0:
136 raise ValueError("syntax error") # Following examples, this seems to be treated as syntax error
137 result //= operand # Integer division as per examples
138 else:
139 # Edge Case: Unsupported operation
140 raise ValueError("unknown operation")
141
142 i += 2
143
144 return result
145 # Handled Edge Cases: Empty input, None input, non-math questions, missing question mark,
146 # empty expression, invalid number formats, unknown operations,
147 # expression starting with operator, single number, even number of tokens,
148 # missing operators, invalid operator/operand types, division by zero
Test NameStatus
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_non_math_question
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.