0

Balanced Parantheses - Python Data Strcutures

Hi, My code is failing Test Case #3 and Test Case #7, can someone help why? I have tried a lot but can't seem to figure out what's going wrong. Any help will be highly appreciated. 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 x=Stack() for i in expression: if i=='(': x.push(i) elif i==')': x.pop() return x.is_empty() print(balanced(input()))

25th Jun 2021, 11:13 PM
Viraj Kumbhakarna
Viraj Kumbhakarna - avatar
4 Respostas
+ 2
# simple fix: def balanced(expression): #your code goes here x=Stack() for i in expression: 7 if i=='(': x.push(i) elif i==')': if x.is_empty(): return False else: x.pop() return x.is_empty()
25th Jun 2021, 11:28 PM
visph
visph - avatar
25th Jun 2021, 11:16 PM
visph
visph - avatar
0
your code throw error if stack is empty and closing parenthesis is encountered (try to pop empty items list ^^)
25th Jun 2021, 11:20 PM
visph
visph - avatar
26th Sep 2022, 12:41 PM
Joe Davies
Joe Davies - avatar