题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
n = input()
nums = '0123456789'
operators = '+-*/[](){}'
numstack =[] #记录数字
operatorstack = [] #纪录操作符并判断优先级
def szys(a,b,s):
if s == '+':
return a+b
elif s == '-':
return a-b
elif s == '*':
return a*b
else:
return int(a/b)
prev = ''
flag = 1
for s in n :
if s in nums:
if prev in operators or not prev:
numstack.append(flag*int(s))
else:
numstack.append(10*numstack.pop()+flag*int(s))
else:
flag = 1
if s in '+-':
if not numstack:
numstack.append(0)
if not operatorstack:
operatorstack.append(s)
else:
if prev in '([{' :
if s =="+":
flag = 1
else:
flag = -1
continue
while operatorstack and operatorstack[-1] in '+-*/':
tempoperator = operatorstack.pop()
numb = numstack.pop()
numa = numstack.pop()
numstack.append(szys(numa,numb,tempoperator))
operatorstack.append(s)
elif s in '*/':
operatorstack.append(s)
elif s in '([{':
operatorstack.append('(')
else:
while operatorstack[-1] != '(':
tempoperator = operatorstack.pop()
numb = numstack.pop()
numa = numstack.pop()
numstack.append(szys(numa,numb,tempoperator))
operatorstack.pop()
prev = s
while operatorstack:
tempoperator = operatorstack.pop()
numb = numstack.pop()
numa = numstack.pop()
numstack.append(szys(numa,numb,tempoperator))
print(numstack[0])
不用eval的做法,改了俩小时才对,写进题解里自己记录一下


