Remove_duplicate


#1

I used the count function from a previous exercise in the "if" statement of my code and it seems to work well for all lists except [88,5,7,88,93,4] where I get the following error:

"Oops, try again. remove_duplicates([88, 5, 7, 88, 93, 4]) returned [88, 5, 7] instead of [88, 4, 5, 93, 7]"

This is the code I used:

def count(sequence,item):
    total = 0
    for i in sequence:
        if i == item:
            total += 1
    return total

def remove_duplicates(x):
    new = []
    for i in x:
        if i in new:
            break
        elif count(x,i) == 1:
            new.append(i)
        elif count(x,i) > 1:
            new.append(i)
    return new

Your help would be appreciated. Thank You!


#2

here:

        if i in new:
            break

break will break the loop, why would you want to do this?


#3

So that if the word is already present in the list, the loop will stop?
Ah, I realised my mistake. Though could you tell me how it worked with other lists fed to it by codecademy?


#4

yes, exactly, well this are the test cases:

tests = [
    [],
    [1],
    [4,5,5,4],
    [6,8,122,2,18],
    [6,6,6,6,6],
    [88,5,7,88,93,4],
    [5,3,5,9,9]
]

[4,5,5,4] is no problem, by the time your loop breaks, 4 an 5 are already added to the new list

the next case has no duplicate values

for [6,6,6,6,6] applies the same, the 6 is already added to new list before break is reached


#5

Thank you for your reply. I was able to understand the problem and rectify it.


#6