In [3]:
from pythonds9.basic.stack import Stack
In [4]:
def matches(_open, close):
    openers = "([{<"
    closers = ")]}>"
    return openers.index(_open) == closers.index(close)
In [5]:
def par_checker(symbol_string):
    s = Stack()
    balanced = True
    index = 0
    
    while index < len(symbol_string) and balanced:
        symbol = symbol_string[index]
        
        if symbol in "([{<":
            s.push(symbol)
        else:  # we have a ")"
            if s.is_empty():
                # There is no left parens in the stack to match this right one
                balanced = False
            else:
                # Pop out a right parens to reduce stack size
                top = s.pop()
                print(s.items, top, symbol)
                if not matches(top, symbol):
                    balanced = False
                
        index += 1
        
    return balanced and s.is_empty()
In [6]:
s = '{{([][])}()}'
par_checker(s)
['{', '{', '('] [ ]
['{', '{', '('] [ ]
['{', '{'] ( )
['{'] { }
['{'] ( )
[] { }
Out[6]:
True
In [7]:
s = '[{()]'
par_checker(s)
['[', '{'] ( )
['['] { ]
Out[7]:
False