0

Why it is not accepting my code for all test cases in python data structure

My Code class balancing: def __init__(self, item): self.item = item self.items = [] self.itms = [] def push(self, l,s): l.append(s) def pop(self, l, s): l.remove(s) def balancer(self): for i in self.item: if i == '(': self.push(self.items, '(') if i == ')': self.push(self.itms, ')') #print((self.items)) # print(self.itms) if len(self.items) == len(self.itms): print('True') else : print('False') user = input('') paran = balancing(user) paran.balancer() #Help

11th Mar 2021, 5:12 PM
Uzair Asif
Uzair Asif - avatar
1 ответ
+ 2
If you mean about the balanced parentheses exercise, then ur code is wrong on inputs like ")foo(", i.e ur code only checks the times they have occured but not the order of them. What u need to do is keep only one stack (not two), pushing a token when u find "(" and popping when u find ")". To avoid the scenario of popping from an empty stack, push "*" at the start and check for that, or use try/except. Another way to solve it without a stack is to keep a running depth counter, +1 on "(", -1 on ")" and few extra checks
11th Mar 2021, 5:33 PM
Giorgos