I've written code for Balanced Parenthesis, all work but Case 7. I can't see my error and would appreciate help. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I've written code for Balanced Parenthesis, all work but Case 7. I can't see my error and would appreciate help.

def balanced(expression): #your code goes here stack=[] count = expression.count(")") for i in expression: stack.insert(0,i) if i == "(": stack.pop() count-=1 if count > 0 or count < 0: return False else: return True print(balanced(input()))

17th Mar 2021, 10:12 AM
Olivia
Olivia - avatar
5 Answers
+ 1
If input is " ) ( " , output ? Should be false
17th Mar 2021, 10:18 AM
Jayakrishna 🇮🇳
+ 1
I Am AJ ! Not sure what you meant but you did help in reminding me the definition of the question. I should've just added parenthesis to the stack and not each char. It's solved now, thanks for trying.
17th Mar 2021, 4:20 PM
Olivia
Olivia - avatar
0
Yeah I just thought of that, trying to figure out how to fix it though...
17th Mar 2021, 10:23 AM
Olivia
Olivia - avatar
0
"""here is my code but my test case 7 is failing i guess its because i am not being able to handle for empty stack but when i fulfill that criteria many test cases arise as well """ open_parenthesis = ['(','{','['] close_parenthesis = [')','}',']'] stack = [] def balanced(expression): #--->(x+)*(z-2*(6)) #your code goes here o = 0 c = 0 for p in expression: if p in open_parenthesis: o += 1 elif p in close_parenthesis: c += 1 if o == c: return True else: return False print(balanced(input()))
23rd Nov 2021, 3:13 PM
Ankit Kumar Singh
- 1
Olivia You have to push ( in stack and on the basis of ( check if closing bracket ) match then remove ( from stack. You can try this https://code.sololearn.com/cmWTdRiciMhG/?ref=app
17th Mar 2021, 12:22 PM
A͢J
A͢J - avatar