weekends

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 valid 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" and "?" to get the expression
28 expression = question[8:-1].strip()
29
30 # Edge Case: Empty expression after removing "What is" and "?"
31 if not expression:
32 raise ValueError("syntax error")
33
34 # Tokenize the expression
35 tokens = []
36 i = 0
37 while i < len(expression):
38 if expression[i].isspace():
39 i += 1
40 continue
41
42 # Handle negative numbers
43 if expression[i] == '-' and (i == 0 or expression[i-1] in ' '):
44 i += 1
45 if i >= len(expression) or not expression[i].isdigit():
46 # This is a minus operator, not a negative number
47 tokens.append('-')
48 continue
49
50 num_start = i - 1
51 while i < len(expression) and (expression[i].isdigit() or expression[i] == '.'):
52 i += 1
53 tokens.append(int(expression[num_start:i]))
54 continue
55
56 # Handle positive numbers
57 if expression[i].isdigit() or (expression[i] == '-' and i < len(expression) - 1 and expression[i+1].isdigit()):
58 num_start = i
59 if expression[i] == '-':
60 i += 1
61 while i < len(expression) and (expression[i].isdigit() or expression[i] == '.'):
62 i += 1
63 tokens.append(int(expression[num_start:i]))
64 continue
65
66 # Handle operators
67 if expression[i:].startswith("plus"):
68 tokens.append("+")
69 i += 4
70 elif expression[i:].startswith("minus"):
71 tokens.append("-")
72 i += 5
73 elif expression[i:].startswith("multiplied by"):
74 tokens.append("*")
75 i += 13
76 elif expression[i:].startswith("divided by"):
77 tokens.append("/")
78 i += 10
79 else:
80 # Edge Case: Unsupported operations
81 raise ValueError("unknown operation")
82
83 # Edge Case: Expression with no tokens
84 if not tokens:
85 raise ValueError("syntax error")
86
87 # Edge Case: Expression starting with an operator (except negative number)
88 if tokens[0] in ['+', '*', '/']:
89 raise ValueError("syntax error")
90
91 # Edge Case: Expression ending with an operator
92 if tokens[-1] in ['+', '-', '*', '/']:
93 raise ValueError("syntax error")
94
95 # Evaluate the expression from left to right
96 result = tokens[0]
97
98 # Edge Case: Single number
99 if len(tokens) == 1:
100 if not isinstance(result, int):
101 raise ValueError("syntax error")
102 return result
103
104 i = 1
105 while i < len(tokens):
106 # Edge Case: Consecutive operators
107 if tokens[i] in ['+', '-', '*', '/'] and (i + 1 >= len(tokens) or tokens[i + 1] in ['+', '-', '*', '/']):
108 raise ValueError("syntax error")
109
110 # Edge Case: Consecutive numbers
111 if isinstance(tokens[i], int) and (i + 1 < len(tokens) and isinstance(tokens[i + 1], int)):
112 raise ValueError("syntax error")
113
114 operator = tokens[i]
115 # Edge Case: Missing operand
116 if i + 1 >= len(tokens):
117 raise ValueError("syntax error")
118
119 operand = tokens[i + 1]
120 # Edge Case: Invalid operand type
121 if not isinstance(operand, int):
122 raise ValueError("syntax error")
123
124 if operator == "+":
125 result += operand
126 elif operator == "-":
127 result -= operand
128 elif operator == "*":
129 result *= operand
130 elif operator == "/":
131 # Edge Case: Division by zero
132 if operand == 0:
133 raise ValueError("syntax error") # Or we could raise ZeroDivisionError
134 result //= operand # Integer division as per examples
135 else:
136 # Edge Case: Unknown operator (should not happen with our parsing)
137 raise ValueError("unknown operation")
138
139 i += 2
140
141 return result
142 # Handled Edge Cases: Empty input, None input, non-math questions, questions without question mark,
143 # empty expressions, unsupported operations, expression starting with operator,
144 # expression ending with operator, single number, consecutive operators,
145 # consecutive numbers, missing operands, invalid operand types, 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.