Skip to content
Advertisement

Counting identical consecutive elements in a list in a continuous manner

Given a list x of number entries, I aim to find the number of identical consecutive entries, where the identical consecutive entries are taken out once counted. For example, if x = [4, 3, 1, 1, 3, 2, 4], the returned solution should be 4:

[4, 3, (1, 1), 3, 2, 4] => (two consecutive entries of 1s are counted: 2)
[4, (3, 3), 2, 4] => (two consecutive entries of 3s are counted: 4)
[4, 2, 4] => (no more consecutive entries: final solution is 4)

I can use the for loop to count the identical consecutive entries, but efficiently removing the elements and running them continuously until there are no more identical consecutive entries is where I find things tricky.

solution = 0

for i in range(len(x)-1):
    if x[i] == x[i+1]:
        solution += 2
        if x[i-1] == x[i+2]:
             solution += 2
...

where I know these recursive approaches are only applicable to particular lists. Using itertools only ‘collapses’ the length of the list, which is not something I’m looking for. Is there an optimal way to calculate the number of identical consecutive entries?

Advertisement

Answer

Use a stack. If top (last) elememt of stack is same as current element n in x, anihilate it (pop()). Otherwise, push n into stack. ans is not really needed – when the loop ends, len(x)-len(stack) is the result.

x = [4, 3, 1, 1, 3, 2, 4]
stack,ans=[],0
for n in x:
    if not stack or stack[-1]!=n:
        stack.append(n)
    else:
        ans+=2
        stack.pop()
print(ans)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement