14. remove_duplicates get error result with two loop


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/4?curriculum_id=4f89dab3d788890003000096

Oops, try again.
remove_duplicates([4, 5, 5, 4]) returned [4, 5, 5, 4, 4] instead of [4, 5]

I know "not in" function in hint, it's powerful, but I still don't understand why my code get error result.
Anyone able to suggest?


def remove_duplicates(numbers):
    list_result=[]
    list_result.append(numbers[0])
    for x in numbers:
        len_list_result=len(list_result)
        index=0
        while index<len_list_result:
            if x!=list_result[index]:
                list_result.append(x)
            index+=1         
    return list_result


#2

in relies upon something being in the object. not in refers to the opposite. Give it a minute. The outcome is opposite to the input.

Any expression that contains not is an inverter. The opposite state is always returned.


#3

You mean I can not use "if x!=list_result[index]:" to check?


#5

Chances are there is something going on in your code that is allowing duplicates to be appended.

def remove_duplicates(numbers):
    list_result=[]
    list_result.append(numbers[0])
    for x in numbers:
        len_list_result = len(list_result)
        index=0
        while index < len_list_result:
            print "x = %d" % x
            print "l = %d" % list_result[index]
            if x != list_result[index]:  
                list_result.append(x)
                print list_result    
            index+=1    
    return list_result

Output
> remove_duplicates([4,5,5,4])
x = 4
l = 4
x = 5
l = 4
[4, 5]
x = 5
l = 5
x = 5
l = 4
[4, 5, 5]
x = 5
l = 5
x = 5
l = 5
x = 4
l = 4
x = 4
l = 5
[4, 5, 5, 4]
x = 4
l = 5
[4, 5, 5, 4, 4]
x = 4
l = 4
x = 4
l = 4
=> [4, 5, 5, 4, 4]

Changing up the conditional in the loop and using a flag to signal duplicate exists gives us the correct output:

def remove_duplicates(numbers):
    list_result=[]
    list_result.append(numbers[0])
    for x in numbers:
        index=0
        flag = True
        while index < len(list_result):
            print "x = %d" % x
            print "l = %d" % list_result[index]
            if x == list_result[index]:
                flag = False
            index+=1     
        if flag:
            list_result.append(x)
            print list_result    
    return list_result

Output

> remove_duplicates([4,5,5,4])
x = 4
l = 4
x = 5
l = 4
[4, 5]
x = 5
l = 4
x = 5
l = 5
x = 4
l = 4
x = 4
l = 5
=> [4, 5]


#6

Thank for your help~
I know what happen in my code~


#10