简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM