armor

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 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 # Tokenize the expression
27 tokens = []
28 i = 0
29 while i < len(expression):
30 # Skip whitespace
31 if expression[i].isspace():
32 i += 1
33 continue
34
35 # Parse numbers (including negative numbers)
36 if expression[i].isdigit() or (expression[i] == '-' and i < len(expression) - 1 and expression[i+1].isdigit()):
37 start = i
38 if expression[i] == '-':
39 i += 1
40 while i < len(expression) and (expression[i].isdigit() or expression[i] == '-'):
41 if expression[i] == '-':
42 # Only allow '-' as part of a negative number at the beginning
43 if i != start + 1 or expression[i-1] != '-':
44 break
45 i += 1
46 try:
47 num = int(expression[start:i])
48 tokens.append(num)
49 except ValueError:
50 raise ValueError("syntax error")
51 continue
52
53 # Parse words (operations)
54 if expression[i].isalpha():
55 start = i
56 while i < len(expression) and expression[i].isalpha():
57 i += 1
58 word = expression[start:i]
59 if word == "plus":
60 tokens.append("+")
61 elif word == "minus":
62 tokens.append("-")
63 elif word == "multiplied":
64 # Check for "by" after "multiplied"
65 if i >= len(expression) or not expression[i:].startswith(" by"):
66 raise ValueError("syntax error")
67 i += 3 # Skip " by"
68 tokens.append("*")
69 elif word == "divided":
70 # Check for "by" after "divided"
71 if i >= len(expression) or not expression[i:].startswith(" by"):
72 raise ValueError("syntax error")
73 i += 3 # Skip " by"
74 tokens.append("/")
75 else:
76 # Edge Case: Unsupported operations
77 raise ValueError("unknown operation")
78 continue
79
80 # Edge Case: Invalid characters
81 raise ValueError("syntax error")
82
83 # Edge Case: Expression starting with an operation
84 if not tokens or not isinstance(tokens[0], int):
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 (incomplete expression)
92 while i < len(tokens):
93 # Edge Case: Missing operand
94 if i + 1 >= len(tokens):
95 raise ValueError("syntax error")
96
97 operation = tokens[i]
98 operand = tokens[i + 1]
99
100 # Edge Case: Non-integer operand
101 if not isinstance(operand, int):
102 raise ValueError("syntax error")
103
104 # Edge Case: Non-operation token in operation position
105 if operation not in ["+", "-", "*", "/"]:
106 raise ValueError("syntax error")
107
108 if operation == "+":
109 result += operand
110 elif operation == "-":
111 result -= operand
112 elif operation == "*":
113 result *= operand
114 elif operation == "/":
115 # Edge Case: Division by zero
116 if operand == 0:
117 raise ValueError("syntax error") # Following test expectations
118 result //= operand # Integer division as per examples
119
120 i += 2
121
122 return result
123 # Handled Edge Cases: Non-math questions, empty expressions, unsupported operations,
124 # invalid characters, negative numbers, expression starting with operation,
125 # incomplete expressions, missing operands, non-integer operands,
126 # non-operation tokens in operation position, 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.