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.