Bracket balance checker in Python Implement a feature for a text editor to find errors in the usage of brackets in the code.

Input: sorted(list(zip(a, b))

Output: False

Input: ([{}, {}])

Output: True

Here's my implementation in Python:

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        """Push item in stack."""
        self.items.append(item)

    def top(self):
        """Return top of the stack."""
        if self.items:
            return self.items[-1]
        raise Exception('Stack empty.')

    def pop(self):
        """Remove and return top of the stack."""
        if self.items:
            return self.items.pop()
        raise Exception('Stack empty.')

    def is_empty(self):
        """Return True if stack is empty."""
        return len(self.items) == 0

    def __len__(self):
        """Return stack length."""
        return len(self.items)

    def __str__(self):
        """Print stack."""
        print(list(reversed(self.items)))


def check_balance(code):
    """Return True if brackets are balanced, False otherwise."""
    valid = {']': '[', ')': '(', '}': '{'}
    lefts = Stack()
    for char in code:
        if char in '[({':
            lefts.push(char)
        if char in '])}' and lefts.is_empty():
            return False
        if char in '])}' and not lefts.is_empty():
            if lefts.top() != valid[char]:
                return False
            lefts.pop()
    if not lefts:
        return True
    return False


if __name__ == '__main__':
    print(check_balance('[(((((({{}}))))))]'))
    print(check_balance('print(list(reversed(self.items))'))
    print(check_balance(' print(list(reversed(self.items))[]'))
    print(check_balance('print(list(reversed(self.items)))'))
    print(check_balance('print(list[(]reversed(self.items))'))
    print(check_balance('print(list(reversed(self.items[0)]))'))
    print(check_balance('print(list(reversed(self.items[7])))'))
Looks pretty good.

A couple comments:

Unless this is an assignment to make or use a Stack, a Python list would suffice.

The code checks if a char is in '[{(', then checks if it is in ']})' and the stack is empty, then checks if it is in ']})' (again) and checks if the top of the stack is the matching bracket. All characters go through all those checks.

In general, it is good to make the common case fast and less cases can be slower.

def check_balance(code):
    """Return True if brackets are balanced, False otherwise.
    """

    valid = {']': '[', ')': '(', '}': '{'}

    lefts = []

    for char in code:
        # common case
        if char not in '[](){}':
            continue

        if char in '[({':
            lefts.append(char)

        elif not lefts or lefts.pop() != valid[char]:
            return False

    return lefts == []