0
Python data structure project #4 balanced parentheses
https://code.sololearn.com/cIofz73jyVJd/?ref=app Please help me to find an error. Most test cases are fine but it doesn’t work for a few test cases and I don’t know why.
8 Respuestas
+ 6
This project prompts you to use a stack.
The standard "list" data structure can act like a stack.
The append method puts an element at the end (on top of the stack).
The pop method removes the last element (again, the top of the stack).
If the list is empty, pop will cause an error. You can also take advantage of this, and use error handling to detect a wrong usage of parentheses.
In the following code it doesn't really matter what you put on the stack, just a marker element that means a new level of parentheses has been opened. I used 1 here.
Algorithm:
- loop through all characters
- opening parenthesis: put 1 on the stack
- closing parenthesis: pop the last element. If there is an error, the sample was flawed.
- at the end the stack must be empty, this marks a balanced result.
def balanced(expression):
stack = []
for c in expression:
if c == '(':
stack.append(1)
elif c == ')':
try:
stack.pop()
except:
return False
return len(stack) == 0
+ 2
almost the same as Tibor Santa ‘s answer
if you add new item at the front of stack
def balanced(expression):
#your code goes here
stack = []
for c in expression:
if c == '(':
stack.insert(0, c)
elif c == ')':
if not stack or stack.pop(0) != '(':
return False
return len(stack) == 0
+ 1
Tibor Santa thank you!
0
try this
for i in a:
if i == '(':
list.append('(')
if list: ## check the list is not empty before trying to pop the ')'.
if i == ')':
list.pop()
edit, no, didn't work
0
rodwynnejones Thank you it helped for test case 7 but still it doesnt work for test case 3.. it is hidden test case so I dont know why
0
Might be better off doing it all in a function and check if the a[0] is a ')' or a[-1} is a '(' so you can return "false" early, then do the append and pop routine if needed.
0
I just passed all test cases by doing this but im pretty sure way more simpler answer exists
a = input()
list = []
count = 0
for i in a:
if i == '(':
list.append('(')
count +=1
if i == ')':
if list == []:
count +=1
if list !=[]:
list.pop()
count -=1
if list == [] and count==0:
print("True")
if list != [] or count !=0:
print("False")
0
Ok bro