leetcode basic calculator 2 python

https://leetcode.com/problems/basic-calculator-ii/

class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
numstack = []
operators = []
l = len(s)
i=0
while i<l:
if s[i].isdigit():
start = i
while i<l and s[i].isdigit():
i+=1
numstack.append(int(s[start:i]))
elif s[i] in ["+","-","*","/"]:
operators.append(s[i])
i+=1
else:
i+=1
# if there is n operator then there is n+1 nums
for i,operator in enumerate(operators):
if operator in ["*","/"]:
num1,num2 = numstack[i],numstack[i+1]
if operator == "*":
numstack[i],numstack[i+1] = 0,num1*num2
else:
numstack[i],numstack[i+1] = 0,num1/num2
operators[i] = operators[i-1] if i-1 >=0 else "+"
if len(numstack) == 0:
return 0
total = numstack[0]
for i,operator in enumerate(operators):
if operator == "+":
total += numstack[i+1]
else:
total -= numstack[i+1]
return total

评论

此博客中的热门博文

Embedded System interview Question

MicroKernel & Exokernel 操作系统未来可能的发展

中国城市房地产分析