Data structures · 6 / 15 Exercise Medium

Balanced brackets

Objective

Create a Python program that checks whether the parentheses, square brackets and curly braces of a text are correctly matched. It is the classic example of using a stack.

Instructions

  • Read an integer n and then n lines of text, all non-empty. The text may contain any character, but only (), [] and {} matter.
  • A text is balanced if every closing symbol matches the last opening symbol still open of the same kind and none is left unclosed at the end.
  • For each line show Balanced or Not balanced.
Input
4
(a + b) * [c - {d}]
(]
((x)
f(g[1]) + {h: 2}
Output
Balanced
Not balanced
Not balanced
Balanced

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise