w3resource

Python: Compute the depth of groups of matched nested parentheses separated by parentheses


Depth of Matched Parentheses Groups

Given a string consisting of groups of matched nested parentheses separated by parentheses, write a Python program to compute the depth of each group.

Input: (()) (()) () ((()()())) 

Output:
[2, 2, 1, 3]
Input: () (()) () () () ()

Output:
[1, 2, 1, 1, 1, 1]
Input: (((((((()))))))) () (()) ((()()()))

Output:
[8, 1, 2, 3]

Visual Presentation:

Python: Compute the depth of groups of matched nested parentheses separated by parentheses.

Sample Solution:

Python Code:

# License: https://bit.ly/3oLErEI

# Function to calculate the depth of groups of matched nested parentheses
def test(parens):
    # Split the input string into individual parentheses groups
    # and calculate the depth of each group
    return [len(s.split(')')[0]) for s in parens.split()]

# Test cases with different strings of parentheses
parentheses = '(()) (()) () ((()()())) '
print("Parentheses strings:", parentheses)
print("\nDepth of groups of matched nested parentheses separated by parentheses:")
print(test(parentheses))

parentheses = '() (()) () () () ()'
print("Parentheses strings:", parentheses)
print("\nDepth of groups of matched nested parentheses separated by parentheses:")
print(test(parentheses))

parentheses = '(((((((()))))))) () (()) ((()()()))'
print("Parentheses strings:", parentheses)
print("\nDepth of groups of matched nested parentheses separated by parentheses:")
print(test(parentheses))

Sample Output:

Parentheses strings: (()) (()) () ((()()())) 

Depth of groups of matched nested parentheses separated by parentheses:
[2, 2, 1, 3]
Parentheses strings: () (()) () () () ()

Depth of groups of matched nested parentheses separated by parentheses:
[1, 2, 1, 1, 1, 1]
Parentheses strings: (((((((()))))))) () (()) ((()()()))

Depth of groups of matched nested parentheses separated by parentheses:
[8, 1, 2, 3]

Flowchart:

Flowchart: Python - Compute the depth of groups of matched nested parentheses separated by parentheses.

For more Practice: Solve these Related Problems:

  • Write a Python program to compute the nesting depth of each matched parentheses group in a string using a stack.
  • Write a Python program to iterate over a string and output a list of depths corresponding to each group of balanced parentheses.
  • Write a Python program to use recursion to track and return the depth of nested parentheses in a given string.
  • Write a Python program to calculate the maximum depth of nested parentheses and also output each group’s individual depth.

Go to:


Previous: Strange sort of list of numbers.
Next: Expand Spaces.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.