Kratos

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 has invalid syntax
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 the "What is" prefix and the trailing question mark
28 expression = question[8:-1].strip()
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 the tokens
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 # Handle negative numbers
59 if token == "-" and i + 1 < len(tokens):
60 # Check if next token is a number
61 try:
62 num = int(tokens[i + 1])
63 parsed_tokens.append(-num)
64 i += 2 # Skip both the minus and the number
65 continue
66 except ValueError:
67 pass # Not a valid negative number
68
69 num = int(token)
70 parsed_tokens.append(num)
71 i += 1
72 continue
73 except ValueError:
74 pass # Not a number
75
76 # Check for operations
77 if token in operations:
78 parsed_tokens.append(operations[token])
79 i += 1
80 continue
81
82 # Handle "by" after "divided" or "multiplied"
83 if token == "by" and len(parsed_tokens) > 0 and parsed_tokens[-1] in ["*", "/"]:
84 i += 1
85 continue
86
87 # Edge Case: Unknown operation
88 raise ValueError("unknown operation")
89
90 # Edge Case: Expression starts with an operation
91 if len(parsed_tokens) > 0 and isinstance(parsed_tokens[0], str):
92 raise ValueError("syntax error")
93
94 # Evaluate the expression from left to right
95 if len(parsed_tokens) == 1:
96 # Edge Case: Single number
97 if isinstance(parsed_tokens[0], int):
98 return parsed_tokens[0]
99 else:
100 raise ValueError("syntax error")
101
102 # Edge Case: Even number of tokens (should be odd: number, operation, number, ...)
103 if len(parsed_tokens) % 2 == 0:
104 raise ValueError("syntax error")
105
106 # Edge Case: Invalid pattern (operation where number expected or vice versa)
107 for i in range(len(parsed_tokens)):
108 if i % 2 == 0: # Should be a number
109 if not isinstance(parsed_tokens[i], int):
110 raise ValueError("syntax error")
111 else: # Should be an operation
112 if not isinstance(parsed_tokens[i], str):
113 raise ValueError("syntax error")
114
115 # Perform calculations from left to right
116 result = parsed_tokens[0]
117
118 for i in range(1, len(parsed_tokens), 2):
119 operation = parsed_tokens[i]
120 operand = parsed_tokens[i + 1]
121
122 if operation == "+":
123 result += operand
124 elif operation == "-":
125 result -= operand
126 elif operation == "*":
127 result *= operand
128 elif operation == "/":
129 # Edge Case: Division by zero
130 if operand == 0:
131 raise ValueError("syntax error")
132 result //= operand # Integer division as per examples
133
134 return result
135 # Handled Edge Cases: Empty input, None input, questions not starting with "What is",
136 # questions with just "What is", empty expressions, no tokens after splitting,
137 # unknown operations, expressions starting with operations, single number,
138 # even number of tokens, invalid patterns, 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.