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,
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" prefix and question mark suffix
28 expression = question[8:-1].strip()
29
30 # Edge Case: Empty expression after removing prefix/suffix
31 if not expression:
32 raise ValueError("syntax error")
33
34 # Tokenize the expression
35 tokens = []
36 i = 0
37
38 while i < len(expression):
39 # Skip whitespace
40 if expression[i].isspace():
41 i += 1
42 continue
43
44 # Parse numbers (including negative numbers)
45 if expression[i].isdigit() or (expression[i] == '-' and i < len(expression) - 1 and expression[i+1].isdigit()):
46 start = i
47 if expression[i] == '-':
48 i += 1
49 while i < len(expression) and (expression[i].isdigit() or expression[i] == '-'):
50 # Handle case where minus is actually a subtraction operator
51 if expression[i] == '-' and i > start:
52 break
53 i += 1
54 tokens.append(int(expression[start:i]))
55 continue
56
57 # Parse operators
58 if expression[i:].startswith("plus"):
59 tokens.append("+")
60 i += 4
61 elif expression[i:].startswith("minus"):
62 tokens.append("-")
63 i += 5
64 elif expression[i:].startswith("multiplied by"):
65 tokens.append("*")
66 i += 13
67 elif expression[i:].startswith("divided by"):
68 tokens.append("/")
69 i += 10
70 else:
71 # Edge Case: Unknown operations
72 raise ValueError("unknown operation")
73
74 # Edge Case: Expression with just a number
75 if len(tokens) == 1 and isinstance(tokens[0], int):
76 return tokens[0]
77
78 # Edge Case: Invalid syntax - empty tokens, even number of tokens, or starts/ends with operator
79 if not tokens or len(tokens) % 2 == 0 or not isinstance(tokens[0], int) or not isinstance(tokens[-1], int):
80 raise ValueError("syntax error")
81
82 # Evaluate the expression from left to right
83 result = tokens[0]
84 i = 1
85
86 while i < len(tokens):
87 # Edge Case: Invalid syntax - consecutive operators
88 if not isinstance(tokens[i], str) or (i + 1 < len(tokens) and not isinstance(tokens[i + 1], int)):
89 raise ValueError("syntax error")
90
91 operator = tokens[i]
92 operand = tokens[i + 1]
93
94 if operator == "+":
95 result += operand
96 elif operator == "-":
97 result -= operand
98 elif operator == "*":
99 result *= operand
100 elif operator == "/":
101 # Edge Case: Division by zero
102 if operand == 0:
103 raise ValueError("syntax error")
104 result //= operand # Integer division as specified
105 else:
106 # Edge Case: Unknown operations (should not happen with earlier validation)
107 raise ValueError("unknown operation")
108
109 i += 2
110
111 return result
112 # Handled Edge Cases: Empty/None input, non-math questions, missing question mark,
113 # empty expression, unknown operations, invalid syntax (consecutive operators,
114 # wrong token sequence), division by zero, negative numbers,
115 # expressions with just a number
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.