def buildParseTree(self):
        """
        构建解析树
        使用栈来保存父节点
        """
        pStack = Stack()
        eTree = BinaryTree('')
        pStack.push(eTree)
        curentTree = eTree
        for i in self.fplist:
            # 如果标记是 (, 为当前节点创建一个子节点, 并下沉至该节点
            if i == "(":

                curentTree.insertLeft("")
                pStack.push(curentTree)
                curentTree = curentTree.getLeftChild()
            # 如果当前标记在列表["+", "-", "/", "*"], 将当前节点的值设置为当前标记对应的运算符;为当前节点穿件一个右节点并下沉至该节点
            elif i not in "=-*/":
                curentTree.setRootVal(eval(i))
                parent = pStack.pop()
                curentTree = parent
            # 如果当前值是是数值, 就将当前节点的数值设置为该数值并返回至父节点
            elif i in "=-*/":
                curentTree.setRootVal(eval(i))
                curentTree.insertRight("")
                pStack.push(curentTree)
                curentTree.getRightChild()
            # 如果标记是), 则跳到当前节点的父节点
            elif i == ")":
                parent = pStack.pop()
                curentTree = parent
            else:
                raise ValueError("Error: %s" % i)
        return eTree
Beispiel #2
0
class MyQueue:
    def __init__(self):
        self.new_stack = Stack()
        self.old_stack = Stack()

    def _shift_stacks(self):
        if self.old_stack.is_empty():
            while not self.new_stack.is_empty():
                self.old_stack.push(self.new_stack.pop())

    def add(self, value):
        return self.new_stack.push(value)

    def peek(self):
        if self.is_empty():
            return False
        self._shift_stacks()
        return self.old_stack.peek()

    def remove(self):
        if self.is_empty():
            return False
        self._shift_stacks()
        return self.old_stack.pop()

    def is_empty(self):
        return len(self) == 0

    def __len__(self):
        return len(self.new_stack) + len(self.old_stack)
class SortedStack(Stack):
    def __init__(self):
        super().__init__()
        self.temp_stack = Stack()

    def push(self, item):
        if self.is_empty() or item < self.peek():
            super().push(item)
        else:
            while self.peek() is not None and item > self.peek():
                self.temp_stack.push(self.pop())
            super().push(item)
            while not self.temp_stack.is_empty():
                super().push(self.temp_stack.pop())
class MinStack(Stack):
    def __init__(self):
        super().__init__()
        self.minvals = Stack()

    def push(self, value):
        super().push(value)
        if not self.minvals or value <= self.min():
            self.minvals.push(value)

    def pop(self):
        value = super().pop()
        if value == self.min():
            self.minvals.pop()
        return value

    def min(self):
        return self.minvals.peek()
Beispiel #5
0
 def calculatePostOrderFormulas(self, postOrderformulas):
     """
     计算后序表达式
     """
     operaDict = {
         "+": operator.add,
         "-": operator.sub,
         "*": operator.mul,
         "/": operator.truediv
     }
     postStack = Stack()
     postOrderList = list(postOrderformulas)
     for ch in postOrderList:
         if ch.isdigit():
             postStack.push(eval(ch))
         else:
             opN1 = postStack.pop()
             opN2 = postStack.pop()
             postStack.push(operaDict[ch](opN2, opN1))
     return postStack.pop()
Beispiel #6
0
class RStack:

    rStack = Stack()
    convertString = "0123456789ABCDEF"

    def formatHex(self, n, base):
        self.toStr(n, base)
        hexNum = ""
        while not self.rStack.isEmpty():
            hexNum += self.rStack.pop()
        return hexNum

    def toStr(self, n, base):
        assert isinstance(n, int)
        assert isinstance(base, int)
        assert base <= len(self.convertString)
        if n < base:
            self.rStack.push(self.convertString[n])
        else:
            self.rStack.push(self.convertString[n % base])
            self.toStr(n // base, base)
Beispiel #7
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
Beispiel #8
0
 def __init__(self):
     self.new_stack = Stack()
     self.old_stack = Stack()
Beispiel #9
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)
 def __init__(self):
     super().__init__()
     self.temp_stack = Stack()
 def __init__(self):
     super().__init__()
     self.minvals = Stack()