Esempio n. 1
0
    def is_valid(string: str) -> bool:
        """
        Premise for this operation is that if the opening bracket matches the closing bracket next to it, remove from the stack
        If the stack isn't empty after iterating through the whole process, it's invalid.
        :type string: str
        :rtype: bool
        """
        stack = Stack()
        opens = ['{', '[', '(']
        closes = ['}', ']', ')']
        matches = {'[': ']', '{': '}', '(': ')'}

        if len(string) == 0:
            return False

        for bracket in string:
            if bracket in opens:
                stack.push(bracket)

            if bracket in closes:
                x = stack.top()
                y = matches[stack.top()]
                if bracket == matches[stack.top()]:
                    stack.pop()
                else:
                    # i.e. ( ] is invalid always
                    return False

        if stack.length() == 0:
            return True
        else:
            return False
from structs import Stack

stack = Stack()
stack.push(12)
stack.push(13)

print(stack.pop())
print(stack.peek())
print(stack.top)
print(stack.peek())
print(stack.isEmpty())