Check If every group of a is followed by a group of b of same length in Python

PythonServer Side ProgrammingProgramming

<p>Suppose we have a lowercase string s with only two characters a and b. We have to check whether every group of consecutive a&#39;s is followed by group of consecutive b&#39;s of equal length.</p><p>So, if the input is like s = &quot;abaaabbbaabbaabbab&quot;, then the output will be True, as all groups are (ab), (aaabbb), (aabb), (aabb), (ab).</p><p>To solve this, we will follow these steps &minus;</p><ul class="list"><li>a_count := 0, string_len := size of s</li><li>i := 0</li><li>while i &lt; string_len, do<ul class="list"><li>while i &lt; string_len and s[i] is &#39;a&#39;, do<ul class="list"><li>a_count := a_count + 1</li><li>i := i + 1</li></ul></li><li>while i &lt; string_len and s[i] is &#39;b&#39;, do<ul class="list"><li>a_count := a_count - 1</li><li>i := i + 1</li></ul></li><li>if a_count is not 0, then<ul class="list"><li>return False</li></ul></li></ul></li><li>return True</li></ul><h2>Example</h2><p>Let us see the following implementation to get better understanding &minus;</p><p><a class="demo" href="http://tpcg.io/r5VtlUpW" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">def solve(s): &nbsp; &nbsp;a_count = 0 &nbsp; &nbsp;string_len = len(s) &nbsp; &nbsp;i = 0 &nbsp; &nbsp;while i &lt; string_len: &nbsp; &nbsp; &nbsp; while i &lt; string_len and s[i] == &#39;a&#39;: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;a_count += 1 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;i += 1 &nbsp; &nbsp; &nbsp; while i &lt; string_len and s[i] == &#39;b&#39;: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;a_count -= 1 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;i += 1 &nbsp; &nbsp; &nbsp; if a_count != 0: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return False &nbsp; &nbsp;return True s = &quot;abaaabbbaabbaabbab&quot; print(solve(s))</pre><h2>Input</h2><pre class="result notranslate">&quot;abaaabbbaabbaabbab&quot;</pre><h2>Output</h2><pre class="result notranslate">True</pre>
raja
Updated on 18-Jan-2021 12:27:59

Advertisements