Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop unexpected result

Tags:

python

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?

like image 456
loneliness Avatar asked Jul 21 '26 14:07

loneliness


1 Answers

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
like image 97
Lydia van Dyke Avatar answered Jul 23 '26 04:07

Lydia van Dyke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!