Balanced Brackets in Python

Here is the a solution to the balanced brackets problem but done in python.  I would appreciate any python experts input on how to do this more concise or elegant.  Cheers!!

def isBalanced(strI
"""Validate if an input string is having balanced bracket pair
return def isBalanced(strInput):
def isBalanced(strInput):
    """Validate if an input string is having balanced bracket pairs
    this includes bracket ordering. i.e a round bracket must be closed
    by a round bracket.  Emtpy strings are treated as balanced."""
    if strInput:
        # list of all bracket kinds, in paired tuples
        brackets = [ ('(',')'), ('[',']'), ('{','}')]
        # define fake constants - python does not support the concept of constants
        kStart = 0
        kEnd = 1

        # internal stack used to push and pop brakets in the input string
        stack = []

        for char in strInput:
            for bracketPair in brackets:
                if char == bracketPair[kStart]:
                elif char == bracketPair[kEnd] and len(stack) > 0 and stack.pop() != bracketPair[kStart]:
                    return False

        if len(stack) == 0:
            return True

    return False
This entry was posted in Development and tagged . Bookmark the permalink.

5 Responses to Balanced Brackets in Python

  1. Mohan Gulati says:

    One optimization that I see is that I could put a break statement after I append the char to the stack. This would make a nominal performance improvement.

  2. Roland Steiner says:

    what about “Test]”?

    BTW, hi from Tokyo! How is Life actually in Vancouver? It seemed a great city when I visited there (much more interesting than Seattle, that’s for sure!).


    ^_^ Roland

  3. Yep there’s a slight mistake here, things that end in a single bracket will not be caught e.g. “test)”

    The elif statement should say:
    elif char == bracketPair[kEnd] and ( len(stack) == 0 OR stack.pop() != bracketPair[kStart]):
    return FALSE

  4. biff says:

    Worded great, thank you for posting!

  5. Dipak Kumar Singh says:

    failed for – [(){}]]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s