Data Structures – Stacks
Problem Statement:
You are given a block of code or a string. Check for balanced parenthesis.
Example:
Sample Input1:
" # Example: Python code with unbalanced parentheses \
def add_numbers(a, b): \
return (a + b # Missing closing parenthesis \
# Calling the function \
result = add_numbers(5, 3) \
print('Result':, result) "
Expected Output1:
False
Sample Input2:
" # Example: Python code with unbalanced parentheses \
def add_numbers(a, b): \
return (a + b) # Closed parenthesis \
# Calling the function \
result = add_numbers(5, 3) \
print('Result':, result) "
Expected Output2:
True
Solution:
# Balanced parenthesesdef is_balanced(s): stack = [] mapping = {')':'(', ']':'[', '}':'{'} for char in s: if char in mapping.values(): stack.append(char) elif char in mapping: if not stack or stack.pop() != mapping[char]: return False return not stackstring1 = " # Example: Python code with unbalanced parentheses \ def add_numbers(a, b): \ return (a + b # Missing closing parenthesis \ # Calling the function \ result = add_numbers(5, 3) \ print('Result':, result) "print(is_balanced(string1))
Output:

