# leetcode之Basic Calculator II

class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
import re
listofnum = []
listofsym = []
symbol = ['*', '/', '+', '-']
#空集
if len(s) == 0:
return 0
#一个字母
try:
return int(s)
except:
#将所有项分别列出来
s = re.sub(' ', '', s)
n = ''
for i in range(len(s)):
try:
if s[i] in symbol:
listofnum.append(int(n))
listofsym.append(s[i])
n = ''
elif i == len(s) - 1:
n = n + s[i]
listofnum.append(int(n))
else:
n = n + s[i]
except:
listofsym.append(s[i])
#计算乘除
if s[i] in ['+', '-']:
a = listofsym.pop()
if listofsym != []:
if listofsym[-1] in ['*', '/']:
listofnum1 = []
listofsym1 = []
listofnum1.append(listofnum.pop())
try:
while listofsym[-1] not in ['+', '-']:
listofsym1.append(listofsym.pop())
listofnum1.append(listofnum.pop())
except:
listofnum1 = listofnum1
listofsym1 = listofsym1
for i in listofsym1[::-1]:
a1 = listofnum1.pop()
b1 = listofnum1.pop()
if i == '*':
listofnum1.append(a1 * b1)
else:
if a1 > 0:
if b1 > 0:
listofnum1.append(a1 / b1)
else:
listofnum1.append(-(a1 / (-b1)))
else:
if b1 > 0:
listofnum1.append(-(-a1 / b1))
else:
listofnum1.append(a1 / b1)
listofnum.append(listofnum1[0])
listofsym.append(a)
#计算最后的
if listofsym[-1] in ['*', '/']:
listofnum1 = []
listofsym1 = []
listofnum1.append(listofnum.pop())
while listofsym != []:
if listofsym[-1] not in ['+', '-']:
listofsym1.append(listofsym.pop())
listofnum1.append(listofnum.pop())
else:
break
for i in listofsym1[::-1]:
a1 = listofnum1.pop()
b1 = listofnum1.pop()
if i == '*':
listofnum1.append(a1 * b1)
else:
if a1 > 0:
if b1 > 0:
listofnum1.append(a1 / b1)
else:
listofnum1.append(-(a1 / (-b1)))
else:
if b1 > 0:
listofnum1.append(-(-a1 / b1))
else:
listofnum1.append(a1 / b1)
listofnum.append(listofnum1[0])
while len(listofsym) != 0:
a = listofnum.pop()
b = listofnum.pop()
try:
if listofsym[-1] == '-':
if listofsym[-2] == '-':
listofnum.append(a + b)
else:
listofnum.append(b - a)
else:
if listofsym[-2] == '-':
listofnum.append(b - a)
else:
listofnum.append(b + a)
listofsym.pop()
except:
if listofsym[-1] == '-':
return b - a
else:
return a + b
return listofnum[0]

04-30 735

06-26 7094

01-30 788

04-05 633

06-14 8538

04-10 340

06-19 7981

01-26 441

08-28 1098

03-21 181