Skip to content

Commit c8efcfa

Browse files
committed
Improved wordy
1 parent d6105b5 commit c8efcfa

File tree

1 file changed

+36
-30
lines changed

1 file changed

+36
-30
lines changed

wordy/wordy.py

Lines changed: 36 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -44,30 +44,49 @@ def answer(question: str) -> int:
4444
_validate_errors(question)
4545
result: int = 0
4646
new_question: list[str] = _reformat(question)
47-
48-
if len(new_question) <= 3:
49-
try:
50-
_validate_evaluation_pattern(new_question)
51-
eval_str: str = "".join(new_question)
52-
result = eval(eval_str)
53-
return result
54-
except Exception as exc:
55-
raise ValueError("syntax error") from exc
56-
5747
# Reduce iteratively: evaluate the first three-token slice
5848
# and fold the result left-to-right.
59-
while len(new_question) >= 3:
49+
while new_question:
6050
try:
51+
if len(new_question) == 3:
52+
_validate_evaluation_pattern(new_question)
53+
return _math_operation(new_question)
54+
55+
if len(new_question) == 1:
56+
return int(new_question[0])
57+
6158
_validate_evaluation_pattern(new_question[:3])
62-
eval_str: str = "".join(new_question[:3])
63-
val: int = eval(eval_str)
64-
result = val
59+
result = _math_operation(new_question[:3])
6560
new_question = [str(result)] + new_question[3:]
66-
if len(new_question) < 3:
67-
_validate_evaluation_pattern(new_question)
68-
return eval("".join(new_question))
6961
except Exception as exc:
7062
raise ValueError("syntax error") from exc
63+
64+
65+
def _math_operation(question: list[str]) -> int:
66+
"""
67+
Compute a single binary arithmetic operation.
68+
69+
Expects a three-token slice like ``['3', '+', '4']`` and returns
70+
the integer result. Division performs floor division (``//``) to
71+
match exercise rules.
72+
73+
:param question: Three tokens ``[lhs, operator, rhs]``.
74+
:type question: list[str]
75+
:returns: The computed integer result.
76+
:rtype: int
77+
"""
78+
math_operator: str = question[1]
79+
result: int = 0
80+
81+
if math_operator == "+":
82+
result = int(question[0]) + int(question[-1])
83+
elif math_operator == "-":
84+
result = int(question[0]) - int(question[-1])
85+
elif math_operator == "/":
86+
result = int(question[0]) // int(question[-1])
87+
elif math_operator == "*":
88+
result = int(question[0]) * int(question[-1])
89+
7190
return result
7291

7392

@@ -138,16 +157,3 @@ def _validate_errors(question: str) -> None:
138157
for item in WRONG_OPERATORS:
139158
if item in question:
140159
raise ValueError("syntax error")
141-
142-
digits: list[bool] = []
143-
for char in question:
144-
if char.isdigit():
145-
digits.append(True)
146-
147-
operators: list[bool] = []
148-
for key, val in STR_TO_OPERATOR.items():
149-
if key in question or val in question:
150-
operators.append(True)
151-
152-
if not any(digits + operators):
153-
raise ValueError("unknown operation")

0 commit comments

Comments
 (0)