Balanced Parentheses Not working | Sololearn: Learn to code for FREE!

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()))`

6/18/2021 3:34:47 PM

Soumya Mahbub

8 Answers

New Answer

+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?

+2

Thanks i got it

0

Hi, you have a lot of code in the description. Can you put it on playground and link it here?

0

Sure I can but can you name one? Sorry i don't know any

0

I mean something like this: https://code.sololearn.com/cUK6Jt1b0wUQ/?ref=app

0

https://code.sololearn.com/cA158A6a0a25

0

I changed it and it works so if anyone needs it you can find it in the link

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())