Python: Separate parentheses groups
Split Matched Parentheses Groups
Given a string consisting of whitespace and groups of matched parentheses, write a Python program to split it into groups of perfectly matched parentheses without any whitespace.
Input: ( ()) ((()()())) (()) () Output: ['(())', '((()()()))', '(())', '()'] Input: () (( ( )() ( )) ) ( ()) Output: ['()', '((()()()))', '(())']
Sample Solution:
Python Code:
# Define a function named 'test' that separates parentheses groups from a combined string
def test(combined):
# Initialize an empty list 'ls' to store separate parentheses groups
ls = []
# Initialize an empty string 's2' to build each parentheses group
s2 = ""
# Iterate through each character in the combined string (ignoring spaces)
for s in combined.replace(' ', ''):
# Append the character to 's2'
s2 += s
# Check if the count of "(" equals the count of ")"
if s2.count("(") == s2.count(")"):
# Append the current parentheses group to the list 'ls'
ls.append(s2)
# Reset 's2' for the next parentheses group
s2 = ""
# Return the list of separate parentheses groups
return ls
# Example 1
combined1 = '( ()) ((()()())) (()) ()'
print("Parentheses string:")
print(combined1)
print("Separate parentheses groups of the said string:")
print(test(combined1))
# Example 2
combined2 = '() (( ( )() ( )) ) ( ())'
print("\nParentheses string:")
print(combined2)
print("Separate parentheses groups of the said string:")
print(test(combined2))
Sample Output:
Parentheses string: ( ()) ((()()())) (()) () Separate parentheses groups of the said string: ['(())', '((()()()))', '(())', '()'] Parentheses string: () (( ( )() ( )) ) ( ()) Separate parentheses groups of the said string: ['()', '((()()()))', '(())']
Flowchart:
Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Find the closest palindrome.
Next: Find a palindrome of a given length containing a given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics