0

Balanced Parentheses

Someone can help me? I don't understand why this code doesn't run ok for all the inputs. Thaks!! 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 is_match(p1, p2): if p1 == "(" and p2 == ")": return True else: return False def balanced(expression): s = Stack() balanced = True index = 0 while index < len(expression) and balanced: paren = expression[index] if paren in "(": s.push(paren) else: if paren in ")": s.pop(paren) else: if s.is_empty(): balanced = False else: top = s.pop() if not is_match(top, paren): balanced = False index += 1 if s.is_empty and balanced: return True else: return False print(balanced(input()))

20th Oct 2022, 6:32 PM
Nicolas Parera
Nicolas Parera - avatar
3 ответов
+ 1
I think, logic is_match() function can never return True.. So it may causing loop stop. What is the need of it? Remove it and use s.pop() instead of s.pop(paren). it works then..
20th Oct 2022, 6:52 PM
Jayakrishna 🇮🇳
+ 1
Thank you for your answer! I delete the match function and use s.pop() but it doesn't work fine. For this input: (x+y)*(x-z)-9 the output is: False for this input: (x-8*(2*5+(2) the output is: True. The code now is like this: 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): s = Stack() balanced = True index = 0 while index < len(expression) and balanced: paren = expression[index] if paren in "(": s.push(paren) else: if paren in ")": s.pop() else: if s.is_empty(): balanced = False index += 1 if s.is_empty and balanced: return True else: return False print(balanced(input()))
21st Oct 2022, 10:10 AM
Nicolas Parera
Nicolas Parera - avatar
+ 1
In first case : when it read '*' then it is not "(", or ")" So else part s.is_empty() makes balanced= false. Loop In second case wong because of : in last if condition you are using s.is_empty instead of s.is_empty() , paranthesis missing... Check is empty before poping item.. May it need some more modification, hope you can find it.. .
21st Oct 2022, 11:06 AM
Jayakrishna 🇮🇳