棧的應用(前綴中綴後綴轉換)

 

class Stack:
    def __init__(self):
        self.items=[]
    def isEmpty(self):
        return self.items==[]
    def push(self,item):
        #添加元素進站
        self.items.append(item)
    def peek(self):
        #打印棧頂元素
        return self.items[len(self.items)-1]
    def pop(self):
        #從棧頂取出元素
        return self.items.pop()
    def size(self):
        #返回棧中元素的個數
        return len(self.items)

def infixToPostfix(infixexpr):
    # prec字典存儲着運算符的優先級
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    # 定義空棧存儲運算符出棧和進棧操做結果
    openStack = Stack()
    # 存儲最後的後綴表達式的結果list
    postficList = []
    # tokenList存儲將表達式分割字符後的list,要求表達式中的字符之間必須有空格
    tokenList = infixexpr.split()

    for token in tokenList:
        # 只要分割的字符在A-Z或者阿拉伯數字0-9之間放到postficList
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token.isnumeric():
            #isnumeric()方法判斷token是不是數字
            postficList.append(token)
            # 左括弧匹配
        elif token == '(':
            openStack.push(token)
        elif token == ')':
            toptoken = openStack.pop()
            # 非括弧符號匹配
            while toptoken != '(':
                postficList.append(toptoken)
                toptoken = openStack.pop()
        else:
            # 運算符優先級比較
            while (not openStack.isEmpty()) and (prec[openStack.peek()] >= prec[token]):
                postficList.append(openStack.pop())
            openStack.push(token)
    while not openStack.isEmpty():
        postficList.append(openStack.pop())

    return " ".join(postficList)

def postfixEval(postfixExpr):
    #後綴表達式的計算
    operandStack=Stack()
    tokenList=postfixExpr.split()
    #對錶達式進行分離
    for token in tokenList:
        if token.isnumeric():
            operandStack.push(int(token))
            #若是是數字就添加進棧,不然從棧裏取出數字進行計算
        else:
            operand2=operandStack.pop()
            operand1=operandStack.pop()
            result=doMath(token,operand1,operand2)
            operandStack.push(result)
    return operandStack.pop()
def doMath(op,op1,op2):
    if op=="*":
        return op1*op2
    elif op=="/":
        return op1/op2
    elif op=="+":
        return op1+op2
    else:
        return op1-op2


if __name__ == '__main__':
    print(infixToPostfix("A * B + C * D"))
    print(infixToPostfix("( ( A * B ) + ( C * D ) )"))
    print(infixToPostfix("A + B * C + D"))
    print(infixToPostfix("( A + B ) * ( C + D )"))
    print(infixToPostfix("A * B + C * D"))
    print(infixToPostfix("83 * 9 + 4"))

    postresult=infixToPostfix("70 * 9 + 4")
    #print(postresult)
    print(postfixEval(postresult))
View Code
相關文章
相關標籤/搜索