
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to count number of characters in each bracket depth in Python
Suppose we have a string s which consists of only three characters "X", "(", and ")". The string has balanced brackets and in between some "X"s are there along with possibly nested brackets may also there recursively. We have to find the number of "X"s at each depth of brackets in s, starting from the shallowest depth to the deepest depth.
So, if the input is like s = "(XXX(X(XX))XX)", then the output will be [5, 1, 2]
To solve this, we will follow these steps −
- depth := -1
- out := a new list
- for each c in s, do
- if c is same as "(", then
- depth := depth + 1
- otherwise when c is same as ")", then
- depth := depth - 1
- if depth is same as size of out , then
- insert 0 at the end of out
- if c is same as "X", then
- out[depth] := out[depth] + 1
- if c is same as "(", then
- return out
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))
Input
"(XXX(X(XX))XX)"
Output
[5, 1, 2]
- Related Questions & Answers
- Python Program to Count Number of Lowercase Characters in a String
- Count Number of Lowercase Characters in a String in Python Program
- Program to count number of similar substrings for each query in Python
- Program to count number of distinct characters of every substring of a string in Python
- C++ program to count number of stairways and number of steps in each stairways
- Python Pandas - Count the number of rows in each group
- Java program to count the characters in each word in a given sentence
- Program to count number of unique palindromes we can make using string characters in Python
- Print Bracket Number in C++
- C program to count characters, lines and number of words in a file
- Program to count number of palindromic substrings in Python
- Program to count number of unhappy friends in Python
- Program to count number of homogenous substrings in Python
- Program to count number of nice subarrays in Python
- Count the Number of matching characters in a pair of string in Python
Advertisements