Check for balanced parentheses in Python



Examples :

  Input:  {[] {()}}  Output:  Balanced  Input :  [{} {} (]  Output:  Unbalanced 

Approach # 1: Using the stack

One one approach for checking balanced parentheses is to use a stack.Every time open parentheses are encountered, push them onto the stack, and when closed parentheses are encountered, match them to the top of the stack and insert them. If the end of the stack is empty, return Balanced, otherwise, Unbalanced .

# Python3 code to check
# balanced parentheses in expression

open_list = [ " [" , " {" "(" ]

close_list = [ "]" , "}" , ")" ]

 
# Function for checking parentheses

def check (myStr):

stack = []

for i in myStr:

if i in open_list:

stack.append (i)

elif i in close_list:

pos = close_list.index (i)

  if (( len (stack) & gt;  0 ) and

(open_list [pos] = = stack [ len (stack) - 1 ])):

stack.pop ()

else :

return "Unbalanced"

if len (stack) = = 0 :

return "Balanced"

 
# Driver code

string = "{[] {()}}"

print (string, "-" , check (string))

 

string = "[{} {}) (]"

print (string, "-" , check (string))

Output:

 {[] {()}} - Balanced [{} {}) (] - Unbalanced 

Approach # 2 Using the queue

First match open parentheses with matching closing parentheses. Iterate over the specified expression using "i" if "i" — open brackets, add to queue if "i" — closing brackets, check if the queue is empty or "i" — top of the queue, if yes, return "Unbalanced", otherwise "Balanced".

# Python3 code to check
# balanced parentheses in expression

def check (expression):

 

open_tup = tuple ( ` ({[` )

  close_tup = tuple ( `)}]` )

map = dict ( zip (open_tup, close_tup))

queue = []

  

  for i in expression:

  if i in open_tup:

queue.append ( map [i])

elif i in close_tup:

if not queue or i! = queue.pop ():

return "Unbalanced"

return "Balanced"

 
# Driver code

string = "{[] {()}}"

print (string, "-" , check (string))

Exit od:

 {[] {()}} - Balanced 

Approach # 3: on based on liquidation
On each iterations, the innermost parentheses are removed (replaced with an empty string). If we get an empty string, our initial one will be balanced; otherwise not.

# Python3 code to check
# balanced brackets in expression

def check (my_string):

  brackets = [ `()` , `{}` , `[]` ]

while any (x in my_string for x in brackets):

for br in brackets:

my_string = my_string.replace (br,` `)

return not my_string

 
# Driver code

string = "{[] {()}}"

print (string, "-" , " Balanced " 

  if check (string) else "Unbalanced" )

Exit:

 {[] {()}} - Balanced