+ 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()))
11 Respostas
+ 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.
+ 2
I have found a different solution using a three strings which works. Thank you for your help.
+ 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 (
+ 1
Aleksei Radchenkov I know. I wrote "Your code only checks ...". Which is the reason it doesn't pass the test case.
+ 1
Simon Sauter, oh right, I misread your comment, sorry... đ
+ 1
No problem.
+ 1
ubai no, not even close.
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.
- 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
- 2
balanced = lambda x :x =='(' or x == ')'
- 2
balanced = lambda x :x =='(' or x == ')'
This is your answer. đŻ