Python Balanced Parentheses Data Structures | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python Balanced Parentheses Data Structures

Hi, everyone. I am playing with the code in this exercise but it does not work for every case scenario. My code is this: def balanced(expression): lst = [] for i in expression: if i == '(' or i == '{' or i == '[': lst.append(i) elif i == ')' or i == '}' or i == ']': lst.pop(0) if len(lst) == 0: return True else: return False print(balanced(input())) What could be my error? Thanks in advance!

14th Feb 2021, 12:38 PM
Javier Muñoz
Javier Muñoz - avatar
6 Answers
+ 6
Because there could be an input wherein there is a closing bracket but no opening bracket before it. Example: INPUT: )Hello( And in first iteration, this will cause an error since the lst is still empty, i.e. no '(' or items to 'pop' . So if there is ')' but no '(' was found like in this example ")Hello(", it is automatically unbalanced therefore return False. TO SOLVE: ---> Check first if there are opening brackets in lst before removing a bracket. ---> If there is a ')' but no '(' before it, return False. Additional: The problem is just looking for brackets/parentheses, so you don't need those other types of brackets. https://code.sololearn.com/cW0z4pz669Kw/?ref=app
14th Feb 2021, 12:47 PM
noteve
noteve - avatar
+ 3
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.insert(0, item) def pop(self): return self.items.pop(0) s = Stack() inp = input() def balanced(inp): try: for i in inp: if i == str("("): s.push('(') elif i == str(")"): s.pop() else: continue if len(s.items) == 0: print(" True") else: print("False") except: print("False") balanced(inp)
25th Apr 2021, 2:19 AM
Thiriloganathan Manimohan
Thiriloganathan Manimohan - avatar
+ 1
Another point of view; lista = list() def balanced(expression): #your code goes here item = list(expression) for i in item: if i == '(': lista.insert(0, i) elif i == ')': if lista == []: return False else: lista.pop(0) if lista == []: return True else: return False print(balanced(input()))
29th Jul 2021, 6:50 PM
Rodrigo Silva
Rodrigo Silva - avatar
+ 1
Hello , every one . Please i am having troubles with the exercise the the code keep giving me the same feedback that my expression is not defined For i in expression : It keeps telling me everytime that the term expression is not defined in this line
25th Sep 2022, 8:35 AM
Hassan Yezir
0
Oh, so I just missed the condition to find out if the first parentheses was an opening one. Thank you!!!
14th Feb 2021, 6:59 PM
Javier Muñoz
Javier Muñoz - avatar
0
Javier Muñoz What your solution?
29th Mar 2021, 6:52 PM
Joshua chola
Joshua chola - avatar