#48 · Stacks and queues · Beginner · 45 XP · about 8 min
Code editors check this on every keystroke. Write is_balanced(text) that returns True when the round (), square [] and curly {} brackets in text are balanced, and False otherwise.
Balanced means every closing bracket matches the most recent opening bracket that is still open, and nothing is left open at the end. Every other character is ignored.
is_balanced("{[()()]}") # returns True is_balanced("([)]") # returns False is_balanced("print(len([1, 2, 3]))") # returns True is_balanced("((") # returns False
In "([)]" the ] arrives while the ( is still open, so the brackets close in the wrong order.
A string with no brackets at all, including the empty string, is balanced.
Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.