05.栈、栈的简单应用--括号匹配问题
class StackUnderflow(ValueError): """空栈访问""" pass class SStack: """ 基于顺序表实现栈类 最后一个为栈顶 """ def __init__(self): self._elems = [] def is_empty(self): return self._elems == [] def top(self): if self.is_empty(): raise StackUnderflow("in SStack.top()") return self._elems[-1] def push(self, elem): self._elems.append(elem) def pop(self): if self.is_empty(): raise StackUnderflow("in SStack.pop()") return self._elems.pop() def print(self): print(self._elems[::-1]) class LNode: """链表节点""" def __init__(self, elem, next_=None): self.elem = elem self.next = next_ class LStack: """ 基于链表实现的栈类,表头端为栈顶,用LNode作结点 """ def __init__(self): self._top = None def is_empty(self): return self._top is None def top(self): if self.is_empty(): raise StackUnderflow("in LStack.top()") return self._top.elem def push(self, elem): self._top = LNode(elem, self._top) def pop(self): if self.is_empty(): raise StackUnderflow("in LStack.pop()") p = self._top self._top = p.next return p.elem def print(self): p = self._top print('[', end='') while p is not None: print(p.elem, end=',') if (p.next is not None) else print(p.elem, end='') p = p.next print(']', end='') print() if __name__ == '__main__': st1 = SStack() st1.push(1) st1.push(2) st1.print() if not st1.is_empty(): print(st1.top()) print(st1.pop()) if not st1.is_empty(): print(st1.top()) print("-------------") lst1 = LStack() lst1.push(1) lst1.push(2) lst1.print() if not lst1.is_empty(): print(lst1.top()) print(lst1.pop()) if not lst1.is_empty(): print(lst1.top())
括号匹配问题:
def check_parents(text): """括号配对检查函数,text为被检查的正文串""" parent = "()[]{}" # 所有括号 open_parents = "([{" # 开括号字符 opposite = {")": "(", "]": "[", "}": "{"} # 配对关系字典 def parentheses(text): """ 括号生成器 返回text里的下一括号及其位置 """ i, text_len = 0, len(text) while 1: while i < text_len and text[i] not in parent: i += 1 if i >= text_len: return yield text[i], i # 每次执行到yield产生出下一个值 i += 1 st = SStack() for pr, i in parentheses(text): if pr in open_parents: st.push(pr) elif st.pop() != opposite[pr]: print("Unmatching is found at", i, "for", pr) return False print("All parentheses are correctly matched.") return True if __name__ == '__main__': print(check_parents("(123)")) print(check_parents("(123]")) # All parentheses are correctly matched. # True # Unmatching is found at 4 for ] # False