Answer to Question #216757 in Python for srikanth

Question #216757
Balanced Brackets

You are given an expression string S which contains expressions that are made of bracket characters {, }, (, ), [, ]. Each expression in the string is separated by space.
Two brackets are considered to be a matched pair if an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and ().
A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. For example, 
{[(])} is not balanced because the contents in between { and } are not balanced. The pair of square brackets enclose a single, unbalanced opening bracket, (, and the pair of brackets enclose a single, unbalanced closing square bracket, ].
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.
Sample Input 1
{()} ({}
Sample Output 1
YES
NO
Sample Input 2
{}[] [({})] {}
Sample Output 2
YES
YES
YES
1
Expert's answer
2021-07-13T04:30:35-0400
#Paranthesis balancing

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")
  
  
s = input("Enter of strings : ");
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