Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Calculator-III by imloafer
def calculator(log: str) -> str:
# your code here
def is_error(tmp):
if len(tmp) < 3:
ans = tmp[-1]
else:
if len(ans := str(eval(''.join(tmp[:3])))) > 5:
return 'error'
for i in range(0, len(tmp[3:]), 2):
if len(ans) > 5:
ans = 'error'
break
ans = str(eval(ans + ''.join(tmp[i+3:i+5])))
return ans
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]
while log[-1] in '=+-':
log = log.rstrip(log[-1])
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')[:5])
symbol = ch
j = i + 1
if symbol:
tmp.append(symbol)
if log[j:]:
tmp.append(log[j:].lstrip('0')[:5])
# inside '='
while '=' in tmp:
tmp = tmp[tmp.index('=')+1:]
# decide output
if tail == '':
ans = tmp[-1]
elif tail in ['+', '-', '=', '=+', '=-']:
ans = is_error(tmp + ['+', '0'])
elif tail == '-=':
ans = '0'
elif tail == '+=':
ans = is_error(tmp)
if ans != 'error':
ans = is_error([ans, '+', ans])
elif tail == '==':
if len(tmp) == 1:
ans = is_error(tmp + ['+', tmp[-1]])
else:
ans = is_error(tmp + tmp[-2:])
return ans
print("Example:")
print(calculator("100000"))
# These "asserts" are used for self-checking
assert calculator('50000-====') == 'error'
assert calculator("123456789") == "12345"
assert calculator("123456789+5=") == "12350"
assert calculator("5+123456789") == "12345"
assert calculator("123456789+5=") == "12350"
assert calculator("90000+10000=") == "error"
assert calculator("90000+10000-10000=") == "error"
assert calculator("90000+10000-10000") == "10000"
assert calculator("50000+=") == "error"
assert calculator("3+=") == "6"
assert calculator("3+2==") == "7"
assert calculator("3+-2=") == "1"
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. 27, 2023
Comments: