leetcode 基本计算器 II python 之xue小的玩
2019-03-29 本文已影响0人
DaydayHoliday
class Solution(object):
def calculate(self, s):
return eval(s.replace('/','//'))
看来内置的执行效率还可以,哈哈哈
栈版本:
class Solution(object):
def calculate(self, s):
def add(x,y):
return x+y
def minus(x,y):
return x-y
def multiply(x,y):
return x*y
def divide(x,y):
return x//y
opes={'+':add,'-':minus,'*':multiply,'/':divide}
sta_nums=[]
sta_opes=[]
numstr=''
for si in s:
if si==' ':
continue
if si>='0' and si<='9':
numstr=numstr+si
continue
else:
num=int(numstr)
numstr=''
if (len(sta_opes)>0 and sta_opes[-1] in [multiply,divide]):
x=sta_nums.pop()
ope=sta_opes.pop()
num=ope(x,num)
sta_nums.append(num)
sta_opes.append(opes[si])
num=int(numstr)
if (len(sta_opes)>0 and sta_opes[-1] in [multiply,divide]):
x=sta_nums.pop()
ope=sta_opes.pop()
num=ope(x,num)
sta_nums.append(num)
res=sta_nums.pop(0)
while (len(sta_opes)>0):
ope=sta_opes.pop(0)
y=sta_nums.pop(0)
res=ope(res,y)
return res