Change language

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

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method