- 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 a string follows a^n b^n pattern or not in Python
Suppose we have a string s we have to check whether the string is following the pattern a^nb^n or not. This is actually a string when n = 3, the string will be "aaabbb".
So, if the input is like s = "aaaaabbbbb", then the output will be True as this follows a^5b^5.
To solve this, we will follow these steps −
- size := size of s
- for i in range 0 to size - 1, do
- if s[i] is not same as 'a', then
- come out from loop
- if s[i] is not same as 'a', then
- if i * 2 is not same as size, then
- return False
- for j in range i to size - 1, do
- if s[j] is not same as 'b', then
- return False
- if s[j] is not same as 'b', then
- return True
Let us see the following implementation to get better understanding −
Example
def solve(s): size = len(s) for i in range(size): if s[i] != 'a': break if i * 2 != size: return False for j in range(i, size): if s[j] != 'b': return False return True s = "aaaaabbbbb" print(solve(s))
Input
"aaaaabbbbb"
Output
True
Advertisements