Balanced Brackets
You are given an expression string
S which contains expressions that made of bracket characters {, }, (, ), [, ]. Each expression in string is separated by space.Two brackets considered to be a matched pair if an opening bracket (i.e., (, [, or {) occurs to left of a closing bracket (i.e., ), ], or }) of exact same type. There are 3 types of matched pairs of brackets: [], {}, and ().
Write a program to examine whether each expression in
The first line contains a string
Each line of the output represents the status of each bracket expression in input string.
Given
S = {()} ({}.The first expression
{()} is balanced, so its output is YES. The second expression ({}} is unbalanced, so its output is NO.
Sample Input 1
{()} ({}
Sample Output 1
YES
NO
Sample Input 2
{}[] [({})] {}
Sample Output 2
YES
YES
YES
open_list = ["[","{","("]
close_list = ["]","}",")"]
def Convert(string):
li = list(string.split(" "))
return li
def balanced_parenthesis(str):
stack = []
for i in j:
if i in open_list:
stack.append(i)
elif i in close_list:
pos = close_list.index(i)
if ((len(stack) > 0) and
(open_list[pos] == stack[len(stack)-1])):
stack.pop()
else:
return ("No")
if len(stack) == 0:
return ("Yes")
else:
return ("No")
n = int(input("Enter number of strings : "))
s = input();
a = (Convert(s))
for j in a:
print(j,"-", balanced_parenthesis(j))
Comments
Leave a comment