Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Calculator-I by kdim
def calculator(log: str) -> str:
is_opr = lambda x: x in '+-*/'
is_dgt = lambda x: x.isnumeric()
Ra, Oa, Rb, Rv, Ob = '', '', '', '0', ''
for s in log:
match Ra, Oa, Rb, Rv, s:
case '', _, '', '', x if is_opr(x):
Oa = x
case a, _, _, v, x if is_dgt(x) and (a == v or Ob == '='):
Rv, Ob, Rb = x, '', ''
case _, _, '', _, x if is_dgt(x):
Rv = Rv.lstrip('0') + x
case _, _, '', _, x if is_opr(x):
Ra, Oa = (Rv := str(eval(Ra + Oa + Rv))), x
case _, _, '', _, '=':
Rb, Rv, Ob = Rv, str(eval(Ra + Oa + Rv)), '='
return Rv
print("Example:")
print(calculator("1+2"))
# These "asserts" are used for self-checking
assert calculator("000000") == "0"
assert calculator("0000123") == "123"
assert calculator("12") == "12"
assert calculator("+12") == "12"
assert calculator("") == "0"
assert calculator("1+2") == "2"
assert calculator("2+") == "2"
assert calculator("1+2=") == "3"
assert calculator("1+2-") == "3"
assert calculator("1+2=2") == "2"
assert calculator("=5=10=15") == "15"
print("The mission is done! Click 'Check Solution' to earn rewards!")
Feb. 3, 2023