Exemple #1
0
class Buffer:
    def __init__(self):
        self.__right = Stack()
        self.__left = Stack()
        self.__N = 0

    def insert(self, c):
        self.__right.push(c)
        self.__N += 1

    def delete(self):
        self.__N -= 1
        return self.__right.pop() if not self.__right.is_empty() else ''

    def left(self, k):
        for i in range(k):
            if self.__left.is_empty():
                return
            self.__right.push(self.__left.pop())

    def right(self, k):
        for i in range(k):
            if self.__right.is_empty():
                return
            self.__left.push(self.__right.pop())

    def size(self):
        return self.__N
Exemple #2
0
def parentheses(test_str):
    s = Stack()
    for i in test_str:
        if i in right_parenthesis:
            s.push(i)
        else:
            pop = s.pop()
            if not ord(pop) - ord(i) <= 2:  # 比较ascii数值,小于等于2的话就是匹配的左括号
                return False
    return s.is_empty()
Exemple #3
0
operator_precedence = {'+': 1, '-': 1, '*': 2, '/': 2}
res_str = ''


def not_greater(this, peek):
    try:
        a = operator_precedence[this]
        b = operator_precedence[peek]
        return True if a <= b else False
    except KeyError:
        return False


for i in test_str_list:
    if i.isnumeric():
        res_str += i + ' '
    elif i == '(':
        operator_stack.push(i)
    elif i == ')':
        while not operator_stack.is_empty() and operator_stack.peek() != '(':
            res_str += operator_stack.pop() + ' '
        operator_stack.pop()
    else:
        while not operator_stack.is_empty() and not_greater(i, operator_stack.peek()):
            res_str += operator_stack.pop() + ' '
        operator_stack.push(i)
while not operator_stack.is_empty():
    res_str += operator_stack.pop()

print(res_str)