Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Calculator-III by juestr
from functools import reduce, wraps
import operator
def map_error(op):
@wraps(op)
def f(x, y):
if x == "error" or y == "error" or abs(r := op(x, y)) > 99999:
return "error"
else:
return r
return f
@map_error
def noop(_, x):
return x
to_op = {
"+": map_error(operator.add),
"-": map_error(operator.sub),
}
def calculator(log: str) -> str:
def key_type(key):
if key.isdigit():
return "d"
elif key == "=":
return "="
else:
return "o"
def press(state, key):
label, acc, x, op = state
match label, key_type(key):
case "clear", "d":
return ("incr", None, int(key), noop)
case "clear", _:
return state
case "incr", "d":
if abs(x) < 10000:
return ("incr", acc, x * 10 + int(key), op)
else:
return state
case "incr", "o":
return ("op_result", op(acc, x), x, to_op[key])
case "incr", "=":
return ("eq_result", op(acc, x), x, op)
case "op_result", "d":
return ("incr", acc, int(key), op)
case "op_result", "o":
return ("op_result", acc, x, to_op[key])
case "op_result", "=":
return ("eq_result", op(acc, acc), acc, op)
case "eq_result", "d":
return ("incr", None, int(key), noop)
case "eq_result", "o":
return ("op_result", acc, acc, to_op[key])
case "eq_result", "=":
return ("eq_result", op(acc, x), x, op)
def display(state):
idx = 1 + (state[0] in ("incr"))
return str(state[idx])
state = ("clear", 0, None, None)
return display(reduce(press, log, state))
Jan. 22, 2023
Comments: