corpus

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: Question doesn't start with "What is"
20 if not question.startswith("What is"):
21 raise ValueError("unknown operation")
22
23 # Edge Case: Question is just "What is" with no numbers or operations
24 if question == "What is":
25 raise ValueError("syntax error")
26
27 # Remove the "What is" prefix and the question mark
28 expression = question[8:].rstrip('?').strip()
29
30 # Edge Case: Empty expression after removing prefix and suffix
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: Decimal numbers are not allowed
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 operation
74 if not operation_found:
75 # Check if it's a valid character that could be part of a number or operation
76 if not expression[i].isspace():
77 raise ValueError("unknown operation")
78 i += 1
79
80 # Edge Case: No tokens found
81 if not tokens:
82 raise ValueError("syntax error")
83
84 # Edge Case: Expression starts with an operator
85 if isinstance(tokens[0], str) and tokens[0] in operations.values():
86 raise ValueError("syntax error")
87
88 # Evaluate the expression from left to right
89 # Edge Case: Single number
90 if len(tokens) == 1:
91 if isinstance(tokens[0], int):
92 return tokens[0]
93 else:
94 # This shouldn't happen with the above checks, but just in case
95 raise ValueError("syntax error")
96
97 # Edge Case: Even number of tokens (should be odd: number, operator, number, ...)
98 if len(tokens) % 2 == 0:
99 raise ValueError("syntax error")
100
101 # Evaluate sequentially
102 result = tokens[0]
103
104 # Edge Case: First token is not a number
105 if not isinstance(result, int):
106 raise ValueError("syntax error")
107
108 i = 1
109 while i < len(tokens):
110 # Edge Case: Missing operator
111 if i + 1 >= len(tokens):
112 raise ValueError("syntax error")
113
114 operator = tokens[i]
115 operand = tokens[i + 1]
116
117 # Edge Case: Expected operator but got number
118 if not isinstance(operator, str):
119 raise ValueError("syntax error")
120
121 # Edge Case: Expected number but got operator
122 if not isinstance(operand, int):
123 raise ValueError("syntax error")
124
125 # Edge Case: Unknown operator
126 if operator not in operations.values():
127 raise ValueError("unknown operation")
128
129 # Perform the operation
130 if operator == "+":
131 result += operand
132 elif operator == "-":
133 result -= operand
134 elif operator == "*":
135 result *= operand
136 elif operator == "/":
137 # Edge Case: Division by zero
138 if operand == 0:
139 raise ValueError("syntax error") # Following the test expectations
140 result //= operand # Integer division as per examples
141
142 i += 2
143
144 return result
145 # Handled Edge Cases: Empty input, non-math questions, missing question components,
146 # decimal numbers, unknown operations, syntax errors (missing operators/operands),
147 # division by zero, invalid token sequences, incorrect token types
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.