Exemplo n.º 1
0
def recursive_stack(num: int, base: int, stack: Stack) -> None:
    s = '0123456789ABCDEF'
    if num < base:
        stack.push(s[num])
    else:
        stack.push(s[num % base])
        recursive_stack(num // base, base, stack)
Exemplo n.º 2
0
def decimal_to_str(num: int, base: int) -> str:
    """ 将整数转换成以 2~16 为进制基数的字符串 """
    stack, result = Stack(), ''
    recursive_stack(num, base, stack)
    while not stack.isEmpty():
        result += stack.pop()
    return result
Exemplo n.º 3
0
def suffix_expr_value(expr):
    """ 计算后序表达式的值  """
    stack = Stack()

    for i in list(expr.replace(' ', '')):
        if i in '0123456789':
            stack.push(int(i))
        else:
            a, b = stack.pop(), stack.pop()
            stack.push(calculation(i, a, b))
    return stack.pop()
Exemplo n.º 4
0
def is_match_brackets(str) -> bool:
    """ 匹配括号(仅匹配 () 出现的情况)"""
    stack = Stack()
    paired = True
    index = 0
    while index < len(str) and paired:
        symbol = str[index]

        if symbol == '(':
            stack.push(symbol)
        else:
            if stack.isEmpty():
                paired = False
            else:
                stack.pop()
        index += 1

    if paired and stack.isEmpty():
        return True
    else:
        return False
Exemplo n.º 5
0
def decimal_to_binary(num: int) -> int:
    """ 将十进制数转换成二进制数 """
    stack = Stack()

    while num > 0:
        rem = num % 2
        stack.push(rem)
        num //= 2

    result = ''
    while not stack.isEmpty():
        result += str(stack.pop())

    return int(result) if result else 0
Exemplo n.º 6
0
def build_parse_tree(expr: str) -> BinaryTree:
    expr, stack, bt = list(expr.replace(' ', '')), Stack(), BinaryTree('')
    stack.push(bt)
    tree = bt

    for i in expr:
        if i == '(':
            tree.insertLeft('')
            stack.push(tree)
            tree = tree.getLeftChild()
        elif i in '1234567890':
            tree.setRootValue(eval(i))
            tree = stack.pop()
        elif i in '+-*/':
            tree.setRootValue(i)
            tree.insertRight('')
            stack.push(tree)
            tree = tree.getRightChild()
        elif i == ')':
            tree = stack.pop()
        else:
            raise ValueError('Unknown operator: ' + i)
    return bt
Exemplo n.º 7
0
def is_match_brackets(string) -> bool:
    """ 匹配括号(仅匹配 (){}[] 出现的情况)"""
    stack, paired, index = Stack(), True, 0

    while index < len(string) and paired:
        symbol = string[index]

        if symbol in '([{':
            stack.push(symbol)
        else:
            if stack.isEmpty():
                paired = False
            else:
                top = stack.pop()
                if not matches(top, symbol):
                    paired = False
        index += 1

    if paired and stack.isEmpty():
        return True
    else:
        return False
Exemplo n.º 8
0
def decimal_to_any(num: int, base: int):
    """ 将十进制数转换成任意进制数 """
    stack, digits = Stack(), '0123456789ABCDEF'

    while num > 0:
        rem = num % base
        stack.push(rem)
        num //= base

    result = ''
    while not stack.isEmpty():
        result += str(digits[stack.pop()])

    if base == 16:
        flag = False
        for i in result:
            if i not in 'ABCDEF':
                flag = True
                break

        return int(result) if flag else (result if result else 0)
    return int(result) if result else 0
Exemplo n.º 9
0
def infix_to_suffix(expr):
    """ 从中序表达式到后序表达式的转换 """
    stack, suffixes, operators = Stack(), [], {
        '*': 3,
        '/': 3,
        '+': 2,
        '-': 2,
        '(': 1,
        ')': 1,
    }

    for i in list(expr.replace(' ', '')):
        if i.upper() in string.ascii_uppercase:
            suffixes.append(i)
        elif i == '(':
            stack.push(i)
        elif i == ')':
            top = stack.pop()
            while top != '(':
                suffixes.append(top)
                top = stack.pop()
        else:
            while not stack.isEmpty() and operators[
                    stack.peek()] >= operators[i]:
                suffixes.append(stack.pop())
            stack.push(i)

    while not stack.isEmpty():
        suffixes.append(stack.pop())

    return ''.join(suffixes)
Exemplo n.º 10
0
 def setUp(self) -> None:
     self.stack = Stack()
Exemplo n.º 11
0
class StackTestCase(unittest.TestCase):
    """ 测试 stack.py """
    def setUp(self) -> None:
        self.stack = Stack()

    def testStackIsEmpty(self) -> None:
        self.assertTrue(self.stack.isEmpty())

        self.stack.push(1)
        self.assertFalse(self.stack.isEmpty())

    def testStackPush(self) -> None:
        self.stack.push(1)
        self.assertEqual([1], self.stack.items)

        self.stack.push('a')
        self.assertEqual([1, 'a'], self.stack.items)

        self.stack.push(False)
        self.assertEqual([1, 'a', False], self.stack.items)

    def testStackPop(self):
        self.stack.push(1)
        self.stack.push('a')
        self.stack.push(False)
        self.stack.push(None)

        self.stack.pop()
        self.assertEqual([1, 'a', False], self.stack.items)

        self.stack.pop()
        self.assertEqual([1, 'a'], self.stack.items)

        self.stack.pop()
        self.assertEqual([1], self.stack.items)

        self.stack.pop()
        self.assertEqual([], self.stack.items)

    def testStackPeek(self) -> None:
        self.stack.push(1)
        self.assertEqual(1, self.stack.peek())

        self.stack.push('a')
        self.assertEqual('a', self.stack.peek())

        self.stack.push(True)
        self.assertEqual(True, self.stack.peek())

        self.stack.push(None)
        self.assertEqual(None, self.stack.peek())

    def testStackSize(self) -> None:
        self.stack.push(99)
        self.assertEqual(1, self.stack.size())

        self.stack.push('A')
        self.assertEqual(2, self.stack.size())

        self.stack.push(True)
        self.assertEqual(3, self.stack.size())

        self.stack.push(None)
        self.assertEqual(4, self.stack.size())

    def tearDown(self) -> None:
        del self.stack