题解 | #四则运算# 使用栈将表达式转为后序表达式并计算
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
from operator import pos
def infixToPostfix(S):
precedences = {'+':1, '-':1, '*':2, '/':2}
postfix = []
operators = []
for i,s in enumerate(S):
if s.isdigit():
if i > 0 and S[i-1].isdigit():
postfix[-1] += s
else:
postfix.append(s)
elif s in '{[(':
operators.append(s)
elif s in ')]}':
while operators[-1] not in '{[(':
postfix.append(operators.pop())
operators.pop()
else:
if s == '-' and S[i-1] in '{[(':
postfix.append('0')
while operators and precedences.get(operators[-1], 0)>=precedences[s]:
postfix.append(operators.pop())
operators.append(s)
while operators: postfix.append(operators.pop())
return postfix
def calPostfix(S):
nums = []
for s in S:
if s.isdigit():
nums.append(int(s))
else:
if s == '+':
num1, num2 = nums.pop(), nums.pop()
nums.append(num1+num2)
if s == '-':
num1, num2 = nums.pop(), nums.pop()
nums.append(num2-num1)
if s == '*':
num1, num2 = nums.pop(), nums.pop()
nums.append(num1*num2)
if s == '/':
num1, num2 = nums.pop(), nums.pop()
nums.append(num2/num1)
return int(nums[0])
while True:
try:
S = input()
except:
break
postfix = infixToPostfix(S)
print(calPostfix(postfix))
查看17道真题和解析