Esempio n. 1
0
def infix_to_postfix(infix):
    """
    中缀转后缀
    :param infix:中缀表达式
    :return: 后缀表达式
    """
    opstack = Stack()  # 操作符栈
    result = []

    for token in infix:
        if is_operand(token):  # 操作数
            result.append(token)
        elif token == '(':  # 遇到左括号,入栈
            opstack.push(token)
        elif token == ')':  # 遇到右括号,弹栈并将值放至result列表末尾, 直到遇到左括号
            _token = opstack.pop()
            while _token and _token != '(':
                result.append(_token)
                _token = opstack.pop()

        else:  # 遇到操作符,压栈,但是如果在栈中有比当前操作符优先级高的任何操作符要先弹出
            while not opstack.is_empty():
                top_token = opstack.peek()
                if higher_precedence(top_token, token):
                    result.append(opstack.pop())
                else:
                    break
            opstack.push(token)

    while not opstack.is_empty():
        result.append(opstack.pop())

    return ''.join(result)
def brackets_match(bracket_str):
    """括号匹配"""
    balanced = True
    stack = Stack()

    for s in bracket_str:
        if s == '(':
            stack.push(s)
        else:
            if stack.is_empty():
                balanced = False
                break
            else:
                stack.pop()

    return balanced and stack.is_empty()
Esempio n. 3
0
def symbol_match(symbol_str):
    balanced = True
    stack = Stack()

    for s in symbol_str:
        if s in OPEN_CHARS:
            stack.push(s)
        else:
            if stack.is_empty():
                balanced = False
                break
            else:
                top_val = stack.pop()
                if not match(top_val, s):
                    balanced = False
                    break

    return balanced and stack.is_empty()
Esempio n. 4
0
def convert_to_binary(number):
    s = Stack()

    while number:
        s.push(number % 2)
        number /= 2

    bin_digits = []
    while not s.is_empty():
        bin_digits.append(str(s.pop()))

    return ''.join(bin_digits)
Esempio n. 5
0
 def test_is_empty_with_empty(self):
     mystack = Stack()
     self.assertTrue(mystack.is_empty())