26. Balanced brackets
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
text = "(a[b]{c})"TrueExample 2
text = "(]"FalseExample 3
text = "(("FalseConstraints
texthas 0 to 100 characters, which can be anything.
Submit also runs 6 more tests you can't see.
- Counting isn't enough:
)(has one of each and isn't balanced, and neither is([)]. The order matters. - Use a list as a stack:
appendeach opening bracket. A closing bracket must match the most recent bracket still open,stack[-1], and then removes it withstack.pop(). - On a closing bracket, return
Falseif the stack is empty or the popped bracket isn't its partner; a dict such as{")": "(", "]": "[", "}": "{"}gives the partner. After the loop, returnTrueonly if the stack is empty, or a bracket was never closed.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.