bracket_push.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
PAIRS = dict(("{}", "()", "[]"))
OPENERS = PAIRS.keys()
CLOSERS = PAIRS.values()


def check_brackets(brackets):
    stack = []
    for char in brackets:
        if char in OPENERS:
            stack.append(char)
        elif char in CLOSERS:
            # Too many closers, or closer doesn't match expected
            if not stack or PAIRS[stack.pop()] != char:
                return False

    # Stack should be empty at the end
    return not stack

Comments

Very cool. I like the variable names. Also, I didn't know about

1
dict(("{}", "()", "[]"))
cds-amal commented 25 May 2016 at 00:47 UTC

You're not logged in right now. Please login via GitHub to comment