Skip to content
Advertisement

Count adjacent repeated elements in the list

What I expect:

input = ["a", "a", "a", "c", "b", "b", "c"]
output: ['a', '3', 'c', '1', 'b', '2', 'c', '1']

My code:

lst = ["a", "a", "a", "c", "b", "b", "c"]

result = []
index = 0

while(index < len(lst)-1):
    count = 1
    result.append(lst[index])
    while(lst[index] == lst[index+1]):
        count += 1
        index += 1

    result.append(str(count))
    index += 1
    print("step: ", result)

print("result: ", result) 

What I got:

step:  ['a', '3']
step:  ['a', '3', 'c', '1']
step:  ['a', '3', 'c', '1', 'b', '2']
result:  ['a', '3', 'c', '1', 'b', '2']

I could not count the last element correctly.

Here is another input:

['East', 'East', 'East', 'East', 'East', 'West', 'West', 'West', 'West', 'North', 'South', 'West', 'West', 'West', 'North', 'South', 'West', 'West', 'West', 'North', 'North', 'West', 'West', 'West', 'East', 'East', 'East', 'East', 'East', 'East', 'East', 'East', 'East', 'East', 'East', 'East', 'South', 'South', 'East', 'East', 'East', 'North', 'North', 'East', 'East', 'South', 'South', 'South', 'South', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West', 'West']

Advertisement

Answer

Your code is not accounting for the last item in the list because you are avoiding an index out-of-bound error in the evaluation of lst[index] == lst[index+1] by iterating over a range of one less than the length of the list with while(index < len(lst)-1):.

An easy workaround without having to duplicate the counting code after the loop is to unconditionally append a dummy item to the list first, and optionally pop it after the counting is done, if you still need the original list intact. The example below uses an instance of object as a dummy item because it helps make sure that the last evaluation of lst[index] == lst[index+1] would never be True:

lst.append(object()) # append a dummy item first
while(index < len(lst)-1):
    count = 1
    result.append(lst[index])
    while(lst[index] == lst[index+1]):
        count += 1
        index += 1

    result.append(str(count))
    index += 1
    print("step: ", result)

lst.pop() # add this line only if you still need the original lst for later use
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement