+ 2

Python Data Structures: Balanced Parentheses help

I am making a few different solutions for the last project in python data structures and this is one of them. It works for 6 out of the 7 tests, and I can’t understand why it doesn’t work on the last. Here is my code: def balanced(expression): out1 = 0 for i in expression: if i == '(': out1 +=1 elif i == ')': out1 -= 1 if out1 == 0: return True else: return False print(balanced(input()))

6th Oct 2021, 7:20 AM
Magnus4791
Magnus4791 - avatar
11 Answers
+ 2
There are several ways to take care of this issue. A simple way would be to return False if out1 is negative at any point. But if I remember correctly the task says you should use a stack.
6th Oct 2021, 7:36 AM
Simon Sauter
Simon Sauter - avatar
+ 2
I have found a different solution using a three strings which works. Thank you for your help.
6th Oct 2021, 10:03 AM
Magnus4791
Magnus4791 - avatar
+ 1
Your code only checks whether the number of opening and closing parentheses are the same. It does not check sequence. So for the following it shows True instead of false: )1 (
6th Oct 2021, 7:34 AM
Simon Sauter
Simon Sauter - avatar
+ 1
Aleksei Radchenkov I know. I wrote "Your code only checks ...". Which is the reason it doesn't pass the test case.
6th Oct 2021, 8:04 AM
Simon Sauter
Simon Sauter - avatar
+ 1
Simon Sauter, oh right, I misread your comment, sorry... 😉
6th Oct 2021, 8:06 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 1
No problem.
6th Oct 2021, 8:07 AM
Simon Sauter
Simon Sauter - avatar
+ 1
ubai no, not even close.
6th Oct 2021, 1:33 PM
Simon Sauter
Simon Sauter - avatar
0
Simon Sauter, actually it does check sequence (test 7), I have just solved it, and it does require to check if there is ')' but no '(' even if there are equal amount of them.
6th Oct 2021, 8:02 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
- 1
Magnus4791, So your code is very near. What you need to add, is to return False if "out" is negative at any point. Here is code that functions correctly(variable names are changed) : https://code.sololearn.com/cH15IFewR82T/?ref=app
6th Oct 2021, 8:04 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
- 2
balanced = lambda x :x =='(' or x == ')'
6th Oct 2021, 1:32 PM
ubai
ubai - avatar
- 2
balanced = lambda x :x =='(' or x == ')' This is your answer. 💯
8th Oct 2021, 5:15 AM
Shubham Bhatia
Shubham Bhatia - avatar