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

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically