loneliness
loneliness

Reputation: 43

For loop unexpected result

I was trying to make a function that takes an iterable as an argument and returns a list of the iterable given but without values that are the same next to each other.

e.g my_function("1112334512") would return ["1", "2", "3", "4", "5", "1", "2"].

I don't want it to remove duplicate values in the iterable, I want it to remove values that have their same value that is next to it. (e.g "AAABA" finished result would be "ABA")

def my_function(iterable):
    iterable_1 = []
    for item in iterable:
        iterable_1.append(item)

    count = 0
    for item in iterable_1:
        # Tempoary count = count + 1
        if iterable_1[count] == iterable_1[count + 1]:
            iterable_1.pop(count)
        else:
            count += 1

    return iterable_1

My problem is that when I thought that this finally did it, the result of running my_function("AAAABBBCCDAABBB") returned: ['A', 'B', 'C', 'D', 'A', 'A', 'B', 'B', 'B'], which in theory did the correct thing up to D where I think the for loop ended.

My question is why? And if it is not the loop then what is it?

Upvotes: 3

Views: 115

Answers (2)

lonsty
lonsty

Reputation: 195

Your code should like this, because iterable_1 changed after you pop a value out.

def my_function(iterable):
    iterable_1 = []
    for item in iterable:
        iterable_1.append(item)

    count = 0
    length = len(iterable_1)

    for item in range(length):
        try:
            if iterable_1[count] == iterable_1[count + 1]:
                iterable_1.pop(count)
            else:
                count += 1
        except IndexError:
            pass

    return iterable_1

Upvotes: 0

Lydia van Dyke
Lydia van Dyke

Reputation: 2526

To me your method seems overly complex for the task. How about

def my_function(iterable):
    result = []
    for e in iterable:
        if not result or result[-1] != e:
            result.append(e)
    return result

Upvotes: 6

Related Questions