uv

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 unsupported 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 # Split the expression into tokens
27 tokens = expression.split()
28
29 # Edge Case: Invalid syntax with operation at the end
30 if tokens[-1] in ["plus", "minus", "multiplied", "divided"]:
31 raise ValueError("syntax error")
32
33 # Convert tokens to numbers and operations
34 parsed_tokens = []
35 i = 0
36 while i < len(tokens):
37 token = tokens[i]
38
39 # Try to parse as number
40 try:
41 num = int(token)
42 parsed_tokens.append(num)
43 except ValueError:
44 # Handle operations
45 if token == "plus":
46 parsed_tokens.append("+")
47 elif token == "minus":
48 parsed_tokens.append("-")
49 elif token == "multiplied" and i + 1 < len(tokens) and tokens[i+1] == "by":
50 parsed_tokens.append("*")
51 i += 1 # Skip "by"
52 elif token == "divided" and i + 1 < len(tokens) and tokens[i+1] == "by":
53 parsed_tokens.append("/")
54 i += 1 # Skip "by"
55 else:
56 # Edge Case: Unsupported operations
57 raise ValueError("unknown operation")
58 i += 1
59
60 # Edge Case: Expression with just one number
61 if len(parsed_tokens) == 1 and isinstance(parsed_tokens[0], int):
62 return parsed_tokens[0]
63
64 # Edge Case: Invalid syntax - consecutive operations or numbers
65 if len(parsed_tokens) < 3 or len(parsed_tokens) % 2 == 0:
66 raise ValueError("syntax error")
67
68 # Check for alternating pattern: number, operation, number, operation, ...
69 for i in range(len(parsed_tokens)):
70 if i % 2 == 0: # Even indices should be numbers
71 if not isinstance(parsed_tokens[i], int):
72 raise ValueError("syntax error")
73 else: # Odd indices should be operations
74 if parsed_tokens[i] not in ["+", "-", "*", "/"]:
75 raise ValueError("syntax error")
76
77 # Evaluate from left to right
78 result = parsed_tokens[0]
79 i = 1
80 while i < len(parsed_tokens):
81 operation = parsed_tokens[i]
82 operand = parsed_tokens[i+1]
83
84 if operation == "+":
85 result += operand
86 elif operation == "-":
87 result -= operand
88 elif operation == "*":
89 result *= operand
90 elif operation == "/":
91 # Edge Case: Division by zero
92 if operand == 0:
93 raise ValueError("syntax error")
94 result //= operand # Integer division as per examples
95 i += 2
96
97 return result
98 # Handled Edge Cases: Non-math questions, empty expressions, unsupported operations,
99 # invalid syntax with operation at the end, expressions with just one number,
100 # consecutive operations or numbers, 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.