Check for Balanced Parentheses in Python



In this article, we will solve the problem of checking balanced parentheses. Let's understand the problem statement, The following are the conditions for balanced parentheses ?

  • Every opening parenthesis has a corresponding closing parentheses.
  • Parentheses should be closed in the correct order.

For example, "{[()]}" is a balanced parenthesis. condiser the same example with different arrangment "{([})]" which is unbalanced parantheses.

Checking parentheses Using 'list' and 'for' loop

list is one of the built-in data types in Python. A Python list is a sequence of comma-separated items, enclosed in square brackets [ ]. The items in a Python list need not be of the same data type.

The for loop in Python provides the ability to loop over the items of any sequence, such as a list, tuple, or string. It performs the same action on each item of the sequence.

Algorithm

Following are the steps to check whether the parentheses are balanced or not using the list and for loop ?

  • Create one list for open parentheses and another list for closed parentheses.
  • Create an empty stack to track the open parentheses and iterate through the given string using a for loop.
  • If the iterated value is present in the open list, append it to the stack.
  • If the iterated value is present in the closed list, find its index value in the closed list.
  • If the length of the stack is greater than zero check if the index value of the open parentheses list is equal to the stack of elements at the position length of the stack - 1 then pop the stack otherwise, return Unbalanced.
  • After the loop, if the stack is empty, return "Balanced".
  • If the stack is not empty, return "Unbalanced".

Example

Following is an example to check whether parentheses are balanced or not using a list and for loop ?

open_list = ["[","{","("]
close_list = ["]","}",")"]
# Function to check 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"
    else:
        return "Unbalanced"
 
my_str1 = "{[]{()}}"
print(my_str1,"-", check(my_str1))
my_str2 = "{([}])]"
print(my_str2,"-",check(my_str2))

Following is the output of the above code ?

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

Checking parentheses Using 'dictionary'

In Python, a dictionary is a built-in data type that stores data in key-value pairs. It is an unordered, mutable, and indexed collection. Each key in a dictionary is unique and maps to a value.

A while loop in Python programming language repeatedly executes a target statement as long as the specified boolean expression is true. This loop starts with a while keyword followed by a boolean expression and colon symbol (:). Then, an indented block of statements starts.

Algorithm

Following are the steps to check whether parentheses are balanced or not using a dictionary ?

  • Create one tuple for open parentheses and another tuple for closed parentheses.
  • Zip the open and closed parentheses tuple into the dictionary using the zip function.
  • Create an empty stack to track the open parentheses and iterate through the given string using a while loop.
  • If the iterated value is present in the open tuple, append it to the stack.
  • Check if the stack is empty or if the character does not match the popped element of the stack (i.e., the last element in the stack). If either condition is true, return "Unbalanced".
  • After the loop, if the stack is empty, return "Balanced".
  • If the stack is not empty, return "Unbalanced".

Example

Following is an example to check whether parentheses are balanced or not using a dictionary and while loop ?

def check(expression):
   open_tup = tuple('({[')
   close_tup = tuple(')}]')
   map = dict(zip(open_tup, close_tup))
   stack = []  # Use a stack instead of "queue" for clarity
   
   for char in expression:  # Use a for loop for better readability
      if char in open_tup:
          stack.append(map[char])  # Push the corresponding closing bracket onto the stack
      elif char in close_tup:
         if not stack or char != stack.pop():  # Check if stack is empty or top doesn't match
            return "Unbalanced"   
   return "Balanced" if not stack else "Unbalanced"

# Driver code
my_str1 = "{[]{()}}"
print(my_str1, "-", check(my_str1))  # Expected output: Balanced
my_str2 = "((()"
print(my_str2, "-", check(my_str2))  # Expected output: Unbalanced

Following is the output of the above code ?

{[]{()}} - Balanced
((() - Unbalanced
Updated on: 2025-01-22T13:33:51+05:30

905 Views

Kickstart Your Career

Get certified by completing the course

Get Started