leetcode 基本计算器 II python 之xue小的玩笑

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 庄周梦蝶如温洁 比翼双飞恋露台 莫若梁兄心景醉 嗅香彩翅索玫瑰 平水韵【十灰】
    捉刀客王静阅读 212评论 0 1
  • 首先要知道的是! 我们是野兽,自称人。 很多欲望是我们hold不住的,很多我们难以接受的事别人做起来很随意。 这本...
    井井有窕阅读 770评论 0 0
  • 站在垫子的前端,屈双膝,双手放在右脚的两侧,撤右脚向后一大步,右膝落地,小腿脚背发力下沉,膝前上侧肌肉群触地,如果...
    维维yoga阅读 2,209评论 0 2