sn62

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 # 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
46 while i < len(expression):
47 # Skip whitespace
48 if expression[i].isspace():
49 i += 1
50 continue
51
52 # Parse numbers (including negative numbers)
53 if expression[i].isdigit() or (expression[i] == '-' and i < len(expression) - 1 and expression[i+1].isdigit()):
54 start = i
55 if expression[i] == '-':
56 i += 1
57 while i < len(expression) and (expression[i].isdigit() or expression[i] == '.'):
58 i += 1
59 # Edge Case: Non-integer numbers
60 num_str = expression[start:i]
61 if '.' in num_str:
62 raise ValueError("syntax error")
63 tokens.append(int(num_str))
64 continue
65
66 # Check for operations
67 found_operation = False
68 for word_op, symbol in operations.items():
69 if expression.startswith(word_op, i):
70 tokens.append(symbol)
71 i += len(word_op)
72 found_operation = True
73 break
74
75 # Edge Case: Unknown operations
76 if not found_operation:
77 raise ValueError("unknown operation")
78
79 # Edge Case: Empty tokens list
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 i = 1
90
91 # Edge Case: Odd number of tokens (invalid syntax)
92 if len(tokens) % 2 == 0:
93 raise ValueError("syntax error")
94
95 while i < len(tokens):
96 # Edge Case: Missing operator
97 if not isinstance(tokens[i], str):
98 raise ValueError("syntax error")
99
100 operator = tokens[i]
101
102 # Edge Case: Missing operand
103 if i + 1 >= len(tokens):
104 raise ValueError("syntax error")
105
106 # Edge Case: Invalid operand type
107 if not isinstance(tokens[i + 1], int):
108 raise ValueError("syntax error")
109
110 operand = tokens[i + 1]
111
112 if operator == "+":
113 result += operand
114 elif operator == "-":
115 result -= operand
116 elif operator == "*":
117 result *= operand
118 elif operator == "/":
119 # Edge Case: Division by zero
120 if operand == 0:
121 raise ValueError("syntax error")
122 result //= operand # Integer division as per examples
123 else:
124 # Edge Case: Unsupported operation
125 raise ValueError("unknown operation")
126
127 i += 2
128
129 return result
130 # Handled Edge Cases: Empty input, None input, non-math questions, missing question mark,
131 # empty expression, non-integer numbers, unknown operations,
132 # empty tokens, expression starting with operator, odd number of tokens,
133 # missing operators, missing operands, invalid operand types,
134 # division by zero, unsupported operations
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.