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
复制代码

 

posted @   fly_bk  阅读(150)  评论(0编辑  收藏  举报
编辑推荐:
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
阅读排行:
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(三):用.NET IoT库
· 【非技术】说说2024年我都干了些啥
历史上的今天:
2018-10-22 Ubuntu端口命令---查看端口占用及关闭
点击右上角即可分享
微信分享提示