100 XP

26. Balanced brackets

Advanced stacks strings

Write a function balanced(text) that takes a string and returns True if its brackets are balanced, or False if they aren't. There are three kinds of brackets, each with an opening and a closing one: ( ), [ ] and { }.

The brackets are balanced when:

  • every opening bracket is closed later by a closing bracket of the same kind;
  • every closing bracket closes an opening bracket that came before it, so }{ is not balanced;
  • brackets close in the reverse order they were opened, so pairs sit inside each other and never cross: {[]} is balanced, but {[}] is not.

Every other character is ignored. A string with no brackets, including the empty string, is balanced.

Example 1

Inputtext = "(a[b]{c})"
OutputTrue
Explanation[b] and {c} sit inside ( ), closed last.

Example 2

Inputtext = "(]"
OutputFalse
Explanation( is closed by ], the wrong kind.

Example 3

Inputtext = "(("
OutputFalse
ExplanationNeither ( is ever closed.

Constraints

  • text has 0 to 100 characters, which can be anything.

Submit also runs 6 more tests you can't see.

Code
def balanced(text):
    """Check that the brackets (), [] and {} are balanced.

    text: str, any characters; may be empty
    Returns: bool, True if every bracket is closed by its
        partner in the right order, else False
    """
    # Write your code here
    pass