agent

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,
13 or is not a 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 "?" from the question
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 supported operations
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 (e.g., decimal points)
59 if '.' in expression[start:i]:
60 raise ValueError("syntax error")
61 tokens.append(int(expression[start:i]))
62 continue
63
64 # Parse operations
65 operation_found = False
66 for word_op, symbol in operations.items():
67 if expression.startswith(word_op, i):
68 tokens.append(symbol)
69 i += len(word_op)
70 operation_found = True
71 break
72
73 # Edge Case: Unknown operations
74 if not operation_found:
75 # Check if it's just a letter sequence that's not a known operation
76 if expression[i].isalpha():
77 # Find the end of this word
78 start = i
79 while i < len(expression) and expression[i].isalpha():
80 i += 1
81 word = expression[start:i]
82 # If it's not a known operation, it's an unknown operation
83 if word not in operations:
84 raise ValueError("unknown operation")
85 else:
86 # Any other character is a syntax error
87 raise ValueError("syntax error")
88
89 # Edge Case: Expression with just a number
90 if len(tokens) == 1 and isinstance(tokens[0], int):
91 return tokens[0]
92
93 # Edge Case: Invalid syntax - empty tokens, or starts/ends with operation
94 if not tokens or len(tokens) < 3 or len(tokens) % 2 == 0:
95 raise ValueError("syntax error")
96
97 # Edge Case: Invalid syntax - consecutive numbers or operators
98 for i in range(len(tokens)):
99 if i % 2 == 0: # Even indices should be numbers
100 if not isinstance(tokens[i], int):
101 raise ValueError("syntax error")
102 else: # Odd indices should be operators
103 if not isinstance(tokens[i], str):
104 raise ValueError("syntax error")
105
106 # Evaluate the expression from left to right
107 result = tokens[0]
108 i = 1
109 while i < len(tokens):
110 operator = tokens[i]
111 # Edge Case: Missing operand
112 if i + 1 >= len(tokens):
113 raise ValueError("syntax error")
114 operand = tokens[i + 1]
115
116 if operator == "+":
117 result += operand
118 elif operator == "-":
119 result -= operand
120 elif operator == "*":
121 result *= operand
122 elif operator == "/":
123 # Edge Case: Division by zero
124 if operand == 0:
125 raise ValueError("syntax error")
126 result //= operand # Integer division as per examples
127 else:
128 # Edge Case: Unknown operator (should not happen with current logic, but for safety)
129 raise ValueError("unknown operation")
130
131 i += 2
132
133 return result
134 # Handled Edge Cases: Empty input, None input, non-math questions, missing question mark,
135 # empty expression, invalid number formats, unknown operations,
136 # expressions with just a number, invalid syntax (odd number of tokens,
137 # consecutive numbers or operators), missing operands, 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.