Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Calculator-II by juestr
from functools import reduce
import operator
to_op = {
"+": operator.add,
"-": 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, x, op, y = state
match label, key_type(key):
case "clear", "d":
return ("incr", int(key), op, y)
case "clear", _:
return state
case "incr", "d":
return ("incr", x * 10 + int(key), op, y)
case "incr", "o":
return ("op_result", v := op(y, x), to_op[key], v)
case "incr", "=":
return ("eq_result", op(y, x), op, x)
case "op_result", "d":
return ("incr", int(key), op, x)
case "eq_result", "d":
return ("incr", int(key), *no_op)
case "op_result" | "eq_result", "o":
return ("op_result", x, to_op[key], x)
case "op_result" | "eq_result", "=":
return ("eq_result", v := op(y, x), op, v)
def display(state):
return str(state[1])
no_op = (lambda _, x: x, None)
state = ("clear", 0, *no_op)
return display(reduce(press, log, state))
Jan. 21, 2023
Comments: