I have got the right output for three test cases but not for the rest what's the problem in the code! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

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

15th Apr 2021, 5:58 PM
Khushboo Golampalle
Khushboo Golampalle - avatar
2 Answers
0
# Hi! Is it possible to make a more simple solution; can this one help you? (You still need to modify it to fit your needs, of course.) s = input() b = 0 for i in s: if i == "(": b += 1 elif i == ")": b -= 1 if b < 0: msg_balance = "not" break else: msg_balance = "not" if b else "" print(msg_balance, "balanced") # Why or why not? https://code.sololearn.com/cpuSHXo64jsS/?ref=app
15th Apr 2021, 8:41 PM
Per Bratthammar
Per Bratthammar - avatar
0
if pairs(stack[-1],exp[i]or len(stack)!=0): I think you've messed up your brackets here. You're passing `exp[i] or len(stack)!=0` as the second argument to your pairs() function. There's a bunch of other formatting issues there. Can you link to the code?
15th Apr 2021, 10:44 PM
Myk Dowling
Myk Dowling - avatar