您的位置:首页 > 其它

Basic Calculator II

2015-08-23 20:44 169 查看
题目:

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers,
+
,
-
,
*
,
/
operators
and empty spaces
. The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5


Note: Do not use the
eval
built-in
library function.

解题思路:

类似于Basic Calculator I。代码如下:

class Solution(object):

def calculate(self, s):

"""

:type s: str

:rtype: int

"""

def cal(num1,num2,op):

if op=='+':

return num1+num2

elif op=='-':

return num1-num2

elif op=='*':

return num1*num2

elif op=='/':

return num1/num2

def readNum(s,index):

res = 0

while s[index] in '0123456789':

res = 10*res+int(s[index])

index = index+1

return res,index

map = {'$':0, '+':1, '-':1, '*':2, '/':2}

operator, operand = ['$'], []

s = ''.join((s+'$').split())

index = 0

while len(operator)!=0:

i = s[index]

if i not in '+-*/$':

num ,index= readNum(s,index)

operand.append(num)

else:

if i=='$' and operator[len(operator)-1]=='$':

return operand.pop()

elif map[i]>map[operator[len(operator)-1]]:

operator.append(i)

index += 1

else:

num1,num2 = operand.pop(), operand.pop()

num = cal(num2,num1,operator.pop())

operand.append(num)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: