14. Remove Duplicates - code works, but I dont' understand why


#1



I worked through removing duplicates, and I don't understand if the code I wrote actually works or if the website just didn't run it through enough tests to find where it breaks down.


It does not have an error message.


I don't understand why numbers == numbers actually works.


def remove_duplicates(lst):
    work_cup = []
    for numbers in lst:
        if numbers == numbers:
            return numbers
        elif numbers not in lst:
            work_cup.append(numbers)
    return work_cup


#2

The lesson check is not exhaustive, and may only examine required elements, not results or syntax errors. Obviously the code does not work as expected.

Think of an algorithm in this way. We iterate over the list in any order and check if it is in work_cup. If it isn't, then add it, otherwise ignore and continue. Once the main list has been iterated, the working list will be populated with discrete items which can then be returned.


#3

Right, so just add to cup if number is not in cup. Thanks!


#4

The side lesson to this is creating a set from a sample space. Think of it as the horizontal axis of a frequency chart, or histogram. A program could use this set to plot all the x-points where y equals zero.

Consider an election with a number of names on the ballot and a list of all the votes. It will contain many duplicate terms, the names of the candidates. This program gleans only the names of the candidates. That will make up our horizontal axis. Now we pile the vote count on those markers.


#5

@parentalconsent I think your code works without the elif statement, ie. you can delete and replace the code block under the if statement with the one under elif statement.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.