String Calculator without parenthesis
def calculate(s):
return helper(s)
def helper(s, index):
ops = {"+", "-", "/", "*", "#"}
sign = '+'
num = 0
stack = []
i = index
s = s + "#"
while i < len(s):
if s[i].isdigit():
num = num*10 + int(s[i])
if s[i] in ops:
if sign == "+":
stack.append(num)
elif sign == '-':
stack.append(-num)
elif sign == "*":
tmp = stack.pop()
print(tmp, num, tmp * num)
stack.append(tmp*num)
elif sign == "/":
tmp = stack.pop()
stack.append(tmp // num)
sign = s[i]
# mistake
num = 0
i += 1
return sum(stack)
String Calculator with parenthesis
def calculate(s):
s = s + "#"
_, _sum = helper(s, 0)
return _sum
def helper(s, i):
stack = []
sign = "+"
num = 0
while i < len(s):
if s[i] == " ":
pass
elif s[i].isdigit():
num = num*10 + int(s[i])
elif s[i] == "(":
i, num = helper(s, i + 1)
else:
if sign == "+":
stack.append(num)
elif sign == "-":
stack.append(-num)
elif sign == "*":
prev = stack.pop()
stack.append(prev * num)
elif sign == "/":
prev = stack.pop()
stack.append(prev / num)
if s[i] == ")":
return i, sum(stack)
sign = s[i]
num = 0
i += 1
return i, sum(stack)