一、中序表达式转换成后序表达式
from main import Stack
import string
def infixToPostfix(infixexper):
'''
中序表达式到后序表达式的转换
:param infixexper:
:return:
'''
# 给运算符定义优先级
prec = {}
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
opStack = Stack() # 保存运算符的空栈
postfixList = [] # 保存运算数的空列表
count = 0 # '('的计数,检测到则加1,检测到')'减1,看最后值是否为0
tokenList = infixexper.split()
lenth = len(tokenList)
# 常见的输入异常错误
for i in range(lenth):
# 两个运算数相邻情况
if tokenList[i] in string.ascii_uppercase and (
tokenList[i + 1] in string.ascii_uppercase or tokenList[i - 1] == ")" or tokenList[i + 1] == "("):
return "Input Error"
# 两个运算符相邻情况
if tokenList[i] in "+-*/" and (tokenList[i + 1] in "+-*/)" or tokenList[i - 1] in "+-*/("):
return "Input Error"
# )(相邻情况
if i + 1 < lenth and tokenList[i] == ')' and tokenList[i + 1] == "(":
return "Input Error"
for token in tokenList:
if token in string.ascii_uppercase: # 检测运算数,将其加入postfixList列表中
postfixList.append(token)
elif token == '(':
count += 1
opStack.push(token)
elif token == ')':
count -= 1
topToken = opStack.pop()
while topToken != '(':
postfixList.append(topToken)
topToken = opStack.pop()
else:
while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]):
postfixList.append(opStack.pop())
opStack.push(token)
#左右括号不等的时候
if count != 0:
return "Input Error"
while not opStack.isEmpty():
postfixList.append(opStack.pop())
return " ".join(postfixList)
infixexpr = "( A + B ) * ( C D )"
print(infixToPostfix(infixexpr))
二、后序表达式的计算
from main import Stack
def postfixEval(postfixExpr):
'''
计算后序表达式
:param postfixExpr: 输入一个后序表达式
:return: 返回一个结果
'''
operandStack = Stack()
# 从左向右遍历,如果为操作数则存入栈中,如果是运算符则取出栈中的两个运算数进行计算,结果存入栈中
tokenList = postfixExpr.split() # 转化为列表
# 使用try、except语句进行异常处理
try:
for token in tokenList:
# 遍历到运算数
if token in "0123456789":
operandStack.push(int(token)) # 列表中的数据是字符型
# 遍历到运算符
else:
operandr = operandStack.pop() # 中序右运算数
operandl = operandStack.pop() # 中序左运算数
result = domath(token, operandl, operandr)
operandStack.push(result)
if operandStack.size() == 1:
return operandStack.pop()
else:
return "Input Error"
except:
return "Input Error"
def domath(token, operandl, operandr):
'''
定义运算
:param token: 运算符
:param operandl: 运算数
:param operandr: 运算数
:return: 运算结果
'''
if token == "*":
result = operandl * operandr
elif token == "/":
result = operandl / operandr
elif token == "+":
result = operandl + operandr
elif token == "-":
result = operandl - operandr
else:
#如果输入的运算符未定义,会输出错误信息,但是会额外多输出一个数字
print("Input operator does not define the operation ")
return 0
return result
print(postfixEval("4 5 6 7 8 + - +"))
print(postfixEval("4 5 6 7 8 ^ + - +"))
三、计算完全括号表达式(中序表达式)
from main import Stack
def infixEval(infixExpr):
'''
计算中序表达式
:param postfixExpr: 输入一个完全括号中序表达式
:return: 返回一个结果
'''
# 使用两个栈从左到右处理中序表达式,operandStack栈存运算符,numStack栈存运算数
operandStack = Stack()
numStack = Stack()
tokenList = infixExpr.split() # 转化为列表
# 中序表达式的计算方式
for token in tokenList:
# 遍历到运算符
if token in "+-*/()":
if token == ")":
while operandStack.peek() != "(":
numr = numStack.pop()
numl = numStack.pop()
operand = operandStack.pop()
result = domath(operand, numl, numr)
numStack.push(result)
operandStack.pop()
# 遍历到"(+-*/"运算数
else:
operandStack.push(token)
# 遍历到运算数
else:
numStack.push(float(token))
# 计算完成后,出栈最后一个值即为计算结果
return numStack.pop()
def domath(operand, numl, numr):
'''
定义运算
:param operand: 运算符
:param numl: 运算数
:param numr: 运算数
:return: 运算结果
'''
if operand == "*":
result = numl * numr
elif operand == "/":
result = numl / numr
elif operand == "+":
result = numl + numr
else:
result = numl - numr
return result
print(infixEval("( 2 * 13.1 )"))