lexicon

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 An integer result of evaluating the math expression.
10
11 Raises:
12 ValueError: If the question is malformed, contains unknown operations,
13 or is not a math question.
14 """
15 # Edge Case: Non-math questions
16 if not question.startswith("What is"):
17 raise ValueError("unknown operation")
18
19 # Remove the "What is " prefix and the trailing "?"
20 expression = question[8:-1].strip()
21
22 # Edge Case: Empty expression after "What is"
23 if not expression:
24 raise ValueError("syntax error")
25
26 # Tokenize the expression
27 tokens = []
28 i = 0
29 while i < len(expression):
30 if expression[i].isspace():
31 i += 1
32 continue
33 elif expression[i].isdigit() or (expression[i] == '-' and i < len(expression) - 1 and expression[i+1].isdigit()):
34 # Parse negative numbers
35 start = i
36 if expression[i] == '-':
37 i += 1
38 while i < len(expression) and (expression[i].isdigit() or expression[i] == '.'):
39 i += 1
40 # Edge Case: Numbers with decimal points
41 num_str = expression[start:i]
42 if '.' in num_str:
43 try:
44 num = float(num_str)
45 # Check if it's actually an integer
46 if num.is_integer():
47 tokens.append(int(num))
48 else:
49 raise ValueError("syntax error")
50 except ValueError:
51 raise ValueError("syntax error")
52 else:
53 try:
54 tokens.append(int(num_str))
55 except ValueError:
56 raise ValueError("syntax error")
57 elif expression[i].isalpha():
58 # Parse words (operations)
59 start = i
60 while i < len(expression) and expression[i].isalpha():
61 i += 1
62 word = expression[start:i]
63 if word == "plus":
64 tokens.append("+")
65 elif word == "minus":
66 tokens.append("-")
67 elif word == "multiplied":
68 # Check for "by" after "multiplied"
69 if i >= len(expression) or not expression[i:].startswith(" by"):
70 raise ValueError("syntax error")
71 i += 3 # Skip " by"
72 tokens.append("*")
73 elif word == "divided":
74 # Check for "by" after "divided"
75 if i >= len(expression) or not expression[i:].startswith(" by"):
76 raise ValueError("syntax error")
77 i += 3 # Skip " by"
78 tokens.append("/")
79 else:
80 # Edge Case: Unknown operations
81 raise ValueError("unknown operation")
82 else:
83 # Edge Case: Invalid characters
84 raise ValueError("syntax error")
85
86 # Edge Case: Expression ending with an operator
87 if not tokens:
88 raise ValueError("syntax error")
89
90 # Edge Case: Expression starting with an operator
91 if isinstance(tokens[0], str):
92 raise ValueError("syntax error")
93
94 # Evaluate the expression from left to right
95 result = tokens[0]
96 i = 1
97
98 # Edge Case: Single number
99 if len(tokens) == 1:
100 return result
101
102 # Edge Case: Invalid syntax - consecutive operators or numbers
103 while i < len(tokens):
104 # Expect an operator
105 if not isinstance(tokens[i], str):
106 raise ValueError("syntax error")
107
108 op = tokens[i]
109 i += 1
110
111 # Expect a number
112 if i >= len(tokens) or isinstance(tokens[i], str):
113 raise ValueError("syntax error")
114
115 num = tokens[i]
116 i += 1
117
118 if op == "+":
119 result += num
120 elif op == "-":
121 result -= num
122 elif op == "*":
123 result *= num
124 elif op == "/":
125 # Edge Case: Division by zero
126 if num == 0:
127 raise ValueError("syntax error")
128 result //= num # Integer division as per examples
129
130 return result
131 # Handled Edge Cases: Non-math questions, empty expressions, numbers with decimal points,
132 # unknown operations, invalid characters, expressions ending with operators,
133 # expressions starting with operators, single numbers, consecutive operators or numbers,
134 # 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.