future

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: Question is just "What is" with no numbers or operations
24 if question == "What is":
25 raise ValueError("syntax error")
26
27 # Remove "What is " prefix and the trailing question mark
28 expression = question[8:].rstrip('?')
29
30 # Edge Case: Empty expression after removing prefix and question mark
31 if not expression:
32 raise ValueError("syntax error")
33
34 # Split the expression into tokens
35 tokens = expression.split()
36
37 # Edge Case: No tokens after splitting
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 operations
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 supported operation
62 if token in operations:
63 parsed_tokens.append(operations[token])
64 elif token == 'by':
65 # 'by' should only appear after 'divided' or 'multiplied'
66 if not parsed_tokens or parsed_tokens[-1] not in ['*', '/']:
67 raise ValueError("syntax error")
68 # 'by' is just a connector, we skip it
69 pass
70 else:
71 # Check for special case: "multiplied by" and "divided by"
72 if token == 'multiplied' and i + 1 < len(tokens) and tokens[i + 1] == 'by':
73 parsed_tokens.append('*')
74 i += 1 # Skip the 'by'
75 elif token == 'divided' and i + 1 < len(tokens) and tokens[i + 1] == 'by':
76 parsed_tokens.append('/')
77 i += 1 # Skip the 'by'
78 else:
79 # Unsupported operation
80 raise ValueError("unknown operation")
81 i += 1
82
83 # Edge Case: Expression starts with an operation
84 if not parsed_tokens or isinstance(parsed_tokens[0], str):
85 raise ValueError("syntax error")
86
87 # Evaluate the expression from left to right
88 result = parsed_tokens[0]
89
90 # Edge Case: Single number with no operations
91 if len(parsed_tokens) == 1:
92 return result
93
94 # Edge Case: Odd number of tokens (should be number-operation-number... pattern)
95 if len(parsed_tokens) % 2 == 0:
96 raise ValueError("syntax error")
97
98 i = 1
99 while i < len(parsed_tokens):
100 # Edge Case: Expected operation but found number
101 if not isinstance(parsed_tokens[i], str):
102 raise ValueError("syntax error")
103
104 operation = parsed_tokens[i]
105
106 # Edge Case: Expected number but found operation
107 if i + 1 >= len(parsed_tokens) or isinstance(parsed_tokens[i + 1], str):
108 raise ValueError("syntax error")
109
110 number = parsed_tokens[i + 1]
111
112 if operation == '+':
113 result += number
114 elif operation == '-':
115 result -= number
116 elif operation == '*':
117 result *= number
118 elif operation == '/':
119 # Edge Case: Division by zero
120 if number == 0:
121 raise ValueError("syntax error") # Following test expectations
122 result //= number # Integer division as per examples
123 else:
124 # Edge Case: Unknown operation (should not happen with our parsing)
125 raise ValueError("unknown operation")
126
127 i += 2
128
129 return result
130 # Handled Edge Cases: Empty input, non-math questions, missing numbers,
131 # unsupported operations, invalid syntax, division by zero,
132 # consecutive operations, starting with operation,
133 # ending with operation, odd number of tokens
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.