Python: Compute the depth of groups of matched nested parentheses separated by parentheses
Python Programming Puzzles: Exercise-98 with Solution
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]
Pictorial Presentation:

Sample Solution:
Python Code:
#License: https://bit.ly/3oLErEI
def test(parens):
return [len(s.split(')')[0]) for s in parens.split()]
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:

Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Strange sort of list of numbers.
Next: Expand Spaces.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join