Пример #1
0
    def conversionToPostOrder(self, inOrdErexpr):
        """
        后序转换
        """
        # 构建运算符优先级字典
        prec = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1, ")": 1}

        if not self.parseChecker(inOrdErexpr):
            raise ValueError

        opStack = Stack()
        postOrderList = list()
        exprList = inOrdErexpr.split()

        for ch in exprList:
            if ch.isdigit():
                postOrderList.append(ch)
            elif ch == "(":
                opStack.push(ch)
            elif ch == ")":
                topOper = opStack.pop()
                while topOper != "(":
                    postOrderList.append(topOper)
                    topOper = opStack.pop()
            else:
                # 比较运算符优先级,如果栈中运算符的优先级>当前运算符, 追加至转换列表中
                while (not opStack.isEmpty()) and (prec[opStack.peek()] >
                                                   prec[ch]):
                    postOrderList.append(opStack.pop())
                opStack.push(ch)
        # 将栈中的运算符追加至转换列表中
        while not opStack.isEmpty():
            postOrderList.append(opStack.pop())
        return "".join(postOrderList)
Пример #2
0
 def parseChecker(self, symbolStr):
     s = Stack()
     balanced = True
     index = 0
     while index < len(symbolStr) and balanced:
         symbol = symbolStr[index]
         if symbol in "{[(":
             s.push(symbol)
         elif s.isEmpty():
             balanced = False
         else:
             topSym = s.pop()
             if not self.matches(topSym, symbol):
                 balanced = False
         index += 1
     if balanced and s.isEmpty():
         return True
     else:
         return False