Python - Count the duplicate seq element in array
<p>How to solve this</p>

<pre><code>Input: 2
Array = [2,1,3,2,2,2,1,2,2]
Result : 3 (Max of count of seq of 2)
</code></pre>

<p>I just simply used the for loop, it works fine. But is there any other efficient way?</p>

<pre><code>for i in array:
    if i == input:
        Cnt = Cnt + 1
        if Cnt &gt; Result:
            Result = Cnt;
    else:
      Cnt = 0
</code></pre>

<p>You could seriously abuse side effects in a comprehension :-) :</p>

<pre><code>Input = 2
Array = [2,1,3,2,2,2,1,2,2]
r = []
Result = max([(r.append(1),len(r))[1] if x==Input else (r.clear(),0)[1] for x in Array])
</code></pre>

<p>.</p>

<p>That kind of rigamarole wouldn't be necessary if Python allowed assignments in expressions:</p>

<pre><code>r = 0
Result = max([++r if x==Input else r=0 for x in Array])   # What we want, but NOT valid Python!
</code></pre>

<p>Note that a generator expression could be used instead of the list comprehension if you don't want to look at the intermediate result.  For the toy Array it doesn't matter, but for an Array of hundreds of thousands of elements the generator saves memory.</p>

python list