Balanced parenthesis | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Balanced parenthesis

Why it is wrong?This code is failing in test 3... code is: def balanced(expression): list=[] for item in expression: if item=="(" or item==")": if item=="(": list.insert(0,item) if "("in list and item==")": list.pop(0) if list==[]: return True else: return False print(balanced(input()))

15th Apr 2021, 12:51 AM
Hrushikesha U N
Hrushikesha U N - avatar
6 Answers
+ 5
Hadise, the following is a bit simpler and based on the observation that the stack of only "(" characters is nothing but a glorified counter. def balanced(expression): count = 0 for char in expression: if char == "(": count += 1 elif char == ")": if count == 0: return False count -= 1 return count == 0 print(balanced(input()))
13th May 2021, 2:38 PM
Josh Greig
Josh Greig - avatar
+ 5
Well, I wrote this code and it was correct😉 def balanced(expression): x=[] for letter in expression: if letter == "(": x.insert(0,letter) if letter ==")": if x != []: x.pop(0) elif x==[]: return False if x==[]: return True else: return False print(balanced(input()))
12th May 2021, 8:24 PM
Hadise Rahdar
Hadise Rahdar - avatar
+ 2
) That isn't balanced but your code will incorrectly say it is. I don't know what test case 3 is but you should fix the above problem and see if your tests pass.
15th Apr 2021, 3:17 AM
Josh Greig
Josh Greig - avatar
+ 2
Oop, I must have accidentally deleted my post, but ya pretty much same as what Josh Greig said anyway.
15th Apr 2021, 4:10 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Good job Josh Greig😀 Yeah, Your code is simpler than mine.😁 Thanks for your good suggestion.💫
13th May 2021, 2:52 PM
Hadise Rahdar
Hadise Rahdar - avatar
+ 1
Have you considered what will happen if there are more ")"s than "("s?
15th Apr 2021, 8:44 AM
Myk Dowling
Myk Dowling - avatar