Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Calculator-I by ddx1
def calculator(log: str) -> str:
log = log.lstrip('0+=')
nums_actions = []
actions = ['+', '-', '=']
cur_number = ''
for l in list(log):
if l.isdigit() or (l == '-' and cur_number == ''):
cur_number += l
else:
nums_actions.append(cur_number.lstrip('0'))
nums_actions.append(l)
cur_number = ''
if cur_number != '':
nums_actions.append(cur_number.lstrip('0'))
if any([_ in nums_actions for _ in actions]):
if nums_actions[-1] not in actions:
return nums_actions[-1]
else:
number = int(nums_actions[0])
for n_a in range(2, len(nums_actions) - 1):
if nums_actions[n_a - 1] == '+':
number += int(nums_actions[n_a])
if nums_actions[n_a - 1] == '-':
number -= int(nums_actions[n_a])
if nums_actions[n_a - 1] == '=':
number = int(nums_actions[n_a])
return str(number)
return log if len(log) > 0 else '0'
June 5, 2024
Comments: