Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First (using re) solution in Clear category for Calculator-I by lisovsky
import re
def calculator(log: str) -> str:
p = re.compile("\d+|[+-=]")
tokens = re.findall(p, log)
curr_n, n = 0, 0
op = "+"
for token in tokens:
if token.isdigit():
curr_n = int(token)
elif token in ("+", "-", "="):
if op == "+":
curr_n = n + curr_n
op = token
elif op == "-":
curr_n = n - curr_n
op = token
n = curr_n
return str(curr_n)
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. 5, 2023
Comments: