Write a Python program for checking parenthesis balance

In this program, we are going to learn the parenthesis balance program that means whether a given set of parenthesis is balanced or not if balanced then return TRUE otherwise return FALSE. So let’s start learning how to check parentheses are balanced or not in Python.

How to check parentheses are balanced or not in Python

we are going to consider a count variable which will be increased in case of opening parenthesis and decreases in case of the closing parenthesis. now we are going to implement the function parenthesis _checker to check the parenthesis balanced or not.

now move on the program:

1st implement the function parenthesis _checker() with count variable :

# Function to checked paranthesis balance
def parenthesis_checker(str):
  #count variable initialization   
  count = 0

implement the logic for parenthesis checking :

for i in str:
  if i == "(":
    #increment of count variable if opening parenthesis is found  
    count += 1
  elif i == ")":
    #decrement of count variable if opening parenthesis is found
    count -= 1
  if count < 0:
     return False
return count == 0

At last, take a set of parenthesis  as input and call the function:

#take  set of parenthesis as a input variable
x=input("")
print(parenthesis_checker(x))

now combine the whole program:

# Function to checked paranthesis balance
def parenthesis_checker(str):
  #count variable initialization   
  count = 0
  for i in str:
    if i == "(":
      #increment of count variable if opening parenthesis is found  
      count += 1
    elif i == ")":
      #decrement of count variable if opening parenthesis is found
      count -= 1
    if count < 0:
       return False
  return count == 0
#take  set of parenthesis as a input variable
x=input("")
print(parenthesis_checker(x))

Output:

(()()0)
True

Output:

()(
False

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *