- def calc(str):
- import re
- #抽提数字
- num=re.compile('\\d+')
- #抽提运算符和括号
- opr=re.compile('[+\\-*/()]')
- #运算符优先级
- rgt={'(':0,'+':1,'-':1,'*':2,'/':2,')':3}
- #运算符的匿名运算函数
- fac={'+':lambda x,y:x+y,'-':lambda x,y:x-y,'*':lambda x,y:x*y,'/':lambda x,y:x/y}
- #中间值的栈
- ans=[]
- #运算符的栈
- stk=['(',]
- while str:
- i=num.match(str)#判断是否数字
- j=opr.match(str)#判断是否符号
- if i:
- #数字直接入ans栈
- ans.append(int(i.group(),10))
- str=str[i.end():]
- elif j:
- if(str[0]=='('):
- #左括号直接入stk栈
- stk.append(str[0])
- elif(str[0]==')'):
- #右括号要进行清栈操作
- while stk[-1]!='(':
- ans[-2]=fac[stk.pop()](ans[-2],ans[-1])
- ans.pop()
- stk.pop()
- else:
- #因为是左结合,所以根据优先级先出栈再入栈
- while rgt[stk[-1]]>=rgt[str[0]]:
- ans[-2]=fac[stk.pop()](ans[-2],ans[-1])
- ans.pop()
- stk.append(str[0])
- str=str[1:]
- else:
- return 0
- #stk清栈
- while stk[-1]!='(':
- ans[-2]=fac[stk.pop()](ans[-2],ans[-1])
- ans.pop()
- #ans栈的0位就是结果(算式无误的话)
- return ans[0]
- #该片段来自于http://www.codesnippet.cn/detail/030720134408.html
来源: http://www.codesnippet.cn/detail/030720134408.html