Wednesday, July 12, 2017

Python code: Calculating stack of balanced brackets in a string

Hi

I am solving the problem of a string of brackets, to detect if the string of brackets are matching and balanced. e.g. a string like following:


[]][{]{(({{)[})(}[[))}{}){[{]}{})()[{}]{{]]]){{}){({(}](({[{[{)]{)}}}({[)}}([{{]]({{
or 
(}{(()[][[){{}{{[}][]{{{{[{{[](}{)}](}}()]}(}(}}]}[](]]){{{()}({[[}}{{[]}(]}{(]{}}[()(}]{[[]{){{

I felt this is something fun and challenging to do. if you have good and creative answers, or detecting my code is buggy for some cases please keep me posted. Thanks!

def is_matched(expression):
    DictBracket = {"{":"}", "[":"]", "(":")"}
    OpenBracket = []
    for counter, char in iter(enumerate(expression)):
        if char in DictBracket.keys():
            OpenBracket.append(char)
        else:
            if counter == 0 and char not in DictBracket.keys():
                return False            
            if counter > 0 and char in DictBracket.values():
                if len(OpenBracket) and DictBracket[OpenBracket.pop()] in char:
                    continue                
            else:
                    return False    
     return len(OpenBracket) == 0
expression = input().strip()
if is_matched(expression) == True:
 print("YES")
else:
 print("NO")

No comments: