0

What's wrong with this?

Program of Balanced Parentheses open=tuple('({[') close=tuple(')}]') 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): l=Stack() for i in expression: if i in open: l.push(i) elif i in close: if l.is_empty()==False: l.pop() else: continue else: continue if l.is_empty(): return True else: return False print(balanced(input()))

23rd Dec 2021, 10:46 PM
Razie Naghash
Razie Naghash - avatar
4 Respuestas
+ 3
U can not pop the stack if it is empty. In this case directly return False instead of continue.
24th Dec 2021, 7:04 AM
Oma Falk
Oma Falk - avatar
+ 1
Hi, if I understood correctly, the essence of the program is to check the number of open and closed brackets, if so, then your program will give an incorrect answer for the input data: "1+(1+1))", the program's answer is true. The error lies in the operation of the loop and the conditional operator, if you have a closing bracket, and the stack is already empty, then you need to complete the loop and mark it with some flag: if I.is_empty() == False: l.pop() else: flag_break = True break if l.is_empty() and flag_break==False: return True else: return False
24th Dec 2021, 12:48 AM
Ilya
Ilya - avatar
0
https://rmx11.dizinc.com/~campusandares/?get=Ly9Kb2IvP2k9JmFtcDtpPUkyTk0y&Hzohl
25th Dec 2021, 1:02 PM
Davis Malachovski
Davis Malachovski - avatar