[Tutor] problem update

Christopher Spears cspears2002 at yahoo.com
Thu Mar 4 19:01:25 EST 2004


I've been hacking away at my problem, and I have made
some progress.  Here is the original problem:

Using the UserList module, create a class called
Ulist, and override the __add__, append, and extend
methods so that duplicate values will not be added to
the list by any of these operations.

Here is the script so far:

import UserList

class UList(UserList.UserList):
    def __init__(self, initlist=None):
        UserList.UserList.__init__(self, initlist)

    def __add__(self, other):
        for s in range(len(self)):
            if self[s] not in other:
                if isinstance(other, UList):
                    return self.__class__(self.data +
other.data)
                elif isinstance(other,
type(self.data)):
                    return self.__class__(self.data +
other)
                else:
                    return self.__class__(self.data +
list(other))
            else:
                print "Found duplicate %s" %self[s]

When I run the code, I get the following results:

>>> import UList
>>> list = [1,2,3]
>>> list1 = [1,4,5]
>>> a = UList.UList(list)
>>> b = UList.UList(list1)
>>> a
[1, 2, 3]
>>> b
[1, 4, 5]
>>> a + b
Found duplicate 1
[1, 2, 3, 1, 4, 5]

My code is only working halfway.  The script detects a
duplicate but adds the duplicates in the lists anyway,
so the next step is to modify the script so that
duplicates will be eliminated.  Any hints?  My guess
is that 1 is not added in beginning of the loop
because the script detects it.  Therefore, 1 must be
added when 2 is being compared against b.
 
-Chris



More information about the Tutor mailing list