@ngel

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 # Remove "What is" and the trailing question mark
24 expression = question[8:].rstrip('?')
25
26 # Edge Case: Empty expression after removing "What is" and "?"
27 if not expression:
28 raise ValueError("syntax error")
29
30 # Split the expression into tokens
31 tokens = expression.split()
32
33 # Edge Case: No tokens
34 if not tokens:
35 raise ValueError("syntax error")
36
37 # Define operation mappings
38 operations = {
39 'plus': '+',
40 'minus': '-',
41 'multiplied': '*',
42 'divided': '/'
43 }
44
45 # Parse tokens into a list of numbers and operators
46 parsed_tokens = []
47 i = 0
48
49 while i < len(tokens):
50 token = tokens[i]
51
52 # Try to parse as number
53 try:
54 num = int(token)
55 parsed_tokens.append(num)
56 i += 1
57 continue
58 except ValueError:
59 pass
60
61 # Handle operations
62 if token in operations:
63 # Special handling for "multiplied by" and "divided by"
64 if token == 'multiplied' or token == 'divided':
65 # Edge Case: Incomplete "multiplied/divided" operation (missing "by")
66 if i + 1 >= len(tokens):
67 raise ValueError("syntax error")
68
69 next_token = tokens[i + 1]
70 # Edge Case: "multiplied/divided" not followed by "by"
71 if next_token != 'by':
72 raise ValueError("syntax error")
73
74 parsed_tokens.append(operations[token])
75 i += 2 # Skip both current token and "by"
76 else:
77 parsed_tokens.append(operations[token])
78 i += 1
79 else:
80 # Edge Case: Unknown operation
81 raise ValueError("unknown operation")
82
83 # Edge Case: Expression starts with an operator
84 if not parsed_tokens:
85 raise ValueError("syntax error")
86
87 # Edge Case: Expression starts with an operator
88 if isinstance(parsed_tokens[0], str):
89 raise ValueError("syntax error")
90
91 # Evaluate the expression from left to right
92 result = parsed_tokens[0]
93 i = 1
94
95 # Edge Case: Single number
96 if len(parsed_tokens) == 1:
97 return result
98
99 # Edge Case: Invalid syntax - even number of tokens (should be odd: number, operator, number, ...)
100 if len(parsed_tokens) % 2 == 0:
101 raise ValueError("syntax error")
102
103 while i < len(parsed_tokens):
104 # Edge Case: Expected operator but found number
105 if not isinstance(parsed_tokens[i], str):
106 raise ValueError("syntax error")
107
108 operator = parsed_tokens[i]
109
110 # Edge Case: Expected number but found operator
111 if i + 1 >= len(parsed_tokens) or isinstance(parsed_tokens[i + 1], str):
112 raise ValueError("syntax error")
113
114 operand = parsed_tokens[i + 1]
115
116 if operator == '+':
117 result += operand
118 elif operator == '-':
119 result -= operand
120 elif operator == '*':
121 result *= operand
122 elif operator == '/':
123 # Edge Case: Division by zero
124 if operand == 0:
125 raise ValueError("syntax error") # Following test expectations
126 result //= operand # Integer division as per examples
127 else:
128 # Edge Case: Unsupported operator
129 raise ValueError("unknown operation")
130
131 i += 2
132
133 return result
134 # Handled Edge Cases: Empty input, None input, questions not starting with "What is",
135 # empty expression, no tokens, incomplete "multiplied/divided" operations,
136 # "multiplied/divided" not followed by "by", unknown operations,
137 # expression starting with operator, single number,
138 # invalid syntax (even number of tokens), expected operator but found number,
139 # expected number but found operator, division by zero, unsupported operator
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.