JiaYou

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 An integer 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: Non-math questions
16 if not question.startswith("What is"):
17 raise ValueError("unknown operation")
18
19 # Remove the "What is" prefix and the trailing question mark
20 expression = question[8:-1].strip()
21
22 # Edge Case: Empty expression after "What is"
23 if not expression:
24 raise ValueError("syntax error")
25
26 # Tokenize the expression
27 tokens = []
28 i = 0
29 while i < len(expression):
30 if expression[i].isspace():
31 i += 1
32 continue
33
34 # Parse numbers (including negative numbers)
35 if expression[i].isdigit() or (expression[i] == '-' and i < len(expression) - 1 and expression[i+1].isdigit()):
36 start = i
37 if expression[i] == '-':
38 i += 1
39 while i < len(expression) and (expression[i].isdigit() or expression[i] == '.'):
40 i += 1
41 # Edge Case: Numbers with decimal points
42 if '.' in expression[start:i]:
43 raise ValueError("syntax error")
44 tokens.append(int(expression[start:i]))
45 continue
46
47 # Parse operations
48 if expression[i:].startswith("plus"):
49 tokens.append("+")
50 i += 4
51 elif expression[i:].startswith("minus"):
52 tokens.append("-")
53 i += 5
54 elif expression[i:].startswith("multiplied by"):
55 tokens.append("*")
56 i += 13
57 elif expression[i:].startswith("divided by"):
58 tokens.append("/")
59 i += 10
60 else:
61 # Edge Case: Unknown operations
62 raise ValueError("unknown operation")
63
64 # Edge Case: Expression starting with an operator
65 if not tokens:
66 raise ValueError("syntax error")
67
68 # Edge Case: Expression starting with an operator
69 if isinstance(tokens[0], str):
70 raise ValueError("syntax error")
71
72 # Evaluate the expression from left to right
73 result = tokens[0]
74 i = 1
75
76 # Edge Case: Invalid syntax - odd number of tokens or missing operands/operators
77 if len(tokens) % 2 == 0:
78 raise ValueError("syntax error")
79
80 while i < len(tokens):
81 # Edge Case: Expecting an operator but found a number
82 if not isinstance(tokens[i], str):
83 raise ValueError("syntax error")
84
85 # Edge Case: Expecting a number but found an operator or reached end
86 if i + 1 >= len(tokens) or isinstance(tokens[i + 1], str):
87 raise ValueError("syntax error")
88
89 operator = tokens[i]
90 operand = tokens[i + 1]
91
92 if operator == "+":
93 result += operand
94 elif operator == "-":
95 result -= operand
96 elif operator == "*":
97 result *= operand
98 elif operator == "/":
99 # Edge Case: Division by zero
100 if operand == 0:
101 raise ValueError("syntax error") # Following test expectations
102 result //= operand # Integer division as per examples
103 else:
104 # This shouldn't happen due to earlier validation, but just in case
105 raise ValueError("unknown operation")
106
107 i += 2
108
109 return result
110 # Handled Edge Cases: Non-math questions, empty expressions, numbers with decimal points, unknown operations, expressions starting with operators, invalid syntax (odd number of tokens, missing operands/operators), 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.