0

Balanced Parentheses Not working

I have this code in a problem called balanced parentheses. The goal of the problem is to find balanced parentheses. For instance "(x+y)*(z-2*(6))" is balanced and "7-(3(2*9))4) (1" is not. I am passing 6 test cases but I can't pass the last one. Can you help me by solving the problem? Thanks in advance `class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def balanced(expression): a = Stack() for i in expression: if i == "(": a.push(i) for i in expression: if i == ")": if a.size() == 0: return False else: a.pop() if a.size() == 0: return True else: return False print(balanced(input()))`

18th Jun 2021, 3:34 PM
Soumya Mahbub
Soumya Mahbub - avatar
9 Antworten
+ 3
I tested ")(". It should return False, but in you current code it returns True. I'm not sure but something like this could be the reason the test case fails?
18th Jun 2021, 4:07 PM
Lisa
Lisa - avatar
+ 2
Thanks i got it
18th Jun 2021, 4:10 PM
Soumya Mahbub
Soumya Mahbub - avatar
0
Hi, you have a lot of code in the description. Can you put it on playground and link it here?
18th Jun 2021, 3:40 PM
Lisa
Lisa - avatar
0
Sure I can but can you name one? Sorry i don't know any
18th Jun 2021, 3:43 PM
Soumya Mahbub
Soumya Mahbub - avatar
18th Jun 2021, 3:55 PM
Lisa
Lisa - avatar
0
https://code.sololearn.com/cA158A6a0a25
18th Jun 2021, 3:57 PM
Soumya Mahbub
Soumya Mahbub - avatar
0
I changed it and it works so if anyone needs it you can find it in the link
18th Jun 2021, 4:28 PM
Soumya Mahbub
Soumya Mahbub - avatar
0
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.insert(0, item) def pop(self): try: return self.items.pop(0) except: par.push(")") def is_empty(self): if self.items == []: return True else: return False prompt = input() par = Stack() for c in prompt: if c == "(": par.push("(") elif c == ")": par.pop() print(par.is_empty())
17th Jul 2021, 3:17 PM
Ale
Ale - avatar
0
my code that properly worked and passed all the cases: def Balanced(exp): i = exp.find (")") j = exp.find ("(") if i < 0 and j < 0: return True if i < 0 and j >= 0: return False if i >= 0 and j < 0: return False if i >= 0 and j >= 0: if i < j: return False else: s = list () counter_2 = 0 for c in exp: if c == "(": s.insert (0,"(") if c == ")": if len (s) > 0: s.pop(0) else: s.insert (0, ")") if len (s) == 0: return True if len (s) > 0: if s[0] == "(" or s[0] == ")": return False else: return True else: if s[0] == "(": return False print (Balanced) print (Balanced(input()))
11th Jul 2022, 10:38 PM
Hamed Saberi
Hamed Saberi - avatar