算术表达式中分隔符匹配算法的实现 --栈

版权声明:本文博主原创,转载请注明出处,感谢您的合作! https://blog.csdn.net/Thanlon/article/details/89318207
理论:

例如:表达式[(x+y)-(x-y)],每次遇到开始符时,将其压入栈中.每次遇到结束符时,将栈顶的分隔符弹出,在栈不为空的情况下,检查两个分隔符是否能组成有效的一对.如果扫描表达式到最后栈为空,则表示匹配成功.否则,匹配失败,栈中一定至少存在一个开始分隔符没有被匹配.

实现:
class IsMatched:
    def is_matched(self, expr):
        lefty = '({{'
        righty = ')}}'
        S = ArrayStack()
        for c in expr:  # traverse expression
            if c in lefty:
                S.push()
            elif c in righty:
                if S.is_empty():  # If stack is empty,it's clearly confirmed "unsuccessfully matched!"
                    return False
                # If variable "c" is belong to variable "righty",and S.pop is belong to variable lefty, successfully matched!
                if righty.index(c) != lefty.index(S.pop()):
                    return False
        return S.is_empty()


class ArrayStack:
    def __init__(self):
        # Create an empty stack
        self.__data = []

    def __len__(self):
        # Return the number of elements in the stack
        return len(self.__data)

    def is_empty(self):
        # Retutn True if the stack is empty
        return len(self.__data) == 0

    def push(self, e):
        # Add an element to the top of stack
        self.__data.append(e)

    def pop(self):
        # If element is empty ,it will raise Empty exception
        if self.is_empty():
            raise Empty('Stack is empty!')
        # Remove and return the element from the top of the stack
        return self.__data.pop()

    def top(self):
        # If element is empty ,it will raise Empty exception
        if self.is_empty():
            raise Empty('Stack is empty!')
        # Return the last item in the list
        return self.__data[-1]


class Empty(Exception):
    pass

我的网址:www.blueflags.cn

猜你喜欢

转载自blog.csdn.net/Thanlon/article/details/89318207