Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Calculator-II by imloafer
def calculator(log: str) -> str:
# your code here
tail = symbol = ''
tmp, j = [], 0
# remove leading zeros and symbols
try:
while log[0] in '0+-=':
log = log.lstrip(log[0])
except IndexError:
return '0'
# split tail
if log[-2:] in ['-=', '+=', '==', '=-', '=+']:
tail, log = log[-2:], log[:-2]
if log[-1] in '-+=':
tail, log = log[-1], log[:-1]
# remove extra symbols
for i, ch in enumerate(log):
if ch in '-+=':
if j != i:
if symbol:
tmp.append(symbol)
tmp.append(log[j:i].lstrip('0'))
symbol = ch
j = i + 1
if symbol:
tmp.append(symbol)
if log[j:]:
tmp.append(log[j:].lstrip('0'))
# inside '='
while '=' in tmp:
tmp = tmp[tmp.index('=')+1:]
# decide output
if tail == '':
ans = tmp[-1]
elif tail in ['+', '-', '=', '=+', '=-']:
ans = str(eval(''.join(tmp) + '+0'))
elif tail in ['+=', '-=']:
ans = str(eval(''.join(tmp) + tail[0] + '(' + ''.join(tmp) + ')'))
elif tail == '==':
ans = str(eval(''.join(tmp + tmp[-2:])))
return ans
print("Example:")
print(calculator("3+="))
# These "asserts" are used for self-checking
assert calculator('2+3=+7=') == '12'
assert calculator('2+3=7+7=') == '14'
assert calculator('3+2-=') == '0'
assert calculator("-=-+3-++--+-2=-") == "1"
assert calculator("3+=") == "6"
assert calculator("3+2==") == "7"
assert calculator("3+-2=") == "1"
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. 26, 2023
Comments: