Python Balanced Parentheses Data Structures | Sololearn: Learn to code for FREE!


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!

2/14/2021 12:38:55 PM

Javier Muñoz

5 Answers

New Answer


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.


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)


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


Oh, so I just missed the condition to find out if the first parentheses was an opening one. Thank you!!!


Javier Muñoz What your solution?