w3resource

Python: Separate parentheses groups

Python Programming Puzzles: Exercise-94 with Solution

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:

Flowchart: Python - Separate parentheses groups.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/puzzles/python-programming-puzzles-94.php