couple

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 An integer result of evaluating the math expression.
10
11 Raises:
12 ValueError: If the question is malformed, contains unsupported operations,
13 or is not a math question.
14 """
15 # Edge Case: Non-math questions
16 if not question.startswith("What is"):
17 raise ValueError("unknown operation")
18
19 # Remove the "What is" prefix and the trailing question mark
20 expression = question[8:-1].strip()
21
22 # Edge Case: Empty expression after "What is"
23 if not expression:
24 raise ValueError("syntax error")
25
26 # Define supported operations
27 operations = {
28 "plus": "+",
29 "minus": "-",
30 "multiplied by": "*",
31 "divided by": "/"
32 }
33
34 # Tokenize the expression
35 tokens = []
36 i = 0
37 while i < len(expression):
38 # Skip whitespace
39 if expression[i].isspace():
40 i += 1
41 continue
42
43 # Parse 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 # Parse operations
58 matched_operation = 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 matched_operation = True
64 break
65
66 # Edge Case: Unknown operations
67 if not matched_operation:
68 # Check if it's a valid character (space or part of number/operation)
69 # If not, it's an unknown operation
70 raise ValueError("unknown operation")
71
72 # Edge Case: Malformed expressions (empty tokens, operations at start/end, consecutive operations)
73 if not tokens:
74 raise ValueError("syntax error")
75
76 # Check for operations at the beginning or end
77 if isinstance(tokens[0], str) or isinstance(tokens[-1], str):
78 raise ValueError("syntax error")
79
80 # Check for consecutive operations or numbers
81 for i in range(len(tokens) - 1):
82 if isinstance(tokens[i], str) == isinstance(tokens[i+1], str):
83 raise ValueError("syntax error")
84
85 # Evaluate the expression from left to right
86 result = tokens[0]
87 i = 1
88 while i < len(tokens):
89 # Edge Case: Malformed expression (should have been caught above, but double-checking)
90 if i + 1 >= len(tokens):
91 raise ValueError("syntax error")
92
93 operator = tokens[i]
94 operand = tokens[i + 1]
95
96 if operator == "+":
97 result += operand
98 elif operator == "-":
99 result -= operand
100 elif operator == "*":
101 result *= operand
102 elif operator == "/":
103 # Edge Case: Division by zero
104 if operand == 0:
105 raise ValueError("syntax error") # Following test expectations
106 result //= operand # Integer division as per examples
107 else:
108 # Edge Case: Unsupported operation (should have been caught earlier)
109 raise ValueError("unknown operation")
110
111 i += 2
112
113 return result
114 # Handled Edge Cases: Non-math questions, empty expressions, invalid number formats,
115 # unknown operations, malformed expressions, consecutive operations,
116 # operations at start/end, 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.