In: Computer Science
Code:
def checkParentheses(input_string): #checkParentheses function which accepts input_string
open_par_list = ["(","[","{"]
close_par_list = [")","]","}"]
stack = [] #declare stack list which holds the open parentheses
values
for i in input_string: #for each character in given
input_string
if i in open_par_list: #if the input_character is '('
stack.append(i) #append it to stack
elif i in close_par_list: #if the input_character is ')'
index = close_par_list.index(i)
if ((len(stack) > 0) and
(stack[len(stack)-1])==open_par_list[index]):
#check if the len(stack)>0 and last value in stack is equal to
'(' or not
stack.pop()
else: #in other case return unbalanced
return "Unbalanced"
if len(stack) == 0: #if stack length is 0 that means the input is
balanced
return "Balanced" #so return balanaced
input_expression=input("Enter the test parentheses string: ") #asking user to enter the input parentheses
print ("The given input" + input_expression + " is "+ checkParentheses(input_expression)) #call checkParentheses() function
Code and Output Screenshots:
Note: if you have any queries please post a comment thanks a lot..always available to help you..