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 ending 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 tokens.append(int(expression[start:i]))
56 continue
57
58 # Parse operators
59 if expression[i:].startswith("plus"):
60 tokens.append("+")
61 i += 4
62 elif expression[i:].startswith("minus"):
63 tokens.append("-")
64 i += 5
65 elif expression[i:].startswith("multiplied by"):
66 tokens.append("*")
67 i += 13
68 elif expression[i:].startswith("divided by"):
69 tokens.append("/")
70 i += 10
71 else:
72 # Edge Case: Unknown operations
73 raise ValueError("unknown operation")
74
75 # Edge Case: Expression with no tokens
76 if not tokens:
77 raise ValueError("syntax error")
78
79 # Edge Case: Expression starting with an operator
80 if isinstance(tokens[0], str):
81 raise ValueError("syntax error")
82
83 # Evaluate the expression from left to right
84 result = tokens[0]
85 i = 1
86
87 while i < len(tokens):
88 # Edge Case: Consecutive operators
89 if i + 1 >= len(tokens):
90 raise ValueError("syntax error")
91
92 # Edge Case: Non-operator where operator expected
93 if not isinstance(tokens[i], str):
94 raise ValueError("syntax error")
95
96 # Edge Case: Non-number where number expected
97 if not isinstance(tokens[i + 1], int):
98 raise ValueError("syntax error")
99
100 operator = tokens[i]
101 operand = tokens[i + 1]
102
103 if operator == "+":
104 result += operand
105 elif operator == "-":
106 result -= operand
107 elif operator == "*":
108 result *= operand
109 elif operator == "/":
110 # Edge Case: Division by zero
111 if operand == 0:
112 raise ValueError("syntax error")
113 result //= operand # Integer division as specified
114 else:
115 # Edge Case: Unsupported operation
116 raise ValueError("unknown operation")
117
118 i += 2
119
120 # Edge Case: Expression ending with an operator
121 if len(tokens) % 2 == 0:
122 raise ValueError("syntax error")
123
124 return result
125 # Handled Edge Cases: Empty input, None input, non-math questions, missing question mark,
126 # empty expression, unknown operations, consecutive operators,
127 # operators at wrong positions, operands at wrong positions,
128 # division by zero, expression ending with operator,
129 # expression starting with operator
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.