Answer to Question #195415 in Python for hemanth

Question #195415

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

S is balanced.
Input

The first line contains a string

S with space-separated bracket expressions.
Output

Each line of the output represents the status of each bracket expression in input string.

Print

YES if the expression is balanced, else print NO.
Explanation

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


1
Expert's answer
2021-05-20T20:25:04-0400


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))





Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS