class IsLackBracket: def __init__(self, text_): self._list = SStack() self.__text = text_ def is_lack_bracket(self): i = 0 while True: while i < len(self.__text): if self.__text[i] not in ("([{)]}"): i += 1 break if self.__text[i] in ("([{"): self._list.push(self.__text[i]) i += 1 break if self.__text[i] is ")" and self._list.top() is "(": self._list.pop() elif self.__text[i] is "]" and self._list.top() is "[": self._list.pop() elif self.__text[i] is "}" and self._list.top() is "{": self._list.pop() elif self.__text[i] in (")]}"): raise SStackError("%s不匹配" % self.__text[i]) i += 1 else: if self._list.is_empty(): raise SStackError("%s不匹配" % self._list.top()) else: print("匹配")
def Inf2Suf(line): st = SStack() exp = [] for x in tokens(line): if x not in infix_operators: exp.append(x) elif st.is_empty() or x == '(': st.push(x) elif x == ')': while not st.is_empty() and st.top() != '(': exp.append(st.pop()) if st.is_empty(): raise SyntaxError("Missing '('.") st.pop() else: while (not st.is_empty() and priority[st.top()] >= priority[x]): exp.append(st.pop()) st.push(x) while not st.is_empty(): if st.top() == '(': raise SyntaxError("Extra '('.") exp.append(st.pop()) return exp
def trans_infix_suffix(line): st = SStack() exp = [] for x in tokens(line): if x not in infix_operators: # 运算对象直接送出 exp.append(x) elif st.is_empty() or x == '(': # 左括号进栈 st.push(x) elif x == ')': # 处理右括号 while not st.is_empty() and st.top() != '(': exp.append(st.pop()) if st.is_empty(): # 没找到左括号 raise SyntaxError("Missing '('.") st.pop() # 弹出左括号 else: # 处理算术运算符,运算符都看作左结合 while(not st.is_empty() and priority[st.top()] >= priority[x]): exp.append(st.pop()) st.push(x) while not st.is_empty(): # 送出栈里面剩下的运算符 if st.top() == '(': # 多余的左括号 raise SyntaxError("Extra '('.") exp.append(st.pop()) return exp
def postorder_nonrec(t, proc): s = SStack() while t is not None or not s.is_empty(): while t is not None: s.push(t) t = t.left if t.left else t.right t = s.pop() proc(t.data) if not s.is_empty() and s.top().left == t: t = s.top().right else: t = None
def postorder_nonrec(t, proc): s = SStack() while t or not s.is_empty(): while t: # 下行循环,直到栈顶的两子树空 s.push(t) t = t.left if t.left else t.right # 能左就左,否则向右 t = s.pop() # 栈顶是应访问节点 proc(t.data) if not s.is_empty() and s.top().left == t: t = s.top().right else: t = None