Balanced Parentheses Python DataStructures Project | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

Balanced Parentheses Python DataStructures Project

Project: Parentheses are balanced, if all opening parentheses have their corresponding closing parentheses. Someone please help! I'm stuck in this test. There are a total of seven test cases. Five of them are correct but two of them are not going well in any way. Can anyone explain what's wrong with my code? Here's my code: 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 stack(self): return self.items def balanced(expression): s = Stack() for i in expression: if i == '(': s.push(i) if i == ')': if s.stack()[0] == '(': s.pop() else: s.push(i) if not s.stack(): return True else: return False

6th Feb 2021, 10:33 AM
Ragib Al Asad
Ragib Al Asad - avatar
25 Answers
+ 15
You have to check if '(' or opening bracket is in the stack in every element, not just in the first element. If there is no '(' in stack, it will automatically become False because it means that ')' was found but there was no '(' that would pair it, i.e. not balance. If this is still unclear please feel free to ask. Thanks. https://code.sololearn.com/cWYv4qILZT90/?ref=app
6th Feb 2021, 10:46 AM
noteve
noteve - avatar
+ 18
class stack: def __init__(self): self.items = [] def push(self,item): self.items.insert(0,item) def pop(self): return self.items.pop(0) def __call__(self): return self.items def balanced(expression): # your code goes here x = stack() for char in expression: if char == '(': x.push(char) if char == ')': if '(' in x(): x.pop() else: return False if not x(): return True return False print(balanced(input()))
21st Jul 2021, 4:44 PM
Shermale Abhijit
Shermale Abhijit - avatar
+ 7
class stack: # defining the stack class def __init__(self): self.items = [] def is_empty(self): # returns true if self.items is empty return self.items == [] def push(self, item): # adds item to the stack self.items.insert(0, item) def pop(self): # removes item from the stack return self.items.pop(0) def __str__(self): # makes stack printable return "|%s|" %(' | '.join([f'"{item}"' for item in self.items])) def __call__(self): # makes stack callable as a function like a list return self.items # keep in mind that you can still implement all of the stack functionality without creating a class. def balanced(expression): # balanced function paren = stack() # initialize for char in expression: # iterate through expression to filter out parentheses if char == '(': paren.push(char) # push opening parenthesis to stack if char == ')': if '(' in paren(): paren.pop() # pop from stack if stack is not empty else: return False # return false if pop attempted on empty stack if not paren(): return True # return true if stack is empty return False # return false if an opening parenthesis is found if __name__ == "__main__": # the main function print(balanced(input())) this code worked for me. added comments for easy reading
6th Apr 2021, 4:32 PM
Pablo Kagioglu Jr.
Pablo Kagioglu Jr. - avatar
+ 6
This code work for all cases, pay attention to the indexerror exception def balanced(expression): #your code goes here bracket_stack = [] for char in expression: if char == "(": bracket_stack.insert(0, char) elif char == ")": try: bracket_stack.pop(0) except IndexError: return False return bracket_stack == [] print(balanced(input()))
14th Sep 2021, 3:43 AM
TrebleClef20
TrebleClef20 - avatar
+ 3
If input() == ')' : s.stack()[0] instruction will raise an IndexError: list index out of range. Since we only push the left parenthesis into the list, we just need to check whether there is a left parenthesis still in the items, when the right parenthesis appears.
1st Apr 2021, 7:47 PM
AIPO π
AIPO π - avatar
+ 2
#write exactly like this: def balanced(expression): #your code goes here s=[] for i in expression: if i not in "()": continue if i =='(': s.insert(0,i) else: if not s: return False else: s.pop(0) return not s print(balanced(input()))
15th Sep 2022, 6:09 AM
Mohammad Haghani Dogahe
Mohammad Haghani Dogahe - avatar
+ 1
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): self.items.pop(0) def print_stack(self): print(self.items) def balanced(expression): #your code goes here s = Stack() for i in expression: if i == "(": s.push("i") elif i ==")": if s.is_empty(): return False else: s.pop() return s.is_empty() print(balanced(input())) I tried to use only the functions from the Stack class. Hope it helps!
23rd Jul 2021, 2:32 PM
Arya Shetty
Arya Shetty - avatar
0
class stack: # defining the stack class def __init__(self): self.items = [] def push(self, item): # adds item to the stack self.items.insert(0, item) def pop(self): # removes item from the stack return self.items.pop(0) def __call__(self): # makes stack callable as a function like a list return self.items def balanced(expression): # balanced function paren = stack() # initialize for char in expression: # iterate through expression to filter out parentheses if char == '(': paren.push(char) # push opening parenthesis to stack if char == ')': if '(' in paren(): paren.pop() # pop from stack if stack is not empty else: return False # return false if pop attempted on empty stack if not paren(): return True # return true if stack is empty return False # return false if an opening parenthesis is found print(balanced(input()))
2nd Jul 2021, 2:43 PM
Shanmuga Priya
Shanmuga Priya - avatar
0
def balanced(expression): result = None stack = [] try: for x in expression: if x == "(": stack.insert(0,x) elif x == ")": stack.pop(0) except IndexError: result = False else: if len(stack) == 0: result = True else: result = False return result print(balanced(input()) Hope it helps someone? :)
20th Jul 2021, 10:40 AM
Kaine Bruce
Kaine Bruce - avatar
0
This one is tricky.
2nd Sep 2021, 11:08 PM
Andrea Vaghi
Andrea Vaghi - avatar
0
def balanced(expression): #your code goes here item = [] for i in expression: if i == '(': item.insert(0,i) if i == ')': if '(' in item: item.pop() else: return False return not item print(balanced(input()))
4th Sep 2021, 9:18 AM
P K Mohan
P K Mohan - avatar
0
def balanced(expression): if expression.count('(')==expression.count(')'): print('True') else: print('False') balanced(input()) SHALL WE CAN USE THIS CODE???
27th Sep 2021, 11:37 AM
Sugand
0
it can be solved just by using the normal list as suggested in the hint: def balanced(expression): #your code goes here list = [] for i in expression: if(i == "(" ): list.insert(0,i) if(i == ")"): if "(" in list: list.pop(0) else: list.insert(0,i) if(len(list)!=0): return("False") else: return("True") print(balanced(input()))
16th Mar 2022, 2:32 PM
Karan Modi
Karan Modi - avatar
0
def balanced (expression): if balanced: return("True") else: return("False") print(balanced(input())) *this is correct only for Test Case #1 and #4
25th Dec 2022, 8:07 AM
Kirat Kungkra Narzary
Kirat Kungkra Narzary - avatar
0
def balanced(expression): lists=[] p=0 for i in expression : if i == "(" : lists.insert(0, i) elif i == ")" and lists!=[] : lists.pop(0) elif i == ")" and lists==[] : p+=1 return lists==[] and p==0 print(balanced(input()))
5th May 2023, 9:17 AM
Pouria Ebneali
0
def balanced (expression): s = [] for el in expression: if el == "(": s.insert(0, el) if el == ")": if "(" in s: s.pop() else: return False if s: return False else: return True print(balanced(input()))
14th May 2023, 8:08 AM
Paul-Henry Paltmann
Paul-Henry Paltmann - avatar
- 1
def balanced(expression): #your code goes here item = [] for i in expression: if i == '(': item.insert(0,i) if i == ')': if '(' in item: item.pop() else: return False if item: return False else: return True print(balanced(input()))
31st Jul 2021, 2:14 PM
David labadze
David labadze - avatar
- 1
Here is my code , This satisfies 6 out of 7 cases but fail in seventh test case, What is the issue?? Help class stack: def __init__(self): self.items = [] # creating a list def is_empty(self): return self.items == [] # creating a function to check whether the stack is empty def push(self, item): self.items.insert(0, item) # pushing an item to the top of the stack def pop(self): self.items.pop(0) # popping the item from the top of the stack def print_stack(self): print(self.items) def balanced(expression): op_para = stack() # creating a stack to keep opening paranthesis k = False for items in expression: if items == "(": op_para.push("(") for i in expression: if i == ")": k = True if op_para.is_empty() and not k: return True for items in expression: if not op_para.is_empty(): if items == ")": op_para.pop() elif items == ")": return False if op_para.is_empty(): return True else: return False print(balanced(input()))
7th Aug 2021, 10:51 AM
Udara Nilupul
Udara Nilupul - avatar
- 1
SO MY Answer is def balanced(expression): #your code goes here bracket_stack = [] for char in expression: if char == "(": bracket_stack.insert(0, char) elif char == ")": try: bracket_stack.pop(0) except IndexError: return False return bracket_stack == [] print(balanced(input()))
14th Nov 2021, 10:06 AM
Muhammad Taqi
Muhammad Taqi - avatar
- 1
class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self,items): self.items.insert(0,items) def pop(self): return self.items.pop(0) def array(self): return self.items def balanced(expression): s = Stack() for x in expression: if x == '(': s.push(x) if x == ')': if '(' in s.array(): s.pop() else: return False # array must be [] (harus kosong arraynya) if s.array()== []: return True else: return False print(balanced(input("Masukan expresi => ")))
3rd Mar 2022, 1:30 AM
achmad mustafa
achmad mustafa - avatar