I have got the right output for three test cases but not for the rest what's the problem in the code!
Parentheses are balanced, if all opening parentheses have their corresponding closing parentheses. Given an expression as input, we need to find out whether the parentheses are balanced or not. For example, "(x+y)*(z-2*(6))" is balanced, while "7-(3(2*9))4) (1" is not balanced. The problem can be solved using a stack. def pairs(open,close): if open=='('and close==')': return True if open=='{'and close=='}': return True if open=='['and close==']': return True return False def balanced(exp): stack = [] for i in range (len(exp)): if exp[i]=='('or exp[i]=='{'or exp[i]=='[': stack.append(exp[i]) elif exp[i]==')'or exp[i]=='}'or exp[i]==']': if pairs(stack[-1],exp[i]or len(stack)!=0): stack.pop() else: return False if len(stack)==0: return True else: False exp = input(" ") print(balanced(exp))