Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to count number of characters in each bracket depth in Python
Sometimes we need to count characters at different bracket depths in a string. This problem involves parsing a string with balanced brackets "(", ")" and characters "X", then counting how many "X" characters appear at each depth level.
So, if the input is like s = "(XXX(X(XX))XX)", then the output will be [5, 1, 2]
Algorithm
To solve this, we will follow these steps ?
- Initialize depth to -1 and create an empty output list
- For each character in the string:
- If character is
"(", increment depth - If character is
")", decrement depth - If current depth equals output list length, append 0
- If character is
"X", increment count at current depth
- If character is
- Return the output list
Example
Let us see the following implementation to get better understanding ?
def solve(s):
depth = -1
out = []
for c in s:
if c == "(":
depth += 1
elif c == ")":
depth -= 1
if depth == len(out):
out.append(0)
if c == "X":
out[depth] += 1
return out
s = "(XXX(X(XX))XX)"
print(solve(s))
The output of the above code is ?
[5, 1, 2]
How It Works
The algorithm tracks the current bracket depth as it processes each character. When it encounters an opening bracket "(", it increases the depth. When it finds a closing bracket ")", it decreases the depth. For each "X" character, it increments the counter at the current depth level.
Step-by-Step Trace
For string "(XXX(X(XX))XX)":
Character | Depth | Action | Output List ----------|-------|---------------|------------ ( | 0 | depth++ | [0] X | 0 | count at [0] | [1] X | 0 | count at [0] | [2] X | 0 | count at [0] | [3] ( | 1 | depth++ | [3, 0] X | 1 | count at [1] | [3, 1] ( | 2 | depth++ | [3, 1, 0] X | 2 | count at [2] | [3, 1, 1] X | 2 | count at [2] | [3, 1, 2] ) | 1 | depth-- | [3, 1, 2] ) | 0 | depth-- | [3, 1, 2] X | 0 | count at [0] | [4, 1, 2] X | 0 | count at [0] | [5, 1, 2] ) | -1 | depth-- | [5, 1, 2]
Conclusion
This algorithm efficiently counts characters at each bracket depth using a single pass through the string. The depth tracking ensures accurate counting at nested levels, making it useful for parsing nested structures.
