harrison

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: 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 question (doesn't end with ?)
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 # Define operation mappings
35 operations = {
36 "plus": "+",
37 "minus": "-",
38 "multiplied by": "*",
39 "divided by": "/"
40 }
41
42 # Tokenize the expression
43 tokens = []
44 i = 0
45 while i < len(expression):
46 # Skip whitespace
47 if expression[i].isspace():
48 i += 1
49 continue
50
51 # Check for numbers (including negative)
52 if expression[i].isdigit() or (expression[i] == '-' and i < len(expression) - 1 and expression[i+1].isdigit()):
53 start = i
54 if expression[i] == '-':
55 i += 1
56 while i < len(expression) and (expression[i].isdigit() or expression[i] == '.'):
57 i += 1
58 # Edge Case: Invalid number format (decimals not allowed per examples)
59 num_str = expression[start:i]
60 if '.' in num_str:
61 raise ValueError("syntax error")
62 tokens.append(int(num_str))
63 continue
64
65 # Check for operations
66 found_operation = False
67 for word_op, symbol in operations.items():
68 if expression.startswith(word_op, i):
69 tokens.append(symbol)
70 i += len(word_op)
71 found_operation = True
72 break
73
74 # Edge Case: Unknown operation
75 if not found_operation:
76 # Check if it's a valid word that's just not supported
77 if any(c.isalpha() for c in expression[i:]):
78 # Find the next space or end of string
79 end = i
80 while end < len(expression) and not expression[end].isspace():
81 end += 1
82 word = expression[i:end]
83 # If it's a word but not a supported operation
84 if word not in operations:
85 raise ValueError("unknown operation")
86 else:
87 # Some other invalid character
88 raise ValueError("syntax error")
89
90 # Edge Case: Expression with just a number
91 if len(tokens) == 1 and isinstance(tokens[0], int):
92 return tokens[0]
93
94 # Edge Case: Invalid syntax - even number of tokens (must be odd: number, operation, number, ...)
95 if len(tokens) % 2 == 0:
96 raise ValueError("syntax error")
97
98 # Edge Case: Invalid syntax - doesn't start with a number
99 if not tokens or not isinstance(tokens[0], int):
100 raise ValueError("syntax error")
101
102 # Evaluate from left to right
103 result = tokens[0]
104 i = 1
105
106 # Edge Case: Malformed expression with missing elements
107 while i < len(tokens):
108 # Edge Case: Missing operation
109 if i >= len(tokens) - 1:
110 raise ValueError("syntax error")
111
112 operation = tokens[i]
113 # Edge Case: Invalid operation type
114 if not isinstance(operation, str):
115 raise ValueError("syntax error")
116
117 number = tokens[i + 1]
118 # Edge Case: Missing number after operation
119 if not isinstance(number, int):
120 raise ValueError("syntax error")
121
122 if operation == "+":
123 result += number
124 elif operation == "-":
125 result -= number
126 elif operation == "*":
127 result *= number
128 elif operation == "/":
129 # Edge Case: Division by zero
130 if number == 0:
131 raise ZeroDivisionError("division by zero")
132 result //= number # Integer division as per examples
133 else:
134 # Edge Case: Unsupported operation symbol
135 raise ValueError("unknown operation")
136
137 i += 2
138
139 return result
140 # Handled Edge Cases: Empty input, None input, non-math questions, malformed questions (no ending ?),
141 # empty expression, invalid number format (decimals), unknown operations,
142 # expression with just a number, invalid syntax (even tokens count),
143 # doesn't start with number, missing operations, invalid operation types,
144 # missing numbers after operations, division by zero, unsupported operation symbols
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.