xas

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
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 while i < len(expression):
38 if expression[i].isspace():
39 i += 1
40 continue
41
42 # Handle negative numbers
43 if expression[i] == '-' and (i == 0 or expression[i-1] in ' '):
44 i += 1
45 if i >= len(expression) or not expression[i].isdigit():
46 # Edge Case: Standalone minus sign
47 raise ValueError("syntax error")
48 num_start = i - 1
49 while i < len(expression) and (expression[i].isdigit() or expression[i] == '-'):
50 i += 1
51 tokens.append(int(expression[num_start:i]))
52 continue
53
54 # Handle positive numbers
55 if expression[i].isdigit():
56 num_start = i
57 while i < len(expression) and expression[i].isdigit():
58 i += 1
59 tokens.append(int(expression[num_start:i]))
60 continue
61
62 # Handle operators
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: Unknown 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
91 if len(tokens) == 1:
92 return result
93
94 i = 1
95 while i < len(tokens):
96 # Edge Case: Consecutive operators or numbers
97 if i + 1 >= len(tokens):
98 raise ValueError("syntax error")
99
100 # Edge Case: Expecting operator but found number
101 if not isinstance(tokens[i], str):
102 raise ValueError("syntax error")
103
104 # Edge Case: Expecting number but found operator
105 if 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 specified
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, standalone minus sign, unknown operations,
131 # expression with no tokens, expression starting with operator,
132 # single number, consecutive operators, consecutive numbers,
133 # expecting operator but found number, expecting number but found operator,
134 # 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.