Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Calculator-II by wo.tomasz
import re
def separate_end(log):
end = ""
sufix = re.findall("[^0-9]+$", log)
if sufix:
end = sufix[0]
return log.rstrip(end), end
def reduce_signs(log):
return "".join(re.findall("[0-9]|.[0-9]+", log))
def remove_prefix(log):
log = log.lstrip("+").lstrip("=")
return log.split("=")[-1]
def repeat_last_operation(log, end):
laop = re.findall("[0-9]+$|.[0-9]+$", log)
if end == "==":
log = log + laop[0] + "="
elif end == "-=" or end == "+=":
log = log + end[0] + calculate(log) + "="
elif end:
log = log + "="
return log
def preparation(log):
log, end = separate_end(log)
log = reduce_signs(log)
log = remove_prefix(log)
log = repeat_last_operation(log, end)
return "0" + log
def calculate(log):
log = log.replace("+", " ").replace("-", " -")
return str(sum([int(n) for n in log.split(" ")]))
def last_val(log):
log = log.replace("+", " ").replace("-", " ").replace("=", " ")
return str(int(log.split(" ")[-1]))
def calculator(log: str) -> str:
log = preparation(log)
return last_val(log) if log[-1].isdigit() else calculate(log[:-1])
Feb. 8, 2023
Comments: