faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 4 people (100%) answered Yes
Recently 3 of 3 people (100%) answered Yes


Set class

Jul 5th, 2000 10:01
Nathan Wallace, Hans Nowak, Snippet 204, Python Snippet Support Team

Packages: oop;new_datatypes
# set.py
""" A generic Set type. A Set can be described as a list with only unique
    elements. Furthermore, the order of elements in a Set is not (supposed
    to be) important, much like the key values of a dictionary.
class Set:
    def __init__(self, other=None):
        if type(other) == type([]):
            self.data = []
        elif isinstance(other, Set):
            # copy constructor
            self.data = other.data[:]
        elif other == None:
            self.data = []  # empty
            self.data = [other]
    def clone(self, other):
        """Return a clone of this Set."""
        assert isinstance(other, Set)
        clone = Set()
        clone.data = self.data[:]
        return clone
    """ Adding, removing and checking elements """
    def add(self, elem):
        if not elem in self.data:
    def append(self, elem): # alias
    def remove(self, elem):
        if elem in self.data:
    def addFromList(self, list):
        for item in list:
            if not item in self.data: self.data.append(item)
    def hasElement(self, elem):
        return elem in self.data
    def sort(self):
    """ Operations for multiple Sets """
    def intersection(self, other):
        """Return the intersection of self and other."""
        assert isinstance(other, Set)
        result = Set()
        for item in self.data:
            if item in other.data:
        return result
    def addition(self, other):
        result = Set(self.data)
        for item in other.data:
        return result
    def difference(self, other):
        result = Set()
        for item in self.data:
            if not item in other.data: result.add(item)
        for item in other.data:
            if not item in self.data: result.add(item)
        return result
    """ Operators """
    def __getitem__(self, index):
        return self.data[index]
    def __getslice__(self, start, stop):
        return self.data[start:stop]
    def __and__(self, other):
        return self.intersection(other)
    def __or__(self, other):
        return self.addition(other)
    def __xor__(self, other):
        return self.difference(other)
    def __add__(self, obj):
    def __sub__(self, obj):
    """ Representation """
    def __repr__(self):
        str = "Set " + repr(self.data)
        return str
# I think this Set class can also be implemented using a dict, storing the
# elements as key values, thus guaranteeing that each element is unique.
# This *could* be useful if this approach leads to a better performance. But
# I'm not sure.
if __name__ == "__main__":
    set1 = Set([1, 3, 5, 7, 9])
    set2 = Set([2, 4, 6, 8, 10])
    set3 = Set([1,2,3,4,5])
    set4 = Set()
    print set1, set2, set3, set4
    set_2i3 = set2.intersection(set3)
    print 'Intersection:', set_2i3
    set_2d3 = set2.difference(set3) ; set_2d3.sort()
    print 'Difference:', set_2d3
    set_2a3 = set2.addition(set3) ; set_2a3.sort()
    print 'Addition:', set_2a3
    print 'With operators:' 
    print set1 & set3
    print set1 | set3
    print set1 ^ set3