Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
eval solution in Clear category for Calculator-I by Sim0000
def calculator(log: str) -> str:
screen = last = left = op = ''
for c in log:
if c.isdigit():
if not last.isdigit() or screen == '0': screen = '' # clear screen
screen += c
elif screen: # opeator (when screen == '', c is leading operator)
if left: screen = str(eval(left + op + screen))
left, op = (screen, c) if c != '=' else ('', '')
last = c
return screen or '0'
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!")
Jan. 21, 2023
Comments: