The Python syntax requires all parentheses to be balanced. This means that each parenthesis that is opened in the source code must be closed further downstream, and that every closed parenthesis must have been opened upstream. Unbalanced parentheses result in a compiler error. The figure below shows the corresponding parentheses in the balanced code snippet (()(()(()))()(()())).
Write a program that can decide whether or not the parentheses in a given text fragment are balanced.
The first line of the input contains a number $$t \in \mathbb{N}$$. This is followed by another $$t$$ lines, each containing a text fragment. You may assume that each text fragment only contains a single type of parentheses. The types of parentheses that should be taken into account are ( and ), { and }, < and > and [ and ].
For each text fragment from the input, generate a line of output containing the term balanced if the parenthesis in fragment are balanced, or the term unbalanced if the parenthesis are not balanced.
If a given text fragment only contains a single type of parentheses, the following algorithm can be used to determine whether or not these parentheses are balanced:
initialize a counter to the value 0
traverse the characters of the text fragment left to right, and
increment the counter by one if the character is an opening parenthesis
decrement the counter by one if the character is a closing parenthesis; if this results in a negative counter, it means that there are more closing than opening parentheses at this point in the text fragment (which is illigal)
if the counter is not equal to zero after the traversal, it means that there is an unequal number of opening and closing parentheses (which is illigal)
Input:
4
(()()(()))
[[[[[ ]]]]
one (two (three) four) five
)(
Output:
balanced
unbalanced
balanced
unbalanced