Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Calculator-II by tokiojapan55
def calculator(log: str) -> str:
cpu = {
"display": "0",
"state": "num",
"operator": "=",
"memory": 0,
"pre": "",
"last": "",
}
for k in list(log):
if k.isdigit():
if cpu["state"] != "num" or cpu["display"] == "0":
cpu["display"] = ""
cpu["display"] += k
cpu["state"] = "num"
elif k in "=+-":
if cpu["operator"] == "=" and cpu["pre"] not in "+-=":
cpu["memory"] = eval(cpu["display"])
elif cpu["pre"] + k == "+=":
cpu["memory"] *= 2
elif cpu["pre"] + k == "-=":
cpu["memory"] = 0
elif cpu["pre"] + k == "==":
cpu["memory"] = eval(str(cpu["memory"]) + cpu["last"])
elif cpu["operator"] == "=":
cpu["memory"] = eval(cpu["display"])
elif cpu["state"] == "num":
cpu["last"] = cpu["operator"] + cpu["display"]
cpu["memory"] = eval(str(cpu["memory"]) + cpu["last"])
cpu["display"] = str(cpu["memory"])
cpu["state"] = "ope"
cpu["operator"] = k
cpu["pre"] = k
return cpu["display"]
Aug. 18, 2023
Comments: