Immune

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 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
28 expression = question[8:-1].strip()
29
30 # Edge Case: Empty expression after removing prefix and 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 if expression[i] == '-':
51 # Only allow '-' at the beginning of a number
52 if i != start:
53 raise ValueError("syntax error")
54 i += 1
55 try:
56 num = int(expression[start:i])
57 tokens.append(num)
58 except ValueError:
59 raise ValueError("syntax error")
60 continue
61
62 # Parse operations
63 if expression[i:].startswith("plus"):
64 tokens.append("+")
65 i += 4
66 elif expression[i:].startswith("minus"):
67 tokens.append("-")
68 i += 5
69 elif expression[i:].startswith("multiplied by"):
70 tokens.append("*")
71 i += 13
72 elif expression[i:].startswith("divided by"):
73 tokens.append("/")
74 i += 10
75 else:
76 # Edge Case: Unsupported operations
77 raise ValueError("unknown operation")
78
79 # Edge Case: Expression with no tokens
80 if not tokens:
81 raise ValueError("syntax error")
82
83 # Edge Case: Expression starting with an operator
84 if isinstance(tokens[0], str):
85 raise ValueError("syntax error")
86
87 # Evaluate the expression from left to right
88 result = tokens[0]
89
90 # Edge Case: Single number with no operations
91 if len(tokens) == 1:
92 return result
93
94 # Edge Case: Invalid syntax - even number of tokens (should be odd: number, operator, number, ...)
95 if len(tokens) % 2 == 0:
96 raise ValueError("syntax error")
97
98 i = 1
99 while i < len(tokens):
100 # Edge Case: Expected operator but found number
101 if not isinstance(tokens[i], str):
102 raise ValueError("syntax error")
103
104 # Edge Case: Expected number but found operator
105 if i + 1 >= len(tokens) or isinstance(tokens[i + 1], str):
106 raise ValueError("syntax error")
107
108 operator = tokens[i]
109 operand = tokens[i + 1]
110
111 if operator == "+":
112 result += operand
113 elif operator == "-":
114 result -= operand
115 elif operator == "*":
116 result *= operand
117 elif operator == "/":
118 # Edge Case: Division by zero
119 if operand == 0:
120 raise ValueError("syntax error")
121 result //= operand # Integer division as per examples
122 else:
123 # Edge Case: Unknown operator (should not happen with current parsing)
124 raise ValueError("unknown operation")
125
126 i += 2
127
128 return result
129 # Handled Edge Cases: Empty input, None input, non-math questions, missing question mark,
130 # empty expression, unsupported operations, invalid syntax,
131 # division by zero, single number with no operations,
132 # expression starting with operator, odd number of tokens,
133 # consecutive operators, consecutive numbers where operators expected
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.