0

Help please with last test (hidden). Task "balanced parentheses" in course "Python data structures". 7th test is wrong(

Parentheses are balanced, if all opening parentheses have their corresponding closing parentheses. Given an expression as input, we need to find out whether the parentheses are balanced or not. For example, "(x+y)*(z-2*(6))" is balanced, while "7-(3(2*9))4) (1" is not balanced. The problem can be solved using a stack. Push each opening parenthesis to the stack and pop the last inserted opening parenthesis whenever a closing parenthesis is encountered. If the closing bracket does not correspond to the opening bracket, then stop and say that the brackets are not balanced. Also, after checking all the parentheses, we need to check the stack to be empty -- if it's not empty, then the parentheses are not balanced. Implement the balanced() function to return True if the parentheses in the given expression are balanced, and False if not. Sample Input: (a( ) eee) ) Sample Output: False Please, tell me what can be wrong? I tried take different tests, all valid. May be I don't see something?

14th Feb 2021, 1:43 PM
Андрей Львов
Андрей Львов - avatar
2 ответов
+ 1
Hi! For better help, I would advise you to put this code in the "coding" section { }, make it public, and link to it in this question
14th Feb 2021, 2:48 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
0
My code: class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items==[] def push(self, item): self.items.insert(0, item) def pop(self): return self.items.pop(0) def print_stack(self): print(self.items) def balanced(expression): #your code goes here st = Stack () for i in expression: if st.is_empty(): if i=='(': st.push(1) case=1 elif i==')': st.push(1) case=2 else: if (i=='(') and (case==1): st.push(1) elif (i==')') and (case==1): st.pop() elif (i==')') and (case==2): st.push(1) elif (i=='(') and (case==2):
14th Feb 2021, 1:44 PM
Андрей Львов
Андрей Львов - avatar