- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If every group of a is followed by a group of b of same length in Python
Suppose we have a lowercase string s with only two characters a and b. We have to check whether every group of consecutive a's is followed by group of consecutive b's of equal length.
So, if the input is like s = "abaaabbbaabbaabbab", then the output will be True, as all groups are (ab), (aaabbb), (aabb), (aabb), (ab).
To solve this, we will follow these steps −
- a_count := 0, string_len := size of s
- i := 0
- while i < string_len, do
- while i < string_len and s[i] is 'a', do
- a_count := a_count + 1
- i := i + 1
- while i < string_len and s[i] is 'b', do
- a_count := a_count - 1
- i := i + 1
- if a_count is not 0, then
- return False
- while i < string_len and s[i] is 'a', do
- return True
Example
Let us see the following implementation to get better understanding −
def solve(s): a_count = 0 string_len = len(s) i = 0 while i < string_len: while i < string_len and s[i] == 'a': a_count += 1 i += 1 while i < string_len and s[i] == 'b': a_count -= 1 i += 1 if a_count != 0: return False return True s = "abaaabbbaabbaabbab" print(solve(s))
Input
"abaaabbbaabbaabbab"
Output
True
Advertisements