let it go

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: Question doesn't start with "What is"
20 if not question.startswith("What is"):
21 raise ValueError("unknown operation")
22
23 # Edge Case: Malformed question (doesn't end with '?' or is too short)
24 if not question.endswith('?'):
25 raise ValueError("syntax error")
26
27 # Extract the expression part
28 expression = question[8:-1].strip() # Remove "What is " and "?"
29
30 # Edge Case: Empty expression after removing prefix and suffix
31 if not expression:
32 raise ValueError("syntax error")
33
34 # Tokenize the expression
35 tokens = expression.split()
36
37 # Edge Case: No tokens
38 if not tokens:
39 raise ValueError("syntax error")
40
41 # Define operation mappings
42 operations = {
43 'plus': '+',
44 'minus': '-',
45 'multiplied': '*',
46 'divided': '/'
47 }
48
49 # Parse tokens into a list of numbers and operators
50 parsed_tokens = []
51 i = 0
52
53 while i < len(tokens):
54 token = tokens[i]
55
56 # Try to parse as number
57 try:
58 num = int(token)
59 parsed_tokens.append(num)
60 except ValueError:
61 # Not a number, check if it's a known operation
62 if token in operations:
63 # Special handling for "multiplied by" and "divided by"
64 if token == 'multiplied':
65 # Edge Case: Incomplete "multiplied by" operation
66 if i + 1 >= len(tokens) or tokens[i + 1] != 'by':
67 raise ValueError("syntax error")
68 parsed_tokens.append('*')
69 i += 1 # Skip "by"
70 elif token == 'divided':
71 # Edge Case: Incomplete "divided by" operation
72 if i + 1 >= len(tokens) or tokens[i + 1] != 'by':
73 raise ValueError("syntax error")
74 parsed_tokens.append('/')
75 i += 1 # Skip "by"
76 else:
77 parsed_tokens.append(operations[token])
78 else:
79 # Edge Case: Unknown operation
80 raise ValueError("unknown operation")
81
82 i += 1
83
84 # Edge Case: Expression with just a number
85 if len(parsed_tokens) == 1:
86 if isinstance(parsed_tokens[0], int):
87 return parsed_tokens[0]
88 else:
89 # This shouldn't happen with our parsing logic, but just in case
90 raise ValueError("syntax error")
91
92 # Edge Case: Even number of tokens (should be odd: number, operator, number, ...)
93 if len(parsed_tokens) % 2 == 0:
94 raise ValueError("syntax error")
95
96 # Evaluate from left to right
97 result = parsed_tokens[0]
98
99 # Edge Case: First token is not a number
100 if not isinstance(result, int):
101 raise ValueError("syntax error")
102
103 i = 1
104 while i < len(parsed_tokens):
105 # Edge Case: Missing operator or number
106 if i + 1 >= len(parsed_tokens):
107 raise ValueError("syntax error")
108
109 operator = parsed_tokens[i]
110 operand = parsed_tokens[i + 1]
111
112 # Edge Case: Expected operator but got number
113 if not isinstance(operator, str):
114 raise ValueError("syntax error")
115
116 # Edge Case: Expected number but got operator
117 if not isinstance(operand, int):
118 raise ValueError("syntax error")
119
120 # Perform operation
121 if operator == '+':
122 result += operand
123 elif operator == '-':
124 result -= operand
125 elif operator == '*':
126 result *= operand
127 elif operator == '/':
128 # Edge Case: Division by zero
129 if operand == 0:
130 raise ValueError("syntax error") # or we could raise ZeroDivisionError
131 result //= operand # Integer division as per examples
132 else:
133 # Edge Case: Unsupported operator (shouldn't happen with our parsing)
134 raise ValueError("unknown operation")
135
136 i += 2
137
138 return result
139 # Handled Edge Cases: Empty input, None input, questions not starting with "What is",
140 # questions not ending with '?', empty expressions, no tokens,
141 # incomplete "multiplied by"/"divided by" operations,
142 # unknown operations, expressions with just a number,
143 # even number of tokens, first token not being a number,
144 # missing operators or numbers, division by zero,
145 # unsupported operators
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.