This program checks if a given string of parentheses is balanced. A balanced string of parentheses means that each opening symbol has a corresponding closing symbol and the pairs of parentheses are properly nested.

Program Structure

The program uses a stack data structure to track open parentheses as they occur in the string. For each closing parenthesis encountered, the program checks if there is a corresponding opening parenthesis by popping the stack. If the stack is empty at the end of processing, the string is balanced; otherwise, it is not.

Python Code

def is_balanced(s):
    stack = []
    for char in s:
        if char == '(':
            stack.append(char)
        elif char == ')':
            if not stack:
                return False
            stack.pop()
    return not stack

# Example Usage
input_string = "()()()"
print(f"Is the string '{{input_string}}' balanced? {is_balanced(input_string)}")

Explanation of the Code

  • is_balanced function: Takes a string as input and initializes an empty stack. It iterates over each character in the string.
  • Opening parentheses: Are pushed onto the stack.
  • Closing parentheses: Trigger a check if the stack is empty. If the stack is empty, it means there is no matching opening parenthesis, so the function returns False. If the stack is not empty, the top element (opening parenthesis) is popped.
  • End of processing: If the stack is empty, all opening parentheses had matching closing ones, and the string is balanced. If the stack is not empty, then there are unmatched opening parentheses, and the string is not balanced.

Usage

This function can be used in a program where balanced parentheses are critical, such as in compilers or during equation validation in mathematical expressions.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)