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]
Visual Presentation:
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:
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.
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-98.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics