Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Just a negligible extension of Calculator-II solution in Clear category for Calculator-III by Mysta
MAX_DIGITS: int = 5
# -----------------------------------------------------------------------------
def valid_length(number: int, lower_equal: bool = False) -> bool:
return len(str(abs(number))) < MAX_DIGITS + int(lower_equal)
# -----------------------------------------------------------------------------
def calculator(log: str) -> str:
display: str = "0"
overflow: bool = False
op1: int = 0
op2: int | None = None
operator: str = ""
pending_op: bool = False
for key in log:
if key.isdigit():
if pending_op:
# The previous key was a "=" and the previous operator and operand
# have been kept to be able to handle the special case "==".
# Entering a digit will start a new operation (starting from 0).
op1 = 0
operator = ""
op2 = None
pending_op = False
# Update the current number
if operator:
# If there had been an operator entered previously then the
# digit applies to the second operand (op2)
if op2 is None:
op2 = int(key)
elif valid_length(op2):
op2 = op2 * 10 + int(key) if op2 else int(key)
display = str(op2)
elif valid_length(op1):
# The digit applies to the first operand (op1)
op1 = op1 * 10 + int(key)
display = str(op1)
elif key in "+-=": # operator key
if operator:
# If there is alredy an operator then possibly a calculation has
# to be performed:
if key == "=":
if op2 is None:
# Special case "+=" or "-=":
# Add/subtract the first operand to/from itself
op2 = op1
elif pending_op:
# The previous key was a "=" and the previous operator and
# operand have been kept to be able to handle the special
# case "==".
# Entering an operator other than "=" will discard them to
# start collecting a new operator and second operand (op2)
operator = ""
op2 = None
pending_op = False
if op2 is not None:
# All required parts are available: Perform the calculation
# and put the result into the first operator (op1) to start
# the next calculations with it
match operator:
case "+":
op1 += op2
case "-":
op1 -= op2
case _:
raise ValueError(f"Operator '{operator}' not supported!")
if not overflow and valid_length(op1, True):
display = str(op1)
else:
overflow = True
display = "error"
if key == "=":
# Set flag that the special case "==" will be detected.
# (If the next entered key is a digit or operator +/- then a
# new operation will start).
pending_op = True
else:
# The calculation was forced by an operator key +/-
# -> Use this operator for next calculation and reset the second
# operand (op2)
operator = key
op2 = None
else:
raise ValueError(f"Key '{key}' not supported!")
return display
March 23, 2026
Comments: